rx-player 4.4.0 → 4.4.1-dev.2025101500
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/CHANGELOG.md +7 -0
- package/README.md +52 -113
- package/VERSION +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_worker.d.ts.map +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_worker.js +1 -1
- package/dist/commonjs/core/{main/common → entry}/FreezeResolver.d.ts +3 -3
- package/dist/commonjs/core/entry/FreezeResolver.d.ts.map +1 -0
- package/dist/commonjs/core/{main/common → entry}/FreezeResolver.js +3 -3
- package/dist/{es2017/core/main/worker → commonjs/core/entry}/content_preparer.d.ts +22 -15
- package/dist/commonjs/core/entry/content_preparer.d.ts.map +1 -0
- package/dist/commonjs/core/{main/worker → entry}/content_preparer.js +62 -64
- package/dist/{es2017/core/main/common → commonjs/core/entry}/content_time_boundaries_observer.d.ts +5 -5
- package/dist/commonjs/core/entry/content_time_boundaries_observer.d.ts.map +1 -0
- package/dist/commonjs/core/{main/common → entry}/content_time_boundaries_observer.js +6 -6
- package/dist/commonjs/core/entry/core_entry.d.ts +36 -0
- package/dist/commonjs/core/entry/core_entry.d.ts.map +1 -0
- package/dist/commonjs/core/{main/worker/worker_main.js → entry/core_entry.js} +192 -153
- package/dist/commonjs/core/{main/worker/worker_text_displayer_interface.d.ts → entry/core_text_displayer_interface.d.ts} +11 -11
- package/dist/commonjs/core/entry/core_text_displayer_interface.d.ts.map +1 -0
- package/dist/commonjs/core/{main/worker/worker_text_displayer_interface.js → entry/core_text_displayer_interface.js} +22 -22
- package/dist/commonjs/core/{main/common → entry}/create_content_time_boundaries_observer.d.ts +6 -6
- package/dist/commonjs/core/entry/create_content_time_boundaries_observer.d.ts.map +1 -0
- package/dist/commonjs/core/{main/common → entry}/create_content_time_boundaries_observer.js +1 -1
- package/dist/commonjs/core/{main/common → entry}/get_buffered_data_per_media_buffer.d.ts +4 -4
- package/dist/commonjs/core/entry/get_buffered_data_per_media_buffer.d.ts.map +1 -0
- package/dist/commonjs/core/{main/common → entry}/get_buffered_data_per_media_buffer.js +1 -1
- package/dist/{es2017/core/main/common → commonjs/core/entry}/get_thumbnail_data.d.ts +3 -3
- package/dist/commonjs/core/entry/get_thumbnail_data.d.ts.map +1 -0
- package/dist/commonjs/core/{main/common → entry}/get_thumbnail_data.js +2 -2
- package/dist/commonjs/core/entry/index.d.ts +5 -0
- package/dist/commonjs/core/entry/index.d.ts.map +1 -0
- package/dist/commonjs/core/entry/index.js +4 -0
- package/dist/{es2017/core/main/common → commonjs/core/entry}/synchronize_sinks_on_observation.d.ts +2 -2
- package/dist/commonjs/core/entry/synchronize_sinks_on_observation.d.ts.map +1 -0
- package/dist/commonjs/core/{main/worker → entry}/track_choice_setter.d.ts +4 -4
- package/dist/commonjs/core/entry/track_choice_setter.d.ts.map +1 -0
- package/dist/commonjs/core/{main/worker → entry}/track_choice_setter.js +4 -4
- package/dist/commonjs/core/entry/utils.d.ts +3 -0
- package/dist/commonjs/core/entry/utils.d.ts.map +1 -0
- package/dist/commonjs/core/entry/utils.js +11 -0
- package/dist/commonjs/core/stream/orchestrator/stream_orchestrator.d.ts.map +1 -1
- package/dist/commonjs/core/stream/orchestrator/stream_orchestrator.js +17 -0
- package/dist/commonjs/core/types.d.ts +519 -1
- package/dist/commonjs/core/types.d.ts.map +1 -1
- package/dist/commonjs/core/types.js +1 -0
- package/dist/commonjs/experimental/features/local.d.ts.map +1 -1
- package/dist/commonjs/experimental/features/local.js +7 -1
- package/dist/commonjs/experimental/features/metaplaylist.d.ts.map +1 -1
- package/dist/commonjs/experimental/features/metaplaylist.js +7 -1
- package/dist/commonjs/experimental/features/multi_thread.d.ts.map +1 -1
- package/dist/commonjs/experimental/features/multi_thread.js +6 -2
- package/dist/commonjs/features/features_object.js +1 -1
- package/dist/commonjs/features/list/dash.d.ts.map +1 -1
- package/dist/commonjs/features/list/dash.js +7 -1
- package/dist/commonjs/features/list/dash_wasm.d.ts.map +1 -1
- package/dist/commonjs/features/list/dash_wasm.js +7 -1
- package/dist/commonjs/features/list/media_source_main.d.ts.map +1 -1
- package/dist/commonjs/features/list/media_source_main.js +7 -1
- package/dist/commonjs/features/list/smooth.d.ts.map +1 -1
- package/dist/commonjs/features/list/smooth.js +7 -1
- package/dist/commonjs/features/types.d.ts +20 -4
- package/dist/commonjs/features/types.d.ts.map +1 -1
- package/dist/commonjs/main_thread/api/public_api.d.ts.map +1 -1
- package/dist/commonjs/main_thread/api/public_api.js +39 -42
- package/dist/commonjs/main_thread/core_interface/base.d.ts +13 -0
- package/dist/commonjs/main_thread/core_interface/base.d.ts.map +1 -0
- package/dist/commonjs/main_thread/core_interface/base.js +32 -0
- package/dist/commonjs/main_thread/core_interface/monothread.d.ts +13 -0
- package/dist/commonjs/main_thread/core_interface/monothread.d.ts.map +1 -0
- package/dist/commonjs/main_thread/core_interface/monothread.js +56 -0
- package/dist/commonjs/main_thread/core_interface/multithread.d.ts +25 -0
- package/dist/commonjs/main_thread/core_interface/multithread.d.ts.map +1 -0
- package/dist/commonjs/main_thread/core_interface/multithread.js +67 -0
- package/dist/commonjs/main_thread/core_interface/types.d.ts +6 -0
- package/dist/commonjs/main_thread/core_interface/types.d.ts.map +1 -0
- package/dist/commonjs/main_thread/core_interface/types.js +2 -0
- package/dist/commonjs/main_thread/init/media_source_content_initializer.d.ts +166 -108
- package/dist/commonjs/main_thread/init/media_source_content_initializer.d.ts.map +1 -1
- package/dist/commonjs/main_thread/init/media_source_content_initializer.js +1492 -919
- package/dist/commonjs/main_thread/init/utils/create_core_playback_observer.d.ts.map +1 -1
- package/dist/commonjs/main_thread/init/utils/create_core_playback_observer.js +2 -1
- package/dist/commonjs/main_thread/init/utils/update_manifest_codec_support.d.ts +1 -1
- package/dist/commonjs/main_thread/init/utils/update_manifest_codec_support.d.ts.map +1 -1
- package/dist/commonjs/main_thread/types.d.ts +537 -0
- package/dist/commonjs/main_thread/types.d.ts.map +1 -1
- package/dist/commonjs/manifest/utils.d.ts.map +1 -1
- package/dist/commonjs/manifest/utils.js +18 -4
- package/dist/commonjs/mse/worker_media_source_interface.d.ts +2 -2
- package/dist/commonjs/mse/worker_media_source_interface.d.ts.map +1 -1
- package/dist/commonjs/mse/worker_media_source_interface.js +12 -12
- package/dist/commonjs/parsers/manifest/smooth/create_parser.d.ts +1 -1
- package/dist/commonjs/parsers/manifest/smooth/create_parser.d.ts.map +1 -1
- package/dist/commonjs/parsers/manifest/smooth/create_parser.js +31 -27
- package/dist/commonjs/parsers/manifest/smooth/parse_C_nodes.d.ts +3 -2
- package/dist/commonjs/parsers/manifest/smooth/parse_C_nodes.d.ts.map +1 -1
- package/dist/commonjs/parsers/manifest/smooth/parse_C_nodes.js +16 -7
- package/dist/commonjs/parsers/manifest/smooth/parse_protection_node.d.ts +3 -2
- package/dist/commonjs/parsers/manifest/smooth/parse_protection_node.d.ts.map +1 -1
- package/dist/commonjs/parsers/manifest/smooth/parse_protection_node.js +37 -6
- package/dist/commonjs/parsers/manifest/smooth/utils/parseBoolean.d.ts +1 -1
- package/dist/commonjs/parsers/manifest/smooth/utils/parseBoolean.d.ts.map +1 -1
- package/dist/commonjs/parsers/manifest/smooth/utils/reduceChildren.d.ts +3 -2
- package/dist/commonjs/parsers/manifest/smooth/utils/reduceChildren.d.ts.map +1 -1
- package/dist/commonjs/parsers/manifest/smooth/utils/reduceChildren.js +28 -5
- package/dist/{es2017/playback_observer/worker_playback_observer.d.ts → commonjs/playback_observer/core_playback_observer.d.ts} +8 -8
- package/dist/commonjs/playback_observer/core_playback_observer.d.ts.map +1 -0
- package/dist/commonjs/playback_observer/{worker_playback_observer.js → core_playback_observer.js} +13 -13
- package/dist/commonjs/transports/smooth/pipelines.d.ts.map +1 -1
- package/dist/commonjs/transports/smooth/pipelines.js +25 -3
- package/dist/commonjs/worker_entry_point.js +62 -2
- package/dist/es2017/__GENERATED_CODE/embedded_worker.d.ts.map +1 -1
- package/dist/es2017/__GENERATED_CODE/embedded_worker.js +1 -1
- package/dist/es2017/core/{main/common → entry}/FreezeResolver.d.ts +3 -3
- package/dist/es2017/core/entry/FreezeResolver.d.ts.map +1 -0
- package/dist/es2017/core/{main/common → entry}/FreezeResolver.js +3 -3
- package/dist/{commonjs/core/main/worker → es2017/core/entry}/content_preparer.d.ts +22 -15
- package/dist/es2017/core/entry/content_preparer.d.ts.map +1 -0
- package/dist/es2017/core/{main/worker → entry}/content_preparer.js +53 -55
- package/dist/{commonjs/core/main/common → es2017/core/entry}/content_time_boundaries_observer.d.ts +5 -5
- package/dist/es2017/core/entry/content_time_boundaries_observer.d.ts.map +1 -0
- package/dist/es2017/core/{main/common → entry}/content_time_boundaries_observer.js +6 -6
- package/dist/es2017/core/entry/core_entry.d.ts +36 -0
- package/dist/es2017/core/entry/core_entry.d.ts.map +1 -0
- package/dist/es2017/core/{main/worker/worker_main.js → entry/core_entry.js} +153 -114
- package/dist/es2017/core/{main/worker/worker_text_displayer_interface.d.ts → entry/core_text_displayer_interface.d.ts} +11 -11
- package/dist/es2017/core/entry/core_text_displayer_interface.d.ts.map +1 -0
- package/dist/es2017/core/{main/worker/worker_text_displayer_interface.js → entry/core_text_displayer_interface.js} +10 -10
- package/dist/es2017/core/{main/common → entry}/create_content_time_boundaries_observer.d.ts +6 -6
- package/dist/es2017/core/entry/create_content_time_boundaries_observer.d.ts.map +1 -0
- package/dist/es2017/core/{main/common → entry}/create_content_time_boundaries_observer.js +1 -1
- package/dist/es2017/core/{main/common → entry}/get_buffered_data_per_media_buffer.d.ts +4 -4
- package/dist/es2017/core/entry/get_buffered_data_per_media_buffer.d.ts.map +1 -0
- package/dist/es2017/core/{main/common → entry}/get_buffered_data_per_media_buffer.js +1 -1
- package/dist/{commonjs/core/main/common → es2017/core/entry}/get_thumbnail_data.d.ts +3 -3
- package/dist/es2017/core/entry/get_thumbnail_data.d.ts.map +1 -0
- package/dist/es2017/core/{main/common → entry}/get_thumbnail_data.js +2 -2
- package/dist/es2017/core/entry/index.d.ts +5 -0
- package/dist/es2017/core/entry/index.d.ts.map +1 -0
- package/dist/es2017/core/entry/index.js +2 -0
- package/dist/{commonjs/core/main/common → es2017/core/entry}/synchronize_sinks_on_observation.d.ts +2 -2
- package/dist/es2017/core/entry/synchronize_sinks_on_observation.d.ts.map +1 -0
- package/dist/es2017/core/{main/worker → entry}/track_choice_setter.d.ts +4 -4
- package/dist/es2017/core/entry/track_choice_setter.d.ts.map +1 -0
- package/dist/es2017/core/{main/worker → entry}/track_choice_setter.js +4 -4
- package/dist/es2017/core/entry/utils.d.ts +3 -0
- package/dist/es2017/core/entry/utils.d.ts.map +1 -0
- package/dist/es2017/core/entry/utils.js +8 -0
- package/dist/es2017/core/stream/orchestrator/stream_orchestrator.d.ts.map +1 -1
- package/dist/es2017/core/stream/orchestrator/stream_orchestrator.js +18 -1
- package/dist/es2017/core/types.d.ts +519 -1
- package/dist/es2017/core/types.d.ts.map +1 -1
- package/dist/es2017/core/types.js +1 -0
- package/dist/es2017/experimental/features/local.d.ts.map +1 -1
- package/dist/es2017/experimental/features/local.js +7 -1
- package/dist/es2017/experimental/features/metaplaylist.d.ts.map +1 -1
- package/dist/es2017/experimental/features/metaplaylist.js +7 -1
- package/dist/es2017/experimental/features/multi_thread.d.ts.map +1 -1
- package/dist/es2017/experimental/features/multi_thread.js +6 -2
- package/dist/es2017/features/features_object.js +1 -1
- package/dist/es2017/features/list/dash.d.ts.map +1 -1
- package/dist/es2017/features/list/dash.js +7 -1
- package/dist/es2017/features/list/dash_wasm.d.ts.map +1 -1
- package/dist/es2017/features/list/dash_wasm.js +7 -1
- package/dist/es2017/features/list/media_source_main.d.ts.map +1 -1
- package/dist/es2017/features/list/media_source_main.js +7 -1
- package/dist/es2017/features/list/smooth.d.ts.map +1 -1
- package/dist/es2017/features/list/smooth.js +7 -1
- package/dist/es2017/features/types.d.ts +20 -4
- package/dist/es2017/features/types.d.ts.map +1 -1
- package/dist/es2017/main_thread/api/public_api.d.ts.map +1 -1
- package/dist/es2017/main_thread/api/public_api.js +40 -43
- package/dist/es2017/main_thread/core_interface/base.d.ts +13 -0
- package/dist/es2017/main_thread/core_interface/base.d.ts.map +1 -0
- package/dist/es2017/main_thread/core_interface/base.js +28 -0
- package/dist/es2017/main_thread/core_interface/monothread.d.ts +13 -0
- package/dist/es2017/main_thread/core_interface/monothread.d.ts.map +1 -0
- package/dist/es2017/main_thread/core_interface/monothread.js +32 -0
- package/dist/es2017/main_thread/core_interface/multithread.d.ts +25 -0
- package/dist/es2017/main_thread/core_interface/multithread.d.ts.map +1 -0
- package/dist/es2017/main_thread/core_interface/multithread.js +45 -0
- package/dist/es2017/main_thread/core_interface/types.d.ts +6 -0
- package/dist/es2017/main_thread/core_interface/types.d.ts.map +1 -0
- package/dist/es2017/main_thread/core_interface/types.js +1 -0
- package/dist/es2017/main_thread/init/media_source_content_initializer.d.ts +166 -108
- package/dist/es2017/main_thread/init/media_source_content_initializer.d.ts.map +1 -1
- package/dist/es2017/main_thread/init/media_source_content_initializer.js +1405 -760
- package/dist/es2017/main_thread/init/utils/create_core_playback_observer.d.ts.map +1 -1
- package/dist/es2017/main_thread/init/utils/create_core_playback_observer.js +2 -1
- package/dist/es2017/main_thread/init/utils/update_manifest_codec_support.d.ts +1 -1
- package/dist/es2017/main_thread/init/utils/update_manifest_codec_support.d.ts.map +1 -1
- package/dist/es2017/main_thread/types.d.ts +537 -0
- package/dist/es2017/main_thread/types.d.ts.map +1 -1
- package/dist/es2017/manifest/utils.d.ts.map +1 -1
- package/dist/es2017/manifest/utils.js +16 -4
- package/dist/es2017/mse/worker_media_source_interface.d.ts +2 -2
- package/dist/es2017/mse/worker_media_source_interface.d.ts.map +1 -1
- package/dist/es2017/mse/worker_media_source_interface.js +12 -12
- package/dist/es2017/parsers/manifest/smooth/create_parser.d.ts +1 -1
- package/dist/es2017/parsers/manifest/smooth/create_parser.d.ts.map +1 -1
- package/dist/es2017/parsers/manifest/smooth/create_parser.js +31 -27
- package/dist/es2017/parsers/manifest/smooth/parse_C_nodes.d.ts +3 -2
- package/dist/es2017/parsers/manifest/smooth/parse_C_nodes.d.ts.map +1 -1
- package/dist/es2017/parsers/manifest/smooth/parse_C_nodes.js +16 -7
- package/dist/es2017/parsers/manifest/smooth/parse_protection_node.d.ts +3 -2
- package/dist/es2017/parsers/manifest/smooth/parse_protection_node.d.ts.map +1 -1
- package/dist/es2017/parsers/manifest/smooth/parse_protection_node.js +15 -6
- package/dist/es2017/parsers/manifest/smooth/utils/parseBoolean.d.ts +1 -1
- package/dist/es2017/parsers/manifest/smooth/utils/parseBoolean.d.ts.map +1 -1
- package/dist/es2017/parsers/manifest/smooth/utils/reduceChildren.d.ts +3 -2
- package/dist/es2017/parsers/manifest/smooth/utils/reduceChildren.d.ts.map +1 -1
- package/dist/es2017/parsers/manifest/smooth/utils/reduceChildren.js +6 -5
- package/dist/{commonjs/playback_observer/worker_playback_observer.d.ts → es2017/playback_observer/core_playback_observer.d.ts} +8 -8
- package/dist/es2017/playback_observer/core_playback_observer.d.ts.map +1 -0
- package/dist/es2017/playback_observer/{worker_playback_observer.js → core_playback_observer.js} +2 -2
- package/dist/es2017/transports/smooth/pipelines.d.ts.map +1 -1
- package/dist/es2017/transports/smooth/pipelines.js +25 -3
- package/dist/es2017/worker_entry_point.js +62 -2
- package/dist/rx-player.js +21882 -19021
- package/dist/rx-player.min.js +20 -20
- package/dist/worker.js +8 -8
- package/package.json +1 -1
- package/src/README.md +88 -198
- package/src/__GENERATED_CODE/embedded_worker.ts +1 -1
- package/src/core/{main/common → entry}/FreezeResolver.ts +7 -7
- package/src/core/{main → entry}/README.md +1 -1
- package/src/core/{main/worker → entry}/content_preparer.ts +77 -76
- package/src/core/{main/common → entry}/content_time_boundaries_observer.ts +10 -10
- package/src/core/{main/worker/worker_main.ts → entry/core_entry.ts} +223 -149
- package/src/core/{main/worker/worker_text_displayer_interface.ts → entry/core_text_displayer_interface.ts} +26 -26
- package/src/core/{main/common → entry}/create_content_time_boundaries_observer.ts +7 -7
- package/src/core/{main/common → entry}/get_buffered_data_per_media_buffer.ts +6 -6
- package/src/core/{main/common → entry}/get_thumbnail_data.ts +5 -5
- package/src/core/entry/index.ts +4 -0
- package/src/core/{main/common → entry}/synchronize_sinks_on_observation.ts +2 -2
- package/src/core/{main/worker → entry}/track_choice_setter.ts +7 -7
- package/src/core/entry/utils.ts +11 -0
- package/src/core/stream/orchestrator/stream_orchestrator.ts +26 -1
- package/src/core/types.ts +631 -3
- package/src/experimental/features/__tests__/local.test.ts +11 -2
- package/src/experimental/features/__tests__/metaplaylist.test.ts +11 -2
- package/src/experimental/features/__tests__/multi_thread.test.ts +8 -3
- package/src/experimental/features/local.ts +7 -1
- package/src/experimental/features/metaplaylist.ts +7 -1
- package/src/experimental/features/multi_thread.ts +6 -2
- package/src/features/features_object.ts +1 -1
- package/src/features/list/__tests__/dash.test.ts +12 -3
- package/src/features/list/__tests__/smooth.test.ts +11 -2
- package/src/features/list/dash.ts +7 -1
- package/src/features/list/dash_wasm.ts +7 -1
- package/src/features/list/media_source_main.ts +7 -1
- package/src/features/list/smooth.ts +7 -1
- package/src/features/types.ts +23 -4
- package/src/main_thread/README.md +8 -0
- package/src/main_thread/api/public_api.ts +46 -48
- package/src/main_thread/core_interface/README.md +22 -0
- package/src/main_thread/core_interface/base.ts +36 -0
- package/src/main_thread/core_interface/monothread.ts +46 -0
- package/src/main_thread/core_interface/multithread.ts +49 -0
- package/src/main_thread/core_interface/types.ts +5 -0
- package/src/main_thread/init/media_source_content_initializer.ts +2034 -1152
- package/src/main_thread/init/utils/create_core_playback_observer.ts +2 -1
- package/src/main_thread/init/utils/update_manifest_codec_support.ts +1 -1
- package/src/main_thread/types.ts +610 -0
- package/src/manifest/utils.ts +20 -4
- package/src/mse/worker_media_source_interface.ts +35 -35
- package/src/parsers/manifest/smooth/create_parser.ts +40 -34
- package/src/parsers/manifest/smooth/parse_C_nodes.ts +19 -8
- package/src/parsers/manifest/smooth/parse_protection_node.ts +17 -9
- package/src/parsers/manifest/smooth/utils/parseBoolean.ts +1 -1
- package/src/parsers/manifest/smooth/utils/reduceChildren.ts +10 -7
- package/src/playback_observer/{worker_playback_observer.ts → core_playback_observer.ts} +13 -13
- package/src/transports/smooth/pipelines.ts +25 -5
- package/src/worker_entry_point.ts +71 -2
- package/dist/commonjs/core/main/common/FreezeResolver.d.ts.map +0 -1
- package/dist/commonjs/core/main/common/content_time_boundaries_observer.d.ts.map +0 -1
- package/dist/commonjs/core/main/common/create_content_time_boundaries_observer.d.ts.map +0 -1
- package/dist/commonjs/core/main/common/get_buffered_data_per_media_buffer.d.ts.map +0 -1
- package/dist/commonjs/core/main/common/get_thumbnail_data.d.ts.map +0 -1
- package/dist/commonjs/core/main/common/synchronize_sinks_on_observation.d.ts.map +0 -1
- package/dist/commonjs/core/main/worker/content_preparer.d.ts.map +0 -1
- package/dist/commonjs/core/main/worker/globals.d.ts +0 -14
- package/dist/commonjs/core/main/worker/globals.d.ts.map +0 -1
- package/dist/commonjs/core/main/worker/globals.js +0 -26
- package/dist/commonjs/core/main/worker/index.d.ts +0 -3
- package/dist/commonjs/core/main/worker/index.d.ts.map +0 -1
- package/dist/commonjs/core/main/worker/index.js +0 -4
- package/dist/commonjs/core/main/worker/send_message.d.ts +0 -4
- package/dist/commonjs/core/main/worker/send_message.d.ts.map +0 -1
- package/dist/commonjs/core/main/worker/send_message.js +0 -23
- package/dist/commonjs/core/main/worker/track_choice_setter.d.ts.map +0 -1
- package/dist/commonjs/core/main/worker/worker_main.d.ts +0 -2
- package/dist/commonjs/core/main/worker/worker_main.d.ts.map +0 -1
- package/dist/commonjs/core/main/worker/worker_text_displayer_interface.d.ts.map +0 -1
- package/dist/commonjs/main_thread/init/multi_thread_content_initializer.d.ts +0 -308
- package/dist/commonjs/main_thread/init/multi_thread_content_initializer.d.ts.map +0 -1
- package/dist/commonjs/main_thread/init/multi_thread_content_initializer.js +0 -1713
- package/dist/commonjs/main_thread/init/send_message.d.ts +0 -3
- package/dist/commonjs/main_thread/init/send_message.d.ts.map +0 -1
- package/dist/commonjs/main_thread/init/send_message.js +0 -13
- package/dist/commonjs/multithread_types.d.ts +0 -915
- package/dist/commonjs/multithread_types.d.ts.map +0 -1
- package/dist/commonjs/multithread_types.js +0 -7
- package/dist/commonjs/playback_observer/worker_playback_observer.d.ts.map +0 -1
- package/dist/es2017/core/main/common/FreezeResolver.d.ts.map +0 -1
- package/dist/es2017/core/main/common/content_time_boundaries_observer.d.ts.map +0 -1
- package/dist/es2017/core/main/common/create_content_time_boundaries_observer.d.ts.map +0 -1
- package/dist/es2017/core/main/common/get_buffered_data_per_media_buffer.d.ts.map +0 -1
- package/dist/es2017/core/main/common/get_thumbnail_data.d.ts.map +0 -1
- package/dist/es2017/core/main/common/synchronize_sinks_on_observation.d.ts.map +0 -1
- package/dist/es2017/core/main/worker/content_preparer.d.ts.map +0 -1
- package/dist/es2017/core/main/worker/globals.d.ts +0 -14
- package/dist/es2017/core/main/worker/globals.d.ts.map +0 -1
- package/dist/es2017/core/main/worker/globals.js +0 -18
- package/dist/es2017/core/main/worker/index.d.ts +0 -3
- package/dist/es2017/core/main/worker/index.d.ts.map +0 -1
- package/dist/es2017/core/main/worker/index.js +0 -2
- package/dist/es2017/core/main/worker/send_message.d.ts +0 -4
- package/dist/es2017/core/main/worker/send_message.d.ts.map +0 -1
- package/dist/es2017/core/main/worker/send_message.js +0 -19
- package/dist/es2017/core/main/worker/track_choice_setter.d.ts.map +0 -1
- package/dist/es2017/core/main/worker/worker_main.d.ts +0 -2
- package/dist/es2017/core/main/worker/worker_main.d.ts.map +0 -1
- package/dist/es2017/core/main/worker/worker_text_displayer_interface.d.ts.map +0 -1
- package/dist/es2017/main_thread/init/multi_thread_content_initializer.d.ts +0 -308
- package/dist/es2017/main_thread/init/multi_thread_content_initializer.d.ts.map +0 -1
- package/dist/es2017/main_thread/init/multi_thread_content_initializer.js +0 -1559
- package/dist/es2017/main_thread/init/send_message.d.ts +0 -3
- package/dist/es2017/main_thread/init/send_message.d.ts.map +0 -1
- package/dist/es2017/main_thread/init/send_message.js +0 -10
- package/dist/es2017/multithread_types.d.ts +0 -915
- package/dist/es2017/multithread_types.d.ts.map +0 -1
- package/dist/es2017/multithread_types.js +0 -6
- package/dist/es2017/playback_observer/worker_playback_observer.d.ts.map +0 -1
- package/src/core/main/worker/globals.ts +0 -38
- package/src/core/main/worker/index.ts +0 -2
- package/src/core/main/worker/send_message.ts +0 -28
- package/src/main_thread/init/multi_thread_content_initializer.ts +0 -2330
- package/src/main_thread/init/send_message.ts +0 -15
- package/src/multithread_types.ts +0 -1095
- /package/dist/commonjs/core/{main/common → entry}/synchronize_sinks_on_observation.js +0 -0
- /package/dist/es2017/core/{main/common → entry}/synchronize_sinks_on_observation.js +0 -0
package/dist/rx-player.min.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
"use strict";(()=>{var Bp=Object.defineProperty,Fp=Object.defineProperties;var Kp=Object.getOwnPropertyDescriptors;var Ql=Object.getOwnPropertySymbols;var Vp=Object.prototype.hasOwnProperty,zp=Object.prototype.propertyIsEnumerable;var $l=(n,e,t)=>e in n?Bp(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ae=(n,e)=>{for(var t in e||(e={}))Vp.call(e,t)&&$l(n,t,e[t]);if(Ql)for(var t of Ql(e))zp.call(e,t)&&$l(n,t,e[t]);return n},ue=(n,e)=>Fp(n,Kp(e));var y={PRODUCTION:0,DEV:1,CURRENT_ENV:0};var S={CURRENT_LEVEL:"NONE"};function E(n){return n==null}var se=class{constructor(){this._listeners={}}addEventListener(e,t,r){let i=this._listeners[e];Array.isArray(i)?i.push(t):this._listeners[e]=[t],r!==void 0&&r.register(()=>{this.removeEventListener(e,t)})}removeEventListener(e,t){if(E(e)){this._listeners={};return}let r=this._listeners[e];if(!Array.isArray(r))return;if(E(t)){delete this._listeners[e];return}let i=r.indexOf(t);i!==-1&&r.splice(i,1),r.length===0&&delete this._listeners[e]}trigger(e,t){let r=this._listeners[e];Array.isArray(r)&&r.slice().forEach(i=>{try{i(t)}catch(o){if(y.CURRENT_ENV===y.DEV)throw o instanceof Error?o:new Error("EventEmitter: listener error");console.error("RxPlayer: EventEmitter error",o instanceof Error?o:null)}})}};var Vn=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope;var qp=typeof window=="undefined"&&!Vn,$t=qp;var Eo;Vn?Eo=self:$t?Eo=global:Eo=window;var Z=Eo;var It=typeof queueMicrotask=="function"?queueMicrotask:function(e){Promise.resolve().then(e,()=>e())};function ts(){if(!$t&&!E(Z.WebKitSourceBuffer)&&Z.WebKitSourceBuffer.prototype.addEventListener===void 0){let e=Z.WebKitSourceBuffer.prototype;for(let t in se.prototype)Object.prototype.hasOwnProperty.call(se.prototype,t)&&(e[t]=se.prototype[t]);e._listeners=[],e._emitUpdate=function(t,r){It(()=>{this.trigger(t,r),this.updating=!1,this.trigger("updateend",new Event("updateend"))})},e.appendBuffer=function(t){var r,i;if(this.updating)throw new Error("updating");this.trigger("updatestart",new Event("updatestart")),this.updating=!0;try{this.append(t)}catch(o){(r=this._emitUpdate)==null||r.call(this,"error",o);return}(i=this._emitUpdate)==null||i.call(this,"update",new Event("update"))}}}function Ie(n,e,t){if(typeof Array.prototype.findIndex=="function")return n.findIndex(e,t);let r=n.length>>>0;for(let i=0;i<r;i++)if(e.call(t,n[i],i,n))return i;return-1}function te(){}var _o=class{constructor(e,t){this._value=e,this._listeners=[],this._isFinished=!1,this._onFinishCbs=[],t!==void 0&&(this._deregisterCancellation=t.register(()=>this.finish()))}getValue(){return this._value}setValue(e){if(this._isFinished){y.CURRENT_ENV===y.DEV&&console.error("Finished shared references cannot be updated");return}if(this._value=e,this._listeners.length===0)return;let t=this._listeners.slice();for(let r of t)try{r.hasBeenCleared||r.trigger(e,r.complete)}catch(i){}}setValueIfChanged(e){e!==this._value&&this.setValue(e)}onUpdate(e,t){let r=()=>{if(t.clearSignal!==void 0&&t.clearSignal.deregister(r),i.hasBeenCleared)return;i.hasBeenCleared=!0;let o=this._listeners.indexOf(i);o>=0&&this._listeners.splice(o,1)},i={trigger:e,complete:r,hasBeenCleared:!1};if(this._listeners.push(i),t.emitCurrentValue===!0&&e(this._value,r),this._isFinished||i.hasBeenCleared){r();return}t.clearSignal.register(r)}waitUntilDefined(e,t){this.onUpdate((r,i)=>{r!==void 0&&(i(),e(this._value))},{clearSignal:t.clearSignal,emitCurrentValue:!0})}_onFinished(e,t){if(t.isCancelled())return te;let r=()=>{let a=Ie(this._onFinishCbs,s=>s.trigger===i);a>=0&&(this._onFinishCbs[a].hasBeenCleared=!0,this._onFinishCbs.splice(a,1))},i=()=>{r(),e()},o=t.register(r);return this._onFinishCbs.push({trigger:i,hasBeenCleared:!1}),o}finish(){this._deregisterCancellation!==void 0&&this._deregisterCancellation(),this._isFinished=!0;let e=this._listeners.slice();for(let t of e)try{t.hasBeenCleared||(t.complete(),t.hasBeenCleared=!0)}catch(r){}if(this._listeners.length=0,this._onFinishCbs.length>0){let t=this._onFinishCbs.slice();for(let r of t)try{r.hasBeenCleared||(r.trigger(),r.hasBeenCleared=!0)}catch(i){}this._onFinishCbs.length=0}}};function gn(n,e,t){let r=new _o(e(n.getValue()),t);return n.onUpdate(function(o){r.setValue(e(o))},{clearSignal:t}),n._onFinished(()=>{r.finish()},t),r}var j=_o;var Xl=new j(0);var Gp=typeof performance!="undefined"?()=>performance.now()+Xl.getValue():()=>Date.now()+Xl.getValue(),z=Gp;var jp="NONE",br=class extends se{constructor(){super(),this.error=te,this.warn=te,this.info=te,this.debug=te,this._levels={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},this._currentFormat="standard",this._currentLevel=jp}setLevel(e,t,r){let i,o=this._levels[e];typeof o=="number"?(i=o,this._currentLevel=e):(i=0,this._currentLevel="NONE");let a;if(t==="standard"||t==="full"?a=t:a="standard",a==="full"&&a!==this._currentFormat){let d=z();console.log(String(d.toFixed(2)),"[Init]",`Local-Date: ${Date.now()}`)}this._currentFormat=a;let s=this._currentFormat==="full"?(d,u)=>(c,...l)=>{let f=z();return u(String(f.toFixed(2)),`[${d}]`,c+":",...l.map(p=>typeof p=="object"&&p!==null&&!(p instanceof Error)?Zl(p):p))}:(d,u)=>(c,...l)=>u(c+":",...l.map(f=>typeof f=="object"&&f!==null&&!(f instanceof Error)?Zl(f):f));if(r===void 0)this.error=i>=this._levels.ERROR?s("error",console.error.bind(console)):te,this.warn=i>=this._levels.WARNING?s("warn",console.warn.bind(console)):te,this.info=i>=this._levels.INFO?s("info",console.info.bind(console)):te,this.debug=i>=this._levels.DEBUG?s("log",console.log.bind(console)):te;else{let d=u=>i>=this._levels[u]?(c,...l)=>r(u,c,l):te;this.error=d("ERROR"),this.warn=d("WARNING"),this.info=d("INFO"),this.debug=d("DEBUG")}this.trigger("onLogLevelChange",{level:this._currentLevel,format:this._currentFormat})}getLevel(){return this._currentLevel}getFormat(){return this._currentFormat}hasLevel(e){return this._levels[e]>=this._levels[this._currentLevel]}};function Zl(n){let e="";for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){e.length>0&&(e+=" ");let r=n[t];r instanceof Error?e+=`${t}="${JSON.stringify(r==null?void 0:r.toString())}"`:e+=`${t}=${typeof r=="string"?`${JSON.stringify(r)}`:String(r)}`}return e}var Yp=new br,m=Yp;var Be=Z,Jl,ec,tc,nc,rc,wt=(rc=(nc=(tc=(ec=(Jl=Be==null?void 0:Be.MediaSource)!=null?Jl:Be==null?void 0:Be.MozMediaSource)!=null?ec:Be==null?void 0:Be.WebKitMediaSource)!=null?tc:Be==null?void 0:Be.MSMediaSource)!=null?nc:Be==null?void 0:Be.ManagedMediaSource)!=null?rc:void 0,ic=wt!==void 0&&wt===(Be==null?void 0:Be.ManagedMediaSource);var Qp=200,vo=new Map;function ns(n,e){if(n.isDummy)return n.FORCED_MEDIA_SOURCE.isTypeSupported(e);if(E(wt))return Vn&&m.error("mse","Cannot request codec support in a worker without MSE."),!1;if(typeof wt.isTypeSupported=="function"){let t=vo.get(e);if(t!==void 0)return t;{let r=wt.isTypeSupported(e);return vo.size>=Qp&&vo.clear(),vo.set(e,r),r}}return!0}var oc={DEFAULT_REQUEST_TIMEOUT:3e4,DEFAULT_CONNECTION_TIMEOUT:15e3,DEFAULT_TEXT_TRACK_MODE:"native",DEFAULT_ENABLE_FAST_SWITCHING:!0,DELTA_POSITION_AFTER_RELOAD:{bitrateSwitch:-.1,trackSwitch:{audio:0,video:0,other:0}},DEFAULT_CODEC_SWITCHING_BEHAVIOR:"continue",DEFAULT_AUDIO_TRACKS_NOT_PLAYABLE_BEHAVIOR:"error",DEFAULT_VIDEO_TRACKS_NOT_PLAYABLE_BEHAVIOR:"error",DEFAULT_AUTO_PLAY:!1,DEFAULT_WANTED_BUFFER_AHEAD:30,DEFAULT_MAX_BUFFER_AHEAD:1/0,DEFAULT_MAX_BUFFER_BEHIND:1/0,DEFAULT_MAX_VIDEO_BUFFER_SIZE:1/0,MAXIMUM_MAX_BUFFER_AHEAD:{text:18e3},MINIMUM_MAX_BUFFER_AHEAD:{text:120},MAXIMUM_MAX_BUFFER_BEHIND:{text:18e3},DEFAULT_BASE_BANDWIDTH:0,INACTIVITY_DELAY:6e4,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:!1,DEFAULT_VIDEO_RESOLUTION_LIMIT:"none",DEFAULT_LIVE_GAP:{DEFAULT:10,LOW_LATENCY:3.5},BUFFER_DISCONTINUITY_THRESHOLD:.2,BITRATE_REBUFFERING_RATIO:1.5,DEFAULT_MAX_MANIFEST_REQUEST_RETRY:4,DEFAULT_CDN_DOWNGRADE_TIME:60,DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:4,INITIAL_BACKOFF_DELAY_BASE:{REGULAR:200,LOW_LATENCY:50},MAX_BACKOFF_DELAY_BASE:{REGULAR:3e3,LOW_LATENCY:1e3},SAMPLING_INTERVAL_MEDIASOURCE:1e3,SAMPLING_INTERVAL_LOW_LATENCY:500,SAMPLING_INTERVAL_NO_MEDIASOURCE:500,ABR_ENTER_BUFFER_BASED_ALGO:10,ABR_EXIT_BUFFER_BASED_ALGO:5,ABR_MINIMUM_TOTAL_BYTES:15e4,ABR_MINIMUM_CHUNK_SIZE:16e3,ABR_STARVATION_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_REGULAR_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_STARVATION_GAP:{DEFAULT:5,LOW_LATENCY:5},OUT_OF_STARVATION_GAP:{DEFAULT:7,LOW_LATENCY:7},ABR_STARVATION_DURATION_DELTA:.1,ABR_FAST_EMA:2,ABR_SLOW_EMA:10,RESUME_GAP_AFTER_SEEKING:{DEFAULT:1.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_NOT_ENOUGH_DATA:{DEFAULT:.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_BUFFERING:{DEFAULT:5,LOW_LATENCY:.5},REBUFFERING_GAP:{DEFAULT:.5,LOW_LATENCY:.2},MINIMUM_BUFFER_AMOUNT_BEFORE_FREEZING:2,UNFREEZING_SEEK_DELAY:6e3,FREEZING_STALLED_DELAY:600,UNFREEZING_DELTA_POSITION:.001,FREEZING_FLUSH_FAILURE_DELAY:{MAXIMUM:2e4,MINIMUM:4e3,POSITION_DELTA:1},SEGMENT_SYNCHRONIZATION_DELAY:1500,MISSING_DATA_TRIGGER_SYNC_DELAY:.1,MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:.15,MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:.4,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:.3,MINIMUM_SEGMENT_SIZE:.001,APPEND_WINDOW_SECURITIES:{START:.2,END:.1},MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:50,TEXT_TRACK_SIZE_CHECKS_INTERVAL:250,BUFFER_PADDING:{audio:1,video:3,other:1},SEGMENT_PRIORITIES_STEPS:[2,4,8,12,18,25],MAX_HIGH_PRIORITY_LEVEL:1,MIN_CANCELABLE_PRIORITY:3,EME_DEFAULT_VIDEO_CODECS:['video/mp4;codecs="avc1.4d401e"','video/mp4;codecs="avc1.42e01e"','video/mp4;codecs="hvc1.1.6.L93.B0"','video/webm;codecs="vp8"'],EME_DEFAULT_AUDIO_CODECS:['audio/mp4;codecs="mp4a.40.2"','audio/webm;codecs="opus"','audio/mp4;codecs="ec-3"'],EME_DEFAULT_WIDEVINE_ROBUSTNESSES:["HW_SECURE_ALL","HW_SECURE_DECODE","HW_SECURE_CRYPTO","SW_SECURE_DECODE","SW_SECURE_CRYPTO"],EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:["3000","2000"],EME_KEY_SYSTEMS:{clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.microsoft.playready.recommendation","com.microsoft.playready","com.chromecast.playready","com.youtube.playready"],fairplay:["com.apple.fps.1_0"]},MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:10,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:200,MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:300,OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:3e3,FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:3e3,DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:3,EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:15,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:1e3,EME_WAITING_DELAY_LOADED_SESSION_EMPTY_KEYSTATUSES:100,FORCED_ENDED_THRESHOLD:8e-4,ADAP_REP_SWITCH_BUFFER_PADDINGS:{video:{before:5,after:5},audio:{before:2,after:2.5},text:{before:0,after:0}},SOURCE_BUFFER_FLUSHING_INTERVAL:500,CONTENT_REPLACEMENT_PADDING:1.2,CACHE_LOAD_DURATION_THRESHOLDS:{video:50,audio:10},STREAM_EVENT_EMITTER_POLL_INTERVAL:250,DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR:.001,BUFFERED_HISTORY_RETENTION_TIME:6e4,BUFFERED_HISTORY_MAXIMUM_ENTRIES:200,MIN_BUFFER_AHEAD:5,UPTO_CURRENT_POSITION_CLEANUP:5,DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_VIDEO_TRACK_SWITCHING_MODE:"reload",DEFAULT_AUDIO_TRACK_SWITCHING_MODE:"seamless",DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:1,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:1e4,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:7e3,FORCE_CANNOT_RELY_ON_REQUEST_MEDIA_KEY_SYSTEM_ACCESS:!1,FORCE_CANNOT_REUSE_MEDIA_KEYS:!1,FORCE_HAS_ISSUES_WITH_HIGH_MEDIA_SOURCE_DURATION:!1,FORCE_IS_SEEKING_APPROXIMATE:!1,FORCE_MEDIA_ELEMENT_FAIL_ON_UNDECIPHERABLE_DATA:!1,FORCE_SHOULD_AWAIT_SET_MEDIA_KEYS:!1,FORCE_SHOULD_FAVOUR_CUSTOM_SAFARI_EME:!1,FORCE_SHOULD_RELOAD_MEDIA_SOURCE_ON_DECIPHERABILITY_UPDATE:!1,FORCE_SHOULD_RENEW_MEDIA_KEY_SYSTEM_ACCESS:!1,FORCE_SHOULD_UNSET_MEDIA_KEYS:!1,FORCE_SHOULD_VALIDATE_METADATA:!1,FORCE_DONT_WAIT_FOR_DATA_BEFORE_LOADED:!1,FORCE_WAIT_FOR_HAVE_ENOUGH_DATA:!1},ac=oc;function $p(n,...e){if(n==null)throw new TypeError("Cannot convert undefined or null to object");let t=Object(n);for(let r of e)for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i]);return t}var Y=typeof Object.assign=="function"?Object.assign:$p;function rs(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function Sr(n,...e){if(e.length===0)return n;let t=e.shift();if(rs(n)&&rs(t))for(let r in t)if(rs(t[r])){let i=n[r];i===void 0&&(i={},n[r]=i),Sr(i,t[r])}else Y(n,{[r]:t[r]});return Sr(n,...e)}var is=class extends se{constructor(){super(...arguments);this.updated=!1;this._config=ac}update(t){let r=Sr(this._config,t);this._config=r,this.updated=!0,this.trigger("update",t)}getCurrent(){return this._config}},Xp=new is,O=Xp;var Xt={EdgeChromium:0,Firefox:1,Ie11:2,OtherIeOrEdgePreEdgeChromium:3,SafariDesktop:4,SafariMobile:5,Other:6},at={A1KStb40xx:100,Panasonic:101,PhilipsNetTv:102,PlayStation4:103,PlayStation5:104,Tizen:105,WebOs2021:106,WebOs2022:107,WebOsOther:108,Xbox:109,Other:110},Fe={DEVICES:at,BROWSERS:Xt,browser:Xt.Other,device:at.Other,isSamsungBrowser:!1};Zp();function Zp(){var n,e,t;$t||(typeof Z.MSInputMethodContext!="undefined"&&typeof document.documentMode!="undefined"?Fe.browser=Xt.Ie11:navigator.appName==="Microsoft Internet Explorer"||navigator.appName==="Netscape"&&/(Trident|Edge)\//.test(navigator.userAgent)?Fe.browser=Xt.OtherIeOrEdgePreEdgeChromium:navigator.userAgent.toLowerCase().indexOf("edg/")!==-1?Fe.browser=Xt.EdgeChromium:navigator.userAgent.toLowerCase().indexOf("firefox")!==-1?Fe.browser=Xt.Firefox:typeof navigator.platform=="string"&&/iPad|iPhone|iPod/.test(navigator.platform)?Fe.browser=Xt.SafariMobile:(Object.prototype.toString.call(Z.HTMLElement).indexOf("Constructor")>=0||((e=(n=Z.safari)==null?void 0:n.pushNotification)==null?void 0:e.toString())==="[object SafariRemoteNotification]"||/Safari\/(\d+)/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&((t=navigator.vendor)==null?void 0:t.indexOf("Apple"))!==-1&&!/Chrome\/(\d+)/.test(navigator.userAgent)&&!/Chromium\/(\d+)/.test(navigator.userAgent))&&(Fe.browser=Xt.SafariDesktop),/SamsungBrowser/.test(navigator.userAgent)&&(Fe.isSamsungBrowser=!0),navigator.userAgent.indexOf("PlayStation 4")!==-1?Fe.device=at.PlayStation4:navigator.userAgent.indexOf("PlayStation 5")!==-1?Fe.device=at.PlayStation5:/Tizen/.test(navigator.userAgent)?Fe.device=at.Tizen:/[Ww]eb[O0]S/.test(navigator.userAgent)?/[Ww]eb[O0]S.TV-2022/.test(navigator.userAgent)||/[Cc]hr[o0]me\/87/.test(navigator.userAgent)?Fe.device=at.WebOs2022:/[Ww]eb[O0]S.TV-2021/.test(navigator.userAgent)||/[Cc]hr[o0]me\/79/.test(navigator.userAgent)?Fe.device=at.WebOs2021:Fe.device=at.WebOsOther:navigator.userAgent.indexOf("NETTV")!==-1&&navigator.userAgent.indexOf("Philips")!==-1?Fe.device=at.PhilipsNetTv:/[Pp]anasonic/.test(navigator.userAgent)?Fe.device=at.Panasonic:navigator.userAgent.indexOf("Xbox")!==-1?Fe.device=at.Xbox:navigator.userAgent.indexOf("Model/a1-kstb40xx")!==-1&&(Fe.device=at.A1KStb40xx))}var V=Fe;function os(){let{FORCE_MEDIA_ELEMENT_FAIL_ON_UNDECIPHERABLE_DATA:n}=O.getCurrent();return n||V.device===V.DEVICES.PlayStation5}function as(n){let{FORCE_SHOULD_RELOAD_MEDIA_SOURCE_ON_DECIPHERABILITY_UPDATE:e}=O.getCurrent();return e||n===void 0||n.indexOf("widevine")<0}var Jp=.016666666666666666;function sc(n,e){return Math.abs(n-e)<Jp}function uc(n,e){let t=Math.min(n.start,e.start),r=Math.max(n.end,e.end);return{start:t,end:r}}function eg(n){for(let e=0;e<n.length;e++){let t=n[e];t.start===t.end&&n.splice(e--,1)}return n}function tg(n){for(let e=1;e<n.length;e++){let t=n[e-1],r=n[e];if(cc(t,r)){let i=uc(t,r);n.splice(--e,2,i)}}return n}function ss(n,e){return n.end<=e.start}function dc({start:n,end:e},t){return n<=t&&t<e}function lc(n,e){return dc(n,e.start)||n.start<e.end&&e.end<n.end||dc(e,n.start)}function cc(n,e){return sc(e.start,n.end)||sc(e.end,n.start)}function Le(n){let e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e}function ds(n,e){for(let t=n.length-1;t>=0;t--){let r=n.start(t);if(e>=r){let i=n.end(t);if(e<i)return{start:r,end:i}}}return null}function ng(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t].start;if(e>=r){let i=n[t].end;if(e<i)return n[t]}}return null}function fc(n,e){let t=n.length;for(let r=0;r<t;r++){let i=n.start(r);if(e<i)return i-e}return 1/0}function mc(n,e){let t=null,r=[];for(let i=0;i<n.length;i++){let o=n[i].start,a=n[i].end;e<o||e>=a?r.push({start:o,end:a}):t={start:o,end:a}}return{outerRanges:r,innerRange:t}}function pc(n,e){let t=ds(n,e);return t!==null?t.end-e:1/0}function Ro(n,e){let t=ng(n,e);return t!==null?t.end-e:1/0}function vt(n,e){if(e.start===e.end)return n;let t=e,r=0;for(;r<n.length;r++){let i=n[r],o=lc(t,i),a=cc(t,i);if(o||a)t=uc(t,i),n.splice(r--,1);else if(r===0){if(ss(t,n[0]))break}else if(ss(n[r-1],t)&&ss(t,i))break}return n.splice(r,0,t),tg(eg(n))}function gc(n,e){let t=[];for(let r=0;r<e.length;r++)lc(n,e[r])&&t.push(e[r]);return t}function hc(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=gc(i,e);if(o.length>0)for(let a=0;a<o.length;a++){let s=o[a];t.push({start:Math.max(i.start,s.start),end:Math.min(i.end,s.end)})}}return t}function ko(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=[],a=gc(i,e);if(a.length>0)for(let s=0;s<a.length;s++){let d=a[s];o.push({start:Math.max(i.start,d.start),end:Math.min(i.end,d.end)})}if(o.length===0)t.push(i);else{let s=i.start;for(let d=0;d<o.length;d++)o[d].start>s&&t.push({start:s,end:o[d].start}),s=o[d].end;s<i.end&&t.push({start:s,end:i.end})}}return t}var Po=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="AssertionError"}};function ne(n,e){if(y.DEV===y.CURRENT_ENV&&!n)throw new Po(e===void 0?"invalid assertion":e)}function yc(n,e,t="object"){ne(!E(n),`${t} should be an object`);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&ne(typeof n[r]===e[r],`${t} should have property ${r} as a ${e[r]}`)}function ze(n){throw new Po("Unreachable path taken")}var U=class{constructor(){let[e,t]=rg();this._isUsed=!1,this._trigger=e,this.signal=new Tr(t)}isUsed(){return this._isUsed}linkToSignal(e){let t=e.register(()=>{this.cancel()});return this.signal.register(t),t}cancel(e){if(this._isUsed)return;this._isUsed=!0;let t=e!=null?e:new we;this._trigger(t)}static isCancellationError(e){return e instanceof we}},Tr=class{constructor(e){this._isCancelled=!1,this.cancellationError=null,this._listeners=[],e(t=>{for(this.cancellationError=t,this._isCancelled=!0;this._listeners.length>0;)try{let r=this._listeners.pop();r==null||r(t)}catch(r){m.error("utils","Error while calling clean up listener",r instanceof Error?r:"Unknown Error")}})}isCancelled(){return this._isCancelled}register(e){return this._isCancelled?(ne(this.cancellationError!==null),e(this.cancellationError),te):(this._listeners.push(e),()=>this.deregister(e))}deregister(e){for(let t=this._listeners.length-1;t>=0;t--)this._listeners[t]===e&&this._listeners.splice(t,1)}},we=class n extends Error{constructor(){super("This task was cancelled."),Object.setPrototypeOf(this,n.prototype),this.name="CancellationError"}};function rg(){let n=te;return[function(t){n(t)},function(t){n=t}]}function us(n){let e=n.map(a=>Math.log(a/n[0])),t=e.map(a=>a-e[0]+1),r=(t[t.length-1]-1)/(n.length*2+10),i=1/r;return n.map((a,s)=>o(s));function o(a){if(a===0)return 0;let s=Math.min(Math.max(1,a),n.length-1);return n[s]===n[s-1]?o(a-1):i*(r+(n[s]*t[s-1]-n[s-1]*t[s])/(n[s]-n[s-1]))+4}}var st=class{constructor(e){this._alpha=Math.exp(Math.log(.5)/e),this._lastEstimate=0,this._totalWeight=0}addSample(e,t){let r=Math.pow(this._alpha,e),i=t*(1-r)+r*this._lastEstimate;isNaN(i)||(this._lastEstimate=i,this._totalWeight+=e)}getEstimate(){let e=1-Math.pow(this._alpha,this._totalWeight);return this._lastEstimate/e}};var Er=class{constructor(){this._currentRepresentationData=null,this._lastRepresentationWithGoodScore=null}addSample(e,t,r){let i=r/t,o=this._currentRepresentationData,a;o!==null&&o.representation.id===e.id?(a=o.ewma,o.ewma.addSample(t,i),o.loadedDuration+=r,o.loadedSegments++):(a=new st(5),a.addSample(t,i),this._currentRepresentationData={representation:e,ewma:a,loadedDuration:r,loadedSegments:0}),a.getEstimate()>1&&this._lastRepresentationWithGoodScore!==e&&(m.debug("ABR","New last stable representation",{bitrate:e.bitrate}),this._lastRepresentationWithGoodScore=e)}getEstimate(e){if(this._currentRepresentationData===null||this._currentRepresentationData.representation.id!==e.id)return;let{ewma:t,loadedSegments:r,loadedDuration:i}=this._currentRepresentationData,o=t.getEstimate(),a=r>=5&&i>=10?1:0;return{score:o,confidenceLevel:a}}getLastStableRepresentation(){return this._lastRepresentationWithGoodScore}};var Ic=6e3,ig=15e3,og=3e3,ag=1e3,sg=9e3,_r=class{constructor(e){this._levelsMap=us(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=Ic,m.debug("ABR","Steps for buffer based chooser.",this._levelsMap.map((t,r)=>`bufferLevel: ${t}, bitrate: ${e[r]}`).join(" ,"))}onAddedSegment(e){let t=this._levelsMap,r=this._bitrates,{bufferGap:i,currentBitrate:o,currentScore:a,speed:s}=e;if(E(o)){this._currentEstimate=r[0];return}let d=-1;for(let h=0;h<r.length;h++){let I=r[h];if(I===o)d=h;else if(I>o)break}if(d<0||r.length!==t.length){m.info("ABR","Current Bitrate not found in the calculated levels"),this._currentEstimate=r[0];return}let u;a!==void 0&&(u=s===0?a.score:a.score/s);let c=isFinite(i)?i:0,l=z();if(c<t[d]||u!==void 0&&u<1&&(a==null?void 0:a.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:l-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+sg){let g=this._blockRaiseDelay+og;m.debug("ABR","Incrementing blocking raise in BufferBasedChooser due to unstable quality",{prevDelay:this._blockRaiseDelay,newDelay:g}),this._blockRaiseDelay=Math.min(g,ig)}else{let g=this._blockRaiseDelay-ag;m.debug("ABR","Lowering quality in BufferBasedChooser",{prevDelay:this._blockRaiseDelay,newDelay:g}),this._blockRaiseDelay=Math.max(Ic,g)}this._lastUnsuitableQualityTimestamp=l;let I=Ie(r,g=>g===o);for(let g=I-1;g>=0;g--)if(c>=t[g]){this._currentEstimate=r[g];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&l-this._lastUnsuitableQualityTimestamp<this._blockRaiseDelay||u===void 0||u<1.15||(a==null?void 0:a.confidenceLevel)!==1){this._currentEstimate=o;return}let f=t[d],p=(()=>{for(let h=d+1;h<t.length;h++)if(t[h]>f)return h})();if(p!==void 0){let h=t[p];if(i>=h){m.debug("ABR","Raising quality in BufferBasedChooser",{bitrate:r[p]}),this._currentEstimate=r[p];return}}this._currentEstimate=o}getLastEstimate(){return this._currentEstimate}};function Q(n,e,t){if(typeof Array.prototype.find=="function")return n.find(e,t);let r=n.length>>>0;for(let i=0;i<r;i++){let o=n[i];if(e.call(t,o,i,n))return o}}function dg(n,e){let t=-1;for(let a=0;a<n.length;a++){let{segment:s}=n[a].content;if(s.duration<=0)continue;let d=s.time+s.duration;if(!s.complete&&a===n.length-1&&e-s.time>-1.2){t=a;break}if(d>e&&e-s.time>-1.2){t=a;break}}if(t<0)return[];let r=n[t],i=r.content.segment.time,o=[r];for(let a=t+1;a<n.length&&n[a].content.segment.time===i;a++)o.push(n[a]);return o}function Co(n){if(n.progress.length<5)return;let e=new st(2),{progress:t}=n;for(let r=1;r<t.length;r++){let i=t[r].size-t[r-1].size,o=t[r].timestamp-t[r-1].timestamp,a=i*8/(o/1e3);e.addSample(o/1e3,a)}return e.getEstimate()}function bc(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function ug(n,e,t,r,i){if(r)return;let{bufferGap:o,speed:a,position:s}=e,d=isFinite(o)?o:0,u=s.getWanted()+d,c=dg(n,u);if(c.length!==1)return;let l=c[0],f=z(),p=l.content.segment.duration*1.5;if(p=Math.min(p,3e3),p=Math.max(p,12e3),f-l.requestTimestamp<p)return;let h=l.progress.length>0?l.progress[l.progress.length-1]:void 0,I=Co(l);if(h!==void 0&&I!==void 0){let R=bc(h,I);if((f-h.timestamp)/1e3<=R&&R-d/a>2500)return I}if(!l.content.segment.complete)return;let g=l.content.segment.duration,b=(f-l.requestTimestamp)/1e3,T=b<=(g*1.5+2)/a;if(E(t)||T)return;let v=g/b,_=t.bitrate*Math.min(.7,v);if(i===void 0||_<i)return _}function lg(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,o=Q(e,({content:l})=>l.segment.duration>0&&l.segment.time+l.segment.duration>i);if(o===void 0)return!0;let a=z(),s=o.progress.length>0?o.progress[o.progress.length-1]:void 0,d=Co(o);if(s===void 0||d===void 0)return!0;let u=bc(s,d);return(a-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var vr=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:o,ABR_REGULAR_FACTOR:a}=O.getCurrent();this._initialBitrate=e,this._inStarvationMode=!1,this._lowLatencyMode=t,t?this._config={starvationGap:r.LOW_LATENCY,outOfStarvationGap:i.LOW_LATENCY,starvationBitrateFactor:o.LOW_LATENCY,regularBitrateFactor:a.LOW_LATENCY}:this._config={starvationGap:r.DEFAULT,outOfStarvationGap:i.DEFAULT,starvationBitrateFactor:o.DEFAULT,regularBitrateFactor:a.DEFAULT}}getBandwidthEstimate(e,t,r,i,o){let a,s,d=this._config,{bufferGap:u,position:c,duration:l}=e,f=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:p}=O.getCurrent();return isNaN(l)||f+c.getWanted()<l-p?!this._inStarvationMode&&f<=d.starvationGap?(m.info("ABR","enter starvation mode.",{buffergap:f,enterStarvation:d.starvationGap}),this._inStarvationMode=!0):this._inStarvationMode&&f>=d.outOfStarvationGap&&(m.info("ABR","exit starvation mode.",{bufferGap:f,outOfStarvation:d.starvationGap}),this._inStarvationMode=!1):this._inStarvationMode&&(m.info("ABR","exit starvation mode.",{bufferGap:f}),this._inStarvationMode=!1),this._inStarvationMode&&(s=ug(i,e,r,this._lowLatencyMode,o),s!==void 0&&(m.info("ABR","starvation mode emergency estimate:",{bandwidth:s}),t.reset(),a=E(r)?s:Math.min(s,r.bitrate))),E(a)&&(s=t.getEstimate(),s!==void 0?a=s*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):o!==void 0?a=o*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):a=this._initialBitrate),e.speed>1&&(a/=e.speed),{bandwidthEstimate:s,bitrateChosen:a}}isUrgent(e,t,r,i){return t===null?!0:e>=t.bitrate?!1:lg(i,r,this._lowLatencyMode)}};var Rr=class{constructor(){this.bandwidth=void 0,this.representation=null,this.algorithmType=3}update(e,t,r){this.representation=e,this.bandwidth=t,this.algorithmType=r}};var kr=class{constructor(e,t){this._scoreCalculator=e,this._lastAbrEstimate=t,this._consecutiveWrongGuesses=0,this._blockGuessesUntil=0,this._lastMaintanableBitrate=null}getGuess(e,t,r,i,o){let{bufferGap:a,speed:s}=t,d=this._lastAbrEstimate.representation;if(d===null)return null;if(i>d.bitrate)return this._lastAbrEstimate.algorithmType===2&&(this._lastAbrEstimate.representation!==null&&(this._lastMaintanableBitrate=this._lastAbrEstimate.representation.bitrate),this._consecutiveWrongGuesses=0),null;let u=this._scoreCalculator.getEstimate(r);if(this._lastAbrEstimate.algorithmType!==2){if(u===void 0)return null;if(this._canGuessHigher(a,s,u)){let l=Sc(e,r);if(l!==null)return l}return null}if(this._isLastGuessValidated(d,i,u)&&(m.debug("ABR","Guessed Representation validated",{chosenBitrate:d.bitrate,otherAbrAlgosBitrate:i,scoreData:u==null?void 0:u.score,scoreConfidence:u==null?void 0:u.confidenceLevel}),this._lastMaintanableBitrate=d.bitrate,this._consecutiveWrongGuesses=0),r.id!==d.id)return d;if(this._shouldStopGuess(r,u,a,o))return this._consecutiveWrongGuesses++,this._blockGuessesUntil=z()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),cg(e,r);if(u===void 0)return r;if(this._canGuessHigher(a,s,u)){let l=Sc(e,r);if(l!==null)return l}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&z()>this._blockGuessesUntil&&i===1&&r/t>1.01}_shouldStopGuess(e,t,r,i){if(t!==void 0&&t.score<1.01)return!0;if((t===void 0||t.score<1.2)&&r<.6)return!0;let o=i.filter(s=>s.content.representation.id===e.id),a=z();for(let s of o){let d=a-s.requestTimestamp;if(s.content.segment.isInit){if(d>1e3)return!0}else{if(d>s.content.segment.duration*1e3+200)return!0;{let u=Co(s);if(u!==void 0&&u<e.bitrate*.8)return!0}}}return!1}_isLastGuessValidated(e,t,r){return r!==void 0&&r.confidenceLevel===1&&r.score>1.5?!0:t>=e.bitrate&&(this._lastMaintanableBitrate===null||this._lastMaintanableBitrate<e.bitrate)}};function Sc(n,e){let t=n.length,r=Ie(n,({id:i})=>i===e.id);if(r<0)return m.error("ABR","Current Representation not found."),null;for(;++r<t;)if(n[r].bitrate>e.bitrate)return n[r];return null}function cg(n,e){let t=Ie(n,({id:r})=>r===e.id);if(t<0)return m.error("ABR","Current Representation not found."),null;for(;--t>=0;)if(n[t].bitrate<e.bitrate)return n[t];return null}var Pr=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=O.getCurrent();this._fastEWMA=new st(e),this._slowEWMA=new st(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=O.getCurrent();if(t<r)return;let i=t*8e3/e,o=e/1e3;this._bytesSampled+=t,this._fastEWMA.addSample(o,i),this._slowEWMA.addSample(o,i)}getEstimate(){let{ABR_MINIMUM_TOTAL_BYTES:e}=O.getCurrent();if(!(this._bytesSampled<e))return Math.min(this._fastEWMA.getEstimate(),this._slowEWMA.getEstimate())}reset(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=O.getCurrent();this._fastEWMA=new st(e),this._slowEWMA=new st(t),this._bytesSampled=0}};function ls(n,e){if(n.length===0)return[];n.sort((o,a)=>o.bitrate-a.bitrate);let t=n[0].bitrate,r=Math.max(e,t),i=Ie(n,o=>o.bitrate>r);return i===-1?n:n.slice(0,i)}function cs(n,e){if(e.width===void 0||e.height===void 0)return n;let t=e.width*e.pixelRatio,r=e.height*e.pixelRatio,i=n.slice().sort((s,d)=>{var u,c;return((u=s.width)!=null?u:0)-((c=d.width)!=null?c:0)}),o=Q(i,s=>typeof s.width=="number"&&s.width>=t&&typeof s.height=="number"&&s.height>=r);if(o===void 0)return n;let a=typeof o.width=="number"?o.width:0;return n.filter(s=>typeof s.width=="number"?s.width<=a:!0)}function Cr(n){return Object.keys(n).map(e=>n[e])}var zn=typeof Object.values=="function"?Object.values:Cr;var Ar=class{constructor(){this._currentRequests={}}add(e){let{id:t,requestTimestamp:r,content:i}=e;this._currentRequests[t]={requestTimestamp:r,progress:[],content:i}}addProgress(e){let t=this._currentRequests[e.id];if(E(t)){if(y.CURRENT_ENV===y.DEV)throw new Error("ABR: progress for a request not added");m.warn("ABR","progress for a request not added",{requestId:e.id});return}t.progress.push(e)}remove(e){if(E(this._currentRequests[e])){if(y.CURRENT_ENV===y.DEV)throw new Error("ABR: can't remove unknown request");m.warn("ABR","can't remove unknown request",{requestId:e})}delete this._currentRequests[e]}getRequests(){return zn(this._currentRequests).filter(e=>!E(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function Ao(n,e){let t=Ie(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var Tc=new j(void 0);Tc.finish();var Ec=new j(1/0);Ec.finish();function fs(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,c,l){var g,b,T;let{type:f}=s.adaptation,p=o(f),h=(g=t[f])!=null?g:0,I={limitResolution:(b=r.limitResolution[f])!=null?b:Tc,throttleBitrate:(T=r.throttleBitrate[f])!=null?T:Ec};return fg({bandwidthEstimator:p,context:s,currentRepresentation:d,filters:I,initialBitrate:h,playbackObserver:c,representations:u,lowLatencyMode:i},l)};function o(a){let s=e[a];if(E(s)){m.debug("ABR","Creating new BandwidthEstimator",{bufferType:a});let d=new Pr;return e[a]=d,d}return s}}function fg({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:o,playbackObserver:a,representations:s},d){let u=new Er,c=new vr(i!=null?i:0,o),l=new Ar,f=te,p={metrics:T,requestBegin:v,requestProgress:_,requestEnd:R,addedSegment(k){f(k)}},h=new U;h.linkToSignal(d);let I=g(s.getValue(),h.signal);return s.onUpdate(b,{clearSignal:d}),{estimates:I,callbacks:p};function g(k,x){if(k.length<=1)return new j({bitrate:void 0,representation:k[0],urgent:!0,knownStableBitrate:void 0});let P=!1,M=k.sort((K,q)=>K.bitrate-q.bitrate),L=new _r(M.map(K=>K.bitrate)),F=new Rr,D=new kr(u,F),B=a.getReference().getValue(),A=new j(N());return a.listen(K=>{B=K,C()},{includeLastObservation:!1,clearSignal:x}),f=function(K){if(B===null)return;let{position:q,speed:X}=B,W=K.buffered,H=Ro(W,q.getWanted()),{representation:G}=K.content,ie=u.getEstimate(G),oe=G.bitrate,fe={bufferGap:H,currentBitrate:oe,currentScore:ie,speed:X};L.onAddedSegment(fe),C()},x.register(()=>{f=te}),r.throttleBitrate.onUpdate(C,{clearSignal:x}),r.limitResolution.onUpdate(C,{clearSignal:x}),A;function C(){A.setValue(N())}function N(){let{bufferGap:K,position:q,maximumPosition:X}=B,W=r.limitResolution.getValue(),H=r.throttleBitrate.getValue(),G=t.getValue(),ie=mg(M,W,H),oe=l.getRequests(),{bandwidthEstimate:fe,bitrateChosen:Re}=c.getBandwidthEstimate(B,n,G,oe,F.bandwidth),ge=u.getLastStableRepresentation(),he=ge===null?void 0:ge.bitrate/(B.speed>0?B.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:_t,ABR_EXIT_BUFFER_BASED_ALGO:ee}=O.getCurrent();P&&K<=ee?P=!1:!P&&isFinite(K)&&K>=_t&&(P=!0);let ye=Ao(ie,Re),ot=L.getLastEstimate(),pn=ye.bitrate,ht=null;P&&ot!==void 0&&ot>pn&&(ht=Ao(ie,ot),pn=ht.bitrate);let yt=null;return o&&G!==null&&e.manifest.isDynamic&&X-q.getWanted()<40&&(yt=D.getGuess(M,B,G,pn,oe)),yt!==null&&yt.bitrate>pn?(m.debug("ABR","new guess-based estimate",{bitrate:yt.bitrate,representation:yt.id}),F.update(yt,fe,2),{bitrate:fe,representation:yt,urgent:G===null||yt.bitrate<G.bitrate,knownStableBitrate:he}):ht!==null?(m.debug("ABR","new buffer-based estimate",{bitrate:ht.bitrate,representation:ht.id}),F.update(ht,fe,0),{bitrate:fe,representation:ht,urgent:c.isUrgent(ht.bitrate,G,oe,B),knownStableBitrate:he}):(m.debug("ABR","new bandwidth estimate",{bitrate:ye.bitrate,representation:ye.id}),F.update(ye,fe,1),{bitrate:fe,representation:ye,urgent:c.isUrgent(ye.bitrate,G,oe,B),knownStableBitrate:he})}}function b(){let k=s.getValue();h.cancel(),h=new U,h.linkToSignal(d),g(k,h.signal).onUpdate(function(M){I.setValue(M)},{clearSignal:h.signal,emitCurrentValue:!0})}function T(k){let{requestDuration:x,segmentDuration:P,size:M,content:L}=k;if(n.addSample(x,M),!L.segment.isInit){let{segment:F,representation:D}=L;if(P===void 0&&!F.complete)return;let B=P!=null?P:F.duration;u.addSample(D,x/1e3,B)}}function v(k){l.add(k)}function _(k){l.addProgress(k)}function R(k){l.remove(k.id)}}function mg(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=ls(r,t)),e!==void 0&&(r=cs(r,e)),r}var _c=fs;function Mo(){var t;if(typeof((t=Z.crypto)==null?void 0:t.randomUUID)=="function")return Z.crypto.randomUUID();let n=new Date().getTime(),e=z();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let i=Math.random()*16;return n>0?(i=(n+i)%16|0,n=Math.floor(n/16)):(i=(e+i)%16|0,e=Math.floor(e/16)),(r==="x"?i:i&3|8).toString(16)})}function w(n){return typeof n=="string"&&n.length>0}function Ce(n,e,t){if(typeof String.prototype.startsWith=="function")return n.startsWith(e,t);let r=typeof t=="number"?Math.max(t,0):0;return n.substring(r,r+e.length)===e}var pg=/^(?:[a-z]+:)?\/\//i,gg=/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function wr(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(pg.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?wr(n.substring(0,t)):e+1}function vc(n,e){let t=xo(n),r=xo(e);if(t.scheme!==r.scheme||t.authority!==r.authority||t.path[0]!==void 0&&t.path[0]!=="/"&&r.path[0]==="/"||r.path[0]!==void 0&&r.path[0]!=="/"&&t.path[0]==="/")return null;let i=xr(t.path),o=xr(r.path),a;if(i===o)a="";else{let d=i.split("/");d.pop();let u=o.split("/");for(;d.length>0&&u.length>0&&d[0]===u[0];)d.shift(),u.shift();for(;d.length>0;)d.shift(),u.unshift("..");let c=u.join("/");(c.endsWith("../")||c.endsWith("./"))&&(c=c.slice(0,c.length-1)),a=c===""?".":c}let s=a;return a===""&&r.query===t.query||w(r.query)&&(s+="?",s+=r.query),w(r.fragment)&&(s+="#",s+=r.fragment),s}function hg(n,e){let t=xo(n),r=xo(e);if(w(r.scheme))return ms(r);let i={scheme:t.scheme,authority:t.authority,path:"",query:r.query,fragment:r.fragment};return w(r.authority)?(i.authority=r.authority,i.path=xr(r.path),ms(i)):(r.path===""?(i.path=t.path,w(r.query)||(i.query=t.query)):Ce(r.path,"/")?i.path=xr(r.path):i.path=xr(Ig(t,r.path)),ms(i))}var Mr=new Map,yg=200;function xo(n){var r,i,o,a,s;if(Mr.has(n))return Mr.get(n);let e=n.match(gg),t;return e===null?t={scheme:"",authority:"",path:"",query:"",fragment:""}:t={scheme:(r=e[1])!=null?r:"",authority:(i=e[2])!=null?i:"",path:(o=e[3])!=null?o:"",query:(a=e[4])!=null?a:"",fragment:(s=e[5])!=null?s:""},Mr.size>=yg&&Mr.clear(),Mr.set(n,t),t}function ms(n){let e="";return w(n.scheme)&&(e+=n.scheme+":"),w(n.authority)&&(e+="//"+n.authority),e+=n.path,w(n.query)&&(e+="?"+n.query),w(n.fragment)&&(e+="#"+n.fragment),e}function xr(n){let e=n.split(/(?=\/)/),t=[];for(let r=0;r<e.length;r++){let i=e[r];if(!(i===".."||i==="."||i==="")){if(i==="/.."){t.pop(),r===e.length-1&&t.push("/");continue}if(i==="/."){r===e.length-1&&t.push("/");continue}t.push(i)}}return t.join("")}function Ig(n,e){if(w(n.authority)&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function hn(...n){var r,i,o;let e=n.filter(a=>a!==""),t=e.length;if(t===0)return"";if(t===1)return(r=e[0])!=null?r:"";{let a=(i=e[0])!=null?i:"",s=(o=e[1])!=null?o:"",d=hg(a,s),u=e.slice(2);return hn(d,...u)}}var bg=4,Or=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:Mo(),this._contentId=(r=e.contentId)!=null?r:Mo(),this._typePreference=e.communicationType==="headers"?0:1,this._bufferStarvationToggle=!1,this._playbackObserver=null,this._lastThroughput={},this._canceller=null}startMonitoringPlayback(e){var t;(t=this._canceller)==null||t.cancel(),this._canceller=new U,this._playbackObserver=e,e.listen(r=>{r.rebuffering!==null&&(this._bufferStarvationToggle=!0)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}stopMonitoringPlayback(){var e;(e=this._canceller)==null||e.cancel(),this._canceller=null,this._playbackObserver=null}updateThroughput(e,t){this._lastThroughput[e]=t}_getCommonCmcdData(e){var i;let t={};t.bs=this._bufferStarvationToggle,this._bufferStarvationToggle=!1,t.cid=this._contentId,t.mtp=e!==void 0?Math.floor(Math.round(e/1e3/100)*100):void 0,t.sid=this._sessionId;let r=(i=this._playbackObserver)==null?void 0:i.getReference().getValue();return t.pr=r===void 0||r.speed===1?void 0:r.speed,r!==void 0&&(t.su=r.rebuffering!==null),t}getCmcdDataForManifest(e){var r;let t=this._getCommonCmcdData((r=this._lastThroughput.video)!=null?r:this._lastThroughput.audio);switch(t.ot="m",e){case"dash":t.sf="d";break;case"smooth":t.sf="s";break;default:t.sf="o";break}return this._producePayload(t)}getCmcdDataForSegmentRequest(e){var a,s,d,u;let t=(a=this._playbackObserver)==null?void 0:a.getReference().getValue(),r=this._getCommonCmcdData(this._lastThroughput[e.adaptation.type]);switch(r.br=Math.round(e.representation.bitrate/1e3),r.d=Math.round(e.segment.duration*1e3),e.adaptation.type){case"video":r.ot="v";break;case"audio":r.ot="a";break;case"text":r.ot="c";break}if(e.segment.isInit&&(r.ot="i"),!E(e.nextSegment)&&e.segment.url!==null&&e.nextSegment.url!==null&&(!e.nextSegment.isInit||e.nextSegment.indexRange===void 0)){let c=e.segment.url,l=e.nextSegment.url,f=vc(c,l);f!==null&&(f!=="."&&(r.nor=encodeURIComponent(f)),e.nextSegment.range!==void 0&&(r.nrr=String(e.nextSegment.range[0])+"-",isFinite(e.nextSegment.range[1])&&(r.nrr+=String(e.nextSegment.range[1]))))}let i;if(t!==void 0&&(r.ot==="v"||r.ot==="a"||r.ot==="av")){let c=t.buffered[e.adaptation.type];if(!E(c)){let l=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let f of c)if(l>=f.start&&l<f.end){i=(f.end-l)*1e3,r.bl=Math.floor(Math.round(i/100)*100);break}}}let o=i===void 0||t===void 0?void 0:i/t.speed;if(r.dl=o===void 0?void 0:Math.floor(Math.round(o/100)*100),o!==void 0){let l=e.representation.bitrate*e.segment.duration/1e3/(o/1e3);r.rtp=Math.floor(Math.round(l*bg/100)*100)}switch(e.manifest.transport){case"dash":r.sf="d";break;case"smooth":r.sf="s";break;default:r.sf="o";break}return r.st=e.manifest.isDynamic?"l":"v",r.tb=e.adaptation.representations.reduce((c,l)=>l.isPlayable()!==!0?c:c===void 0?Math.round(l.bitrate/1e3):Math.max(c,Math.round(l.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,c)=>{this._typePreference===0?t[c]+=u:r+=u},o=(u,c)=>{let l=e[u];if(l!==void 0){let f=`${u}=${String(l)},`;i(f,c)}},a=(u,c)=>{if(e[u]===!0){let l=`${u},`;i(l,c)}},s=(u,c)=>{let l=e[u];if(l!==void 0){let p=`prop=${`"${l.replace("\\","\\\\").replace('"','\\"')}"`},`;i(p,c)}},d=(u,c)=>{let l=e[u];if(l!==void 0){let f=`prop=${l},`;i(f,c)}};return o("bl","request"),o("br","object"),a("bs","status"),s("cid","session"),o("d","object"),o("dl","request"),o("mtp","request"),s("nor","request"),s("nrr","request"),d("ot","object"),o("pr","session"),o("rtp","status"),d("sf","session"),s("sid","session"),d("st","session"),a("su","request"),o("tb","object"),this._typePreference===0?(t.object[t.object.length-1]===","&&(t.object=t.object.substring(0,t.object.length-1)),t.request[t.request.length-1]===","&&(t.request=t.request.substring(0,t.request.length-1)),t.session[t.session.length-1]===","&&(t.session=t.session.substring(0,t.session.length-1)),t.status[t.status.length-1]===","&&(t.status=t.status.substring(0,t.status.length-1)),m.debug("CMCD","proposing headers payload"),{type:"headers",value:{"CMCD-Object":t.object,"CMCD-Request":t.request,"CMCD-Session":t.session,"CMCD-Status":t.status}}):(r[r.length-1]===","&&(r=r.substring(0,r.length-1)),r=encodeURIComponent(r),m.debug("CMCD","proposing query string payload",{queryString:r}),{type:"query",value:[["CMCD",r]]})}};var Rc=Or;var Wn=class extends se{constructor(e){super(),this._downgradedCdnList={metadata:[],timeouts:[]},e.register(()=>{for(let t of this._downgradedCdnList.timeouts)clearTimeout(t);this._downgradedCdnList={metadata:[],timeouts:[]}})}getCdnPreferenceForResource(e){return e.length<=1?e:this._innerGetCdnPreferenceForResource(e)}downgradeCdn(e){let t=kc(this._downgradedCdnList.metadata,e);t>=0&&this._removeIndexFromDowngradeList(t);let{DEFAULT_CDN_DOWNGRADE_TIME:r}=O.getCurrent(),i=r;this._downgradedCdnList.metadata.push(e);let o=setTimeout(()=>{let a=kc(this._downgradedCdnList.metadata,e);a>=0&&this._removeIndexFromDowngradeList(a),this.trigger("priorityChange",null)},i);this._downgradedCdnList.timeouts.push(o),this.trigger("priorityChange",null)}_innerGetCdnPreferenceForResource(e){let[t,r]=e.reduce((i,o)=>(this._downgradedCdnList.metadata.some(a=>a.id===o.id&&a.baseUrl===o.baseUrl)?i[1].push(o):i[0].push(o),i),[[],[]]);return t.concat(r)}_removeIndexFromDowngradeList(e){this._downgradedCdnList.metadata.splice(e,1);let t=this._downgradedCdnList.timeouts.splice(e,1);clearTimeout(t[0])}};function kc(n,e){return n.length===0?-1:e.id!==void 0?Ie(n,t=>t.id===e.id):Ie(n,t=>t.baseUrl===e.baseUrl)}var dt=class n extends Error{constructor(e,t,r){super(e),Object.setPrototypeOf(this,n.prototype),this.name="CustomLoaderError",this.canRetry=t,this.xhr=r}};var Ae=class n extends Error{constructor(e,t,r){let i;switch(r){case"TIMEOUT":i="The request timed out";break;case"ERROR_EVENT":i="An error prevented the request to be performed successfully";break;case"PARSE_ERROR":i="An error happened while formatting the response data";break;case"ERROR_HTTP_CODE":i="An HTTP status code indicating failure was received: "+String(t);break}super(i),Object.setPrototypeOf(this,n.prototype),this.name="RequestError",this.url=e,this.status=t,this.type=r}serialize(){return{url:this.url,status:this.status,type:this.type}}},He={TIMEOUT:"TIMEOUT",ERROR_EVENT:"ERROR_EVENT",ERROR_HTTP_CODE:"ERROR_HTTP_CODE",PARSE_ERROR:"PARSE_ERROR"};var ps=typeof Headers=="function"?Headers:null,wo=typeof AbortController=="function"?AbortController:null;function Oo(n){var f,p;let e;if(!E(n.headers))if(E(ps))e=n.headers;else{e=new ps;let h=Object.keys(n.headers);for(let I=0;I<h.length;I++){let g=h[I];e.append(g,n.headers[g])}}m.debug("utils","Fetch",{url:n.url});let t=null,r=!1,i=!1,o=z(),a=E(wo)?null:new wo;function s(){if(E(a)){m.warn("utils","Fetch: AbortController API not available.");return}a.abort()}let d;n.timeout!==void 0&&(d=setTimeout(()=>{r=!0,u!==void 0&&clearTimeout(u),s()},n.timeout));let u;n.connectionTimeout!==void 0&&(u=setTimeout(()=>{i=!0,d!==void 0&&clearTimeout(d),s()},n.connectionTimeout));let c=n.cancelSignal.register(function(I){t=I,s()}),l={method:"GET"};if(e!==void 0&&(l.headers=e),l.signal=E(a)?null:a.signal,m.hasLevel("DEBUG")){let h="fetch GET "+n.url;n.timeout!==void 0&&(h+=" to="+String(n.timeout/1e3)),n.connectionTimeout!==void 0&&(h+=" cto="+String(n.connectionTimeout/1e3)),((f=n.headers)==null?void 0:f.Range)!==void 0&&(h+=" Range="+((p=n.headers)==null?void 0:p.Range)),m.debug("utils",h)}return fetch(n.url,l).then(h=>{if(u!==void 0&&clearTimeout(u),h.status>=300)throw m.warn("utils","Fetch: Request HTTP Error",{status:h.status,responseUrl:h.url}),new Ae(h.url,h.status,He.ERROR_HTTP_CODE);if(E(h.body))throw new Ae(h.url,h.status,He.PARSE_ERROR);let I=h.headers.get("Content-Length"),g=!E(I)&&!isNaN(+I)?+I:void 0,b=h.body.getReader(),T=0;return v();async function v(){let _=await b.read();if(!_.done&&!E(_.value)){T+=_.value.byteLength;let R=z(),k={url:h.url,currentTime:R,duration:R-o,sendingTime:o,chunkSize:_.value.byteLength,chunk:_.value.buffer,size:T,totalSize:g};return n.onData(k),v()}else if(_.done){d!==void 0&&clearTimeout(d),c();let R=z();return{requestDuration:R-o,receivedTime:R,sendingTime:o,size:T,status:h.status,url:h.url}}return v()}}).catch(h=>{throw t!==null?t:(c(),r?(m.warn("utils","Fetch: Request timed out.",{url:n.url,timeout:n.timeout}),new Ae(n.url,0,He.TIMEOUT)):i?(m.warn("utils","Fetch: Request connection timed out.",{url:n.url,connectionTimeout:n.connectionTimeout}),new Ae(n.url,0,He.TIMEOUT)):h instanceof Ae?h:(m.warn("utils","Fetch: Request Error",{error:h instanceof Error?h.toString():"Unkwown Error"}),new Ae(n.url,0,He.ERROR_EVENT)))})}function Dr(){let n=/\[\s*native\s+code\s*\]/;return typeof Z.fetch=="function"&&!E(wo)&&n.test(wo.toString())&&!E(ps)}var Sg="json";function Lr(n){let e={url:n.url,headers:n.headers,responseType:E(n.responseType)?Sg:n.responseType,timeout:n.timeout,connectionTimeout:n.connectionTimeout};return new Promise((t,r)=>{let{onProgress:i,cancelSignal:o}=n,{url:a,headers:s,responseType:d,timeout:u,connectionTimeout:c}=e,l=new XMLHttpRequest;l.open("GET",a,!0);let f;u!==void 0&&(l.timeout=u,f=setTimeout(()=>{g(),r(new Ae(a,l.status,He.TIMEOUT))},u+3e3));let p;if(c!==void 0&&(p=setTimeout(()=>{g(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(new Ae(a,l.status,He.TIMEOUT))},c)),l.responseType=d,l.responseType==="document"&&l.overrideMimeType("text/xml"),!E(s)){let b=s;for(let T in b)Object.prototype.hasOwnProperty.call(b,T)&&l.setRequestHeader(T,b[T])}let h=z(),I=null;if(o!==void 0&&(I=o.register(function(T){g(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(T)}),o.isCancelled()))return;if(l.onerror=function(){g(),r(new Ae(a,l.status,He.ERROR_EVENT))},l.ontimeout=function(){g(),r(new Ae(a,l.status,He.TIMEOUT))},c!==void 0&&(l.onreadystatechange=function(){l.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&clearTimeout(p)}),i!==void 0&&(l.onprogress=function(T){let v=z();i({url:a,duration:v-h,sendingTime:h,currentTime:v,size:T.loaded,totalSize:T.total})}),l.onload=function(T){if(l.readyState===XMLHttpRequest.DONE)if(g(),l.status>=200&&l.status<300){let v=z(),_=l.response instanceof ArrayBuffer?l.response.byteLength:T.total,R=l.status,k=l.responseType,x=w(l.responseURL)?l.responseURL:a,P;if(k==="json"?P=typeof l.response=="object"?l.response:Tg(l.responseText):P=l.response,E(P)){r(new Ae(a,l.status,He.PARSE_ERROR));return}t({status:R,url:x,responseType:k,sendingTime:h,receivedTime:v,requestDuration:v-h,size:_,responseData:P})}else r(new Ae(a,l.status,He.ERROR_HTTP_CODE))},m.hasLevel("DEBUG")){let b="XHR GET "+a;n.responseType!==void 0&&(b+=" type="+n.responseType),u!==void 0&&(b+=" to="+String(u/1e3)),c!==void 0&&(b+=" cto="+String(c/1e3)),(s==null?void 0:s.Range)!==void 0&&(b+=" Range="+(s==null?void 0:s.Range)),m.debug("utils",b)}l.send();function g(){f!==void 0&&clearTimeout(f),p!==void 0&&clearTimeout(p),I!==null&&I()}})}function Tg(n){try{return JSON.parse(n)}catch(e){return null}}var ke=Lr;var yn=He,tt={NETWORK_ERROR:"NETWORK_ERROR",MEDIA_ERROR:"MEDIA_ERROR",ENCRYPTED_MEDIA_ERROR:"ENCRYPTED_MEDIA_ERROR",OTHER_ERROR:"OTHER_ERROR"},gs={PIPELINE_LOAD_ERROR:"PIPELINE_LOAD_ERROR",PIPELINE_PARSE_ERROR:"PIPELINE_PARSE_ERROR",INTEGRITY_ERROR:"INTEGRITY_ERROR",MANIFEST_PARSE_ERROR:"MANIFEST_PARSE_ERROR",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"MANIFEST_INCOMPATIBLE_CODECS_ERROR",MANIFEST_UPDATE_ERROR:"MANIFEST_UPDATE_ERROR",MANIFEST_UNSUPPORTED_ADAPTATION_TYPE:"MANIFEST_UNSUPPORTED_ADAPTATION_TYPE",MEDIA_STARTING_TIME_NOT_FOUND:"MEDIA_STARTING_TIME_NOT_FOUND",MEDIA_TIME_BEFORE_MANIFEST:"MEDIA_TIME_BEFORE_MANIFEST",MEDIA_TIME_AFTER_MANIFEST:"MEDIA_TIME_AFTER_MANIFEST",MEDIA_TIME_NOT_FOUND:"MEDIA_TIME_NOT_FOUND",NO_PLAYABLE_REPRESENTATION:"NO_PLAYABLE_REPRESENTATION",MEDIA_IS_ENCRYPTED_ERROR:"MEDIA_IS_ENCRYPTED_ERROR",CREATE_MEDIA_KEYS_ERROR:"CREATE_MEDIA_KEYS_ERROR",MEDIA_KEYS_ATTACHMENT_ERROR:"MEDIA_KEYS_ATTACHMENT_ERROR",KEY_ERROR:"KEY_ERROR",KEY_STATUS_CHANGE_ERROR:"KEY_STATUS_CHANGE_ERROR",KEY_UPDATE_ERROR:"KEY_UPDATE_ERROR",KEY_LOAD_ERROR:"KEY_LOAD_ERROR",KEY_LOAD_TIMEOUT:"KEY_LOAD_TIMEOUT",KEY_GENERATE_REQUEST_ERROR:"KEY_GENERATE_REQUEST_ERROR",INCOMPATIBLE_KEYSYSTEMS:"INCOMPATIBLE_KEYSYSTEMS",INVALID_ENCRYPTED_EVENT:"INVALID_ENCRYPTED_EVENT",INVALID_KEY_SYSTEM:"INVALID_KEY_SYSTEM",LICENSE_SERVER_CERTIFICATE_ERROR:"LICENSE_SERVER_CERTIFICATE_ERROR",MULTIPLE_SESSIONS_SAME_INIT_DATA:"MULTIPLE_SESSIONS_SAME_INIT_DATA",BUFFER_APPEND_ERROR:"BUFFER_APPEND_ERROR",BUFFER_FULL_ERROR:"BUFFER_FULL_ERROR",BUFFER_TYPE_UNKNOWN:"BUFFER_TYPE_UNKNOWN",MEDIA_ERR_BLOCKED_AUTOPLAY:"MEDIA_ERR_BLOCKED_AUTOPLAY",MEDIA_ERR_PLAY_NOT_ALLOWED:"MEDIA_ERR_PLAY_NOT_ALLOWED",MEDIA_ERR_NOT_LOADED_METADATA:"MEDIA_ERR_NOT_LOADED_METADATA",MEDIA_ERR_ABORTED:"MEDIA_ERR_ABORTED",MEDIA_ERR_NETWORK:"MEDIA_ERR_NETWORK",MEDIA_ERR_DECODE:"MEDIA_ERR_DECODE",MEDIA_ERR_SRC_NOT_SUPPORTED:"MEDIA_ERR_SRC_NOT_SUPPORTED",MEDIA_ERR_UNKNOWN:"MEDIA_ERR_UNKNOWN",MEDIA_SOURCE_NOT_SUPPORTED:"MEDIA_SOURCE_NOT_SUPPORTED",MEDIA_KEYS_NOT_SUPPORTED:"MEDIA_KEYS_NOT_SUPPORTED",DISCONTINUITY_ENCOUNTERED:"DISCONTINUITY_ENCOUNTERED",NONE:"NONE",NO_AUDIO_VIDEO_TRACKS:"NO_AUDIO_VIDEO_TRACKS"};function nt(n,e){return`${n}: ${e}`}var be=class n extends Error{constructor(e,t,r){super(nt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="EncryptedMediaError",this.type=tt.ENCRYPTED_MEDIA_ERROR,this.code=e,this._originalMessage=t,this.fatal=!1,this.keyStatuses=r.keyStatuses,this.keySystemConfiguration=r.keySystemConfiguration,this.keySystem=r.keySystem}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage,keyStatuses:this.keyStatuses,keySystemConfiguration:this.keySystemConfiguration,keySystem:this.keySystem}}};var re=class n extends Error{constructor(e,t,r){super(nt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="MediaError",this.type=tt.MEDIA_ERROR,this._originalMessage=t,this.code=e,this.fatal=!1,(r==null?void 0:r.tracks)!==void 0&&(r==null?void 0:r.tracks.length)>0&&(this.tracksInfo=r.tracks)}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage,tracks:this.tracksInfo}}};var ut=class n extends Error{constructor(e,t){super(nt(e,t.message)),Object.setPrototypeOf(this,n.prototype),this.name="NetworkError",this.type=tt.NETWORK_ERROR,this.url=t.url,this.status=t.status,this.errorType=t.type,this._baseError=t,this.code=e,this.fatal=!1}isHttpError(e){return this.errorType===yn.ERROR_HTTP_CODE&&this.status===e}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,baseError:this._baseError.serialize()}}};var We=class n extends Error{constructor(e,t){super(nt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="OtherError",this.type=tt.OTHER_ERROR,this.code=e,this.fatal=!1,this._originalMessage=t}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage}}};function Zt(n){return(n instanceof be||n instanceof re||n instanceof We||n instanceof ut)&&Object.keys(tt).indexOf(n.type)>=0}function Me(n,{defaultCode:e,defaultReason:t}){if(Zt(n))return n;let r=n instanceof Error?n.toString():t;return new We(e,r)}var lt=class n extends Error{constructor(e,t,r){super(t),Object.setPrototypeOf(this,n.prototype),this.name="SourceBufferError",this.errorName=e,this.isBufferFull=r}serialize(){return{errorName:this.name,message:this.message,isBufferFull:this.isBufferFull}}toString(){return`${this.errorName}: ${this.message}`}};var Eg={aa:"aar",ab:"abk",ae:"ave",af:"afr",ak:"aka",am:"amh",an:"arg",ar:"ara",as:"asm",av:"ava",ay:"aym",az:"aze",ba:"bak",be:"bel",bg:"bul",bi:"bis",bm:"bam",bn:"ben",bo:"bod",br:"bre",bs:"bos",ca:"cat",ce:"che",ch:"cha",co:"cos",cr:"cre",cs:"ces",cu:"chu",cv:"chv",cy:"cym",da:"dan",de:"deu",dv:"div",dz:"dzo",ee:"ewe",el:"ell",en:"eng",eo:"epo",es:"spa",et:"est",eu:"eus",fa:"fas",ff:"ful",fi:"fin",fj:"fij",fo:"fao",fr:"fra",fy:"fry",ga:"gle",gd:"gla",gl:"glg",gn:"grn",gu:"guj",gv:"glv",ha:"hau",he:"heb",hi:"hin",ho:"hmo",hr:"hrv",ht:"hat",hu:"hun",hy:"hye",hz:"her",ia:"ina",id:"ind",ie:"ile",ig:"ibo",ii:"iii",ik:"ipk",io:"ido",is:"isl",it:"ita",iu:"iku",ja:"jpn",jv:"jav",ka:"kat",kg:"kon",ki:"kik",kj:"kua",kk:"kaz",kl:"kal",km:"khm",kn:"kan",ko:"kor",kr:"kau",ks:"kas",ku:"kur",kv:"kom",kw:"cor",ky:"kir",la:"lat",lb:"ltz",lg:"lug",li:"lim",ln:"lin",lo:"lao",lt:"lit",lu:"lub",lv:"lav",mg:"mlg",mh:"mah",mi:"mri",mk:"mkd",ml:"mal",mn:"mon",mr:"mar",ms:"msa",mt:"mlt",my:"mya",na:"nau",nb:"nob",nd:"nde",ne:"nep",ng:"ndo",nl:"nld",nn:"nno",no:"nor",nr:"nbl",nv:"nav",ny:"nya",oc:"oci",oj:"oji",om:"orm",or:"ori",os:"oss",pa:"pan",pi:"pli",pl:"pol",ps:"pus",pt:"por",qu:"que",rm:"roh",rn:"run",ro:"ron",ru:"rus",rw:"kin",sa:"san",sc:"srd",sd:"snd",se:"sme",sg:"sag",si:"sin",sk:"slk",sl:"slv",sm:"smo",sn:"sna",so:"som",sq:"sqi",sr:"srp",ss:"ssw",st:"sot",su:"sun",sv:"swe",sw:"swa",ta:"tam",te:"tel",tg:"tgk",th:"tha",ti:"tir",tk:"tuk",tl:"tgl",tn:"tsn",to:"ton",tr:"tur",ts:"tso",tt:"tat",tw:"twi",ty:"tah",ug:"uig",uk:"ukr",ur:"urd",uz:"uzb",ve:"ven",vi:"vie",vo:"vol",wa:"wln",wo:"wol",xh:"xho",yi:"yid",yo:"yor",za:"zha",zh:"zho",zu:"zul"},Pc=Eg;var _g={alb:"sqi",arm:"hye",baq:"eus",bur:"mya",chi:"zho",cze:"ces",dut:"nld",fre:"fra",geo:"kat",ger:"deu",gre:"ell",ice:"isl",mac:"mkd",mao:"mri",may:"msa",per:"fas",slo:"slk",rum:"ron",tib:"bod",wel:"cym"},Cc=_g;function vg(n){if(E(n)||n==="")return"und";let t=(""+n).toLowerCase().split("-")[0],r=Rg(t);return w(r)?r:n}function Rg(n){let e;switch(n.length){case 2:e=Pc[n];break;case 3:e=Cc[n];break}return e}var Ac=vg;var Nr=Ac;function Se(n,e){if(n.length!==e.length)return!1;if(n===e)return!0;for(let t=n.length-1;t>=0;t--)if(n[t]!==e[t])return!1;return!0}var Jt=["audio","video","text"];function bn(n){var o,a;let e=n.timeBounds;if(e.timeshiftDepth===null)return(o=e.minimumSafePosition)!=null?o:0;let{maximumTimeData:t}=e,r;if(!e.maximumTimeData.isLinear)r=t.maximumSafePosition;else{let s=z()-t.time;r=t.maximumSafePosition+s/1e3}let i=r-e.timeshiftDepth;return Math.max((a=e.minimumSafePosition)!=null?a:0,i)}function Sn(n){let{maximumTimeData:e}=n.timeBounds;if(!n.isLive||e.livePosition===void 0)return;if(!e.isLinear)return e.livePosition;let t=z()-e.time;return e.livePosition+t/1e3}function kt(n){let{maximumTimeData:e}=n.timeBounds;if(!e.isLinear)return e.maximumSafePosition;let t=z()-e.time;return e.maximumSafePosition+t/1e3}function Ot(n,e){if(e===void 0)return ys(n).filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1);let t=n.adaptations[e];return t===void 0?[]:t.filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1)}function Hn(n,e){let t=null;for(let r=n.periods.length-1;r>=0;r--){let i=n.periods[r];if(hs(i,e,t))return i;t=i}}function Do(n,e){let t=e.end;if(t===void 0)return null;let r=Q(n.periods,i=>i.end===void 0||t<i.end);return r===void 0?null:r}function hs(n,e,t){return e>=n.start&&(n.end===void 0||e<n.end)?!0:e===n.end&&(t===null||t.start>n.end)}function ys(n){let e=n.adaptations;return Cr(e).reduce((t,r)=>E(r)?t:t.concat(r),[])}function Lo(n,e){var r,i;let t={language:(r=n.language)!=null?r:"",normalized:(i=n.normalizedLanguage)!=null?i:"",audioDescription:n.isAudioDescription===!0,id:n.id,representations:(e?n.representations.filter(o=>Rt(o)===!0):n.representations).map(Bo),label:n.label};return n.isDub===!0&&(t.dub=!0),t}function No(n){var e,t;return{language:(e=n.language)!=null?e:"",normalized:(t=n.normalizedLanguage)!=null?t:"",closedCaption:n.isClosedCaption===!0,id:n.id,label:n.label,forced:n.isForcedSubtitles}}function Uo(n,e){let t=n.trickModeTracks!==void 0?n.trickModeTracks.map(i=>{let o=(e?i.representations.filter(s=>Rt(s)===!0):i.representations).map(In),a={id:i.id,representations:o,isTrickModeTrack:!0};return i.isSignInterpreted===!0&&(a.signInterpreted=!0),a}):void 0,r={id:n.id,representations:(e?n.representations.filter(i=>Rt(i)===!0):n.representations).map(In),label:n.label};return n.isSignInterpreted===!0&&(r.signInterpreted=!0),n.isTrickModeTrack===!0&&(r.isTrickModeTrack=!0),t!==void 0&&(r.trickModeTracks=t),r}function Bo(n){let{id:e,bitrate:t,codecs:r,isSpatialAudio:i,isSupported:o,decipherable:a}=n;return{id:e,bitrate:t,codec:r==null?void 0:r[0],isSpatialAudio:i,isCodecSupported:o,decipherable:a}}function In(n){let{id:e,bitrate:t,frameRate:r,width:i,height:o,codecs:a,hdrInfo:s,isSupported:d,decipherable:u,contentProtections:c}=n;return{id:e,bitrate:t,frameRate:r,width:i,height:o,codec:a==null?void 0:a[0],hdrInfo:s,isCodecSupported:d,decipherable:u,contentProtections:c!==void 0?{keyIds:c.keyIds}:void 0}}function Tn(n){switch(n.type){case"audio":return{type:"audio",track:Lo(n,!1)};case"video":return{type:"video",track:Uo(n,!1)};case"text":return{type:"text",track:No(n)}}}function Rt(n){return n.decipherable===!1?!1:n.isSupported}function Mc(n){return new Function(`return (${n}(arguments[0], arguments[1]))`)}function rt(){let n="",e=-1;return function(){return e++,e>=Number.MAX_SAFE_INTEGER&&(n+="0",e=0),n+String(e)}}var wc=typeof Z=="object"&&typeof Z.TextDecoder=="function",kg=typeof Z=="object"&&typeof Z.TextEncoder=="function";function Fo(n){let e=new ArrayBuffer(n.length*2),t=new Uint8Array(e);for(let r=0;r<t.length;r+=2){let i=n.charCodeAt(r/2);t[r]=i&255,t[r+1]=i>>8&255}return t}function Ko(n){if(wc)try{return new TextDecoder("utf-16le").decode(n)}catch(t){let r=t instanceof Error?t:"Unknown Error";m.warn("utils","could not use TextDecoder to parse UTF-16LE, fallbacking to another implementation",r)}let e="";for(let t=0;t<n.length;t+=2)e+=String.fromCharCode((n[t+1]<<8)+n[t]);return e}function Te(n){if(kg)try{return new TextEncoder().encode(n)}catch(i){let o=i instanceof Error?i:"Unknown Error";m.warn("utils","Could not use TextEncoder to encode string into UTF-8, fallbacking to another implementation",o)}let e,t=encodeURIComponent(n);if(typeof unescape=="function")e=unescape(t);else{let i=/[0-9a-fA-F]/,o=t.length;e="";for(let a=0;a<t.length;a++){let s=!1;if(t[a]==="%"){if(a<=o-6&&t[a+1]==="u"&&i.test(t[a+2])&&i.test(t[a+3])&&i.test(t[a+4])&&i.test(t[a+5])){let d=parseInt(t.substring(a+1,a+6),16);e+=String.fromCharCode(d),s=!0,a+=5}else if(a<=o-3&&i.test(t[a+1])&&i.test(t[a+2])){let d=parseInt(t.substring(a+1,a+3),16);e+=String.fromCharCode(d),s=!0,a+=2}}s||(e+=t[a])}}let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i)&255;return r}function Pg(n){let t="";for(let r=0;r<n.length;r+=16e3){let i=n.subarray(r,r+16e3);t+=String.fromCharCode.apply(null,i)}return t}function xc(n,e){let t=n.toString(16);return t.length>=e?t:new Array(e-t.length+1).join("0")+t}function ce(n){if(wc)try{return new TextDecoder().decode(n)}catch(i){let o=i instanceof Error?i:"Unknown Error";m.warn("utils","could not use TextDecoder to parse UTF-8, fallbacking to another implementation",o)}let e=n;e[0]===239&&e[1]===187&&e[2]===191&&(e=e.subarray(3));let t=Pg(e),r;if(typeof escape=="function")r=escape(t);else{let i=/[A-Za-z0-9*_+-./]/;r="";for(let o=0;o<t.length;o++)if(i.test(t[o]))r+=t[o];else{let a=t.charCodeAt(o);r+=a>=256?"%u"+xc(a,4):"%"+xc(a,2)}}return decodeURIComponent(r)}function Xe(n){let e=n.length,t=new Uint8Array(e/2);for(let r=0,i=0;r<e;r+=2,i++)t[i]=parseInt(n.substring(r,r+2),16)&255;return t}function Ne(n,e=""){let t="";for(let r=0;r<n.byteLength;r++)t+=(n[r]>>>4).toString(16),t+=(n[r]&15).toString(16),e.length>0&&r<n.byteLength-1&&(t+=e);return t}function Vo(n){ne(n.length===16,"GUID length should be 16");let e=n[0],t=n[1],r=n[2],i=n[3],o=n[4],a=n[5],s=n[6],d=n[7],u=new Uint8Array(16);return u[0]=i,u[1]=r,u[2]=t,u[3]=e,u[4]=a,u[5]=o,u[6]=d,u[7]=s,u.set(n.subarray(8,16),8),u}function Is(n,e){let t=e;for(;t<n.length&&n[t]!==0;)t+=1;let r=n.subarray(e,t);return{end:t+1,string:ce(r)}}var Cg=rt(),bs=class{constructor(e,t,r){var o,a,s,d,u;this.id=e.id,this.uniqueId=Cg(),this.shouldBeAvoided=!1,this.bitrate=e.bitrate,this.codecs=[],this.trackType=t,e.isSpatialAudio!==void 0&&(this.isSpatialAudio=e.isSpatialAudio),e.height!==void 0&&(this.height=e.height),e.width!==void 0&&(this.width=e.width),e.mimeType!==void 0&&(this.mimeType=e.mimeType),e.contentProtections!==void 0&&(this.contentProtections=e.contentProtections),e.frameRate!==void 0&&(this.frameRate=e.frameRate),e.hdrInfo!==void 0&&(this.hdrInfo=e.hdrInfo),this.cdnMetadata=e.cdnMetadata,this.index=e.index;let i=this.contentProtections!==void 0;if(t==="audio"||t==="video"){if(e.supplementalCodecs!==void 0){let c=r.isSupported((o=this.mimeType)!=null?o:"",(a=e.supplementalCodecs)!=null?a:"",i);c!==!1&&(this.codecs=[e.supplementalCodecs],this.isSupported=c)}this.isSupported!==!0&&(this.codecs.length>0?this.codecs.push((s=e.codecs)!=null?s:""):(this.codecs=e.codecs===void 0?[]:[e.codecs],this.isSupported=r.isSupported((d=this.mimeType)!=null?d:"",(u=e.codecs)!=null?u:"",i)))}else e.codecs!==void 0&&this.codecs.push(e.codecs),this.isSupported=!0}refreshCodecSupport(e){var s,d;if(this.isSupported!==void 0)return;let t=this.contentProtections!==void 0,r=!1,i=(s=this.mimeType)!=null?s:"",o=(d=this.codecs)!=null?d:[];o.length===0&&(o=[""]);let a=!1;for(let u of o){if(r=e.isSupported(i,u,t),r===!0){this.codecs=[u];break}r===void 0&&(a=!0)}r===!0?this.isSupported=!0:a?this.isSupported=void 0:this.isSupported=!1}getMimeTypeString(){var e,t,r;return`${(e=this.mimeType)!=null?e:""};codecs="${(r=(t=this.codecs)==null?void 0:t[0])!=null?r:""}"`}getEncryptionData(e){var i;let t=this.getAllEncryptionData(),r=[];for(let o=0;o<t.length;o++){let a=!1,s=t[o];for(let d=0;d<s.values.length;d++)if(s.values[d].systemId.toLowerCase()===e.toLowerCase())if(a)r[r.length-1].values.push(s.values[d]);else{let u=(i=this.contentProtections)==null?void 0:i.keyIds;r.push({type:s.type,keyIds:u,values:[s.values[d]]}),a=!0}}return r}getAllEncryptionData(){var t;if(this.contentProtections===void 0||this.contentProtections.initData.length===0)return[];let e=(t=this.contentProtections)==null?void 0:t.keyIds;return this.contentProtections.initData.map(r=>({type:r.type,keyIds:e,values:r.values}))}addProtectionData(e,t,r){let i=!1;if(this.contentProtections===void 0)return this.contentProtections={keyIds:t!==void 0?[t]:[],initData:[{type:e,values:r}]},!0;if(t!==void 0){let a=this.contentProtections.keyIds;if(a===void 0)this.contentProtections.keyIds=[t];else{let s=!1;for(let d of a)Se(d,t)&&(s=!0);s||(m.warn("manifest","found unanounced key id.",{keyId:Ne(t)}),a.push(t))}}let o=this.contentProtections.initData;for(let a=0;a<o.length;a++)if(o[a].type===e){let s=o[a].values;for(let d=0;d<r.length;d++){let u=r[d],c;for(c=0;c<s.length;c++)if(u.systemId===s[c].systemId){if(Se(u.data,s[c].data))break;m.warn("manifest","different init data for the same system ID",{systemId:u.systemId})}c===s.length&&(s.push(u),i=!0)}return i}return this.contentProtections.initData.push({type:e,values:r}),!0}isPlayable(){return Rt(this)}getMetadataSnapshot(){return{id:this.id,uniqueId:this.uniqueId,bitrate:this.bitrate,codecs:this.codecs,mimeType:this.mimeType,width:this.width,height:this.height,frameRate:this.frameRate,isSupported:this.isSupported,hdrInfo:this.hdrInfo,contentProtections:this.contentProtections,decipherable:this.decipherable,isCodecSupportedInWebWorker:this.isCodecSupportedInWebWorker}}},Oc=bs;var Ur=class n{constructor(e,t,r={}){let{trickModeTracks:i}=e,{representationFilter:o,isManuallyAdded:a}=r;this.id=e.id,this.type=e.type,e.isTrickModeTrack!==void 0&&(this.isTrickModeTrack=e.isTrickModeTrack),e.language!==void 0&&(this.language=e.language,this.normalizedLanguage=Nr(e.language)),e.closedCaption!==void 0&&(this.isClosedCaption=e.closedCaption),e.audioDescription!==void 0&&(this.isAudioDescription=e.audioDescription),e.isDub!==void 0&&(this.isDub=e.isDub),e.forcedSubtitles!==void 0&&(this.isForcedSubtitles=e.forcedSubtitles),e.isSignInterpreted!==void 0&&(this.isSignInterpreted=e.isSignInterpreted),e.label!==void 0&&(this.label=e.label),i!==void 0&&i.length>0&&(this.trickModeTracks=i.map(u=>new n(u,t)));let s=e.representations,d=[];this.supportStatus={hasSupportedCodec:!1,hasCodecWithUndefinedSupport:!1,isDecipherable:!1};for(let u=0;u<s.length;u++){let c=new Oc(s[u],this.type,t),l=!0;if(!E(o)){let f={id:c.id,bitrate:c.bitrate,codecs:c.codecs,height:c.height,width:c.width,frameRate:c.frameRate,hdrInfo:c.hdrInfo};if(c.contentProtections!==void 0&&(f.contentProtections={},c.contentProtections.keyIds!==void 0)){let p=c.contentProtections.keyIds;f.contentProtections.keyIds=p}l=o(f,{trackType:this.type,language:this.language,normalizedLanguage:this.normalizedLanguage,isClosedCaption:this.isClosedCaption,isDub:this.isDub,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted})}l?(d.push(c),c.isSupported===void 0?(this.supportStatus.hasCodecWithUndefinedSupport=!0,this.supportStatus.hasSupportedCodec===!1&&(this.supportStatus.hasSupportedCodec=void 0)):c.isSupported&&(this.supportStatus.hasSupportedCodec=!0),c.decipherable===void 0?this.supportStatus.isDecipherable===!1&&(this.supportStatus.isDecipherable=void 0):c.decipherable&&(this.supportStatus.isDecipherable=!0)):m.debug("manifest","Filtering Representation due to representationFilter",this.type,`Adaptation: ${this.id}`,`Representation: ${c.id}`,`(${c.bitrate})`)}d.sort((u,c)=>u.bitrate-c.bitrate),this.representations=d,this.manuallyAdded=a===!0}refreshCodecSupport(e){let t=!1,r=!1;for(let i of this.representations)i.refreshCodecSupport(e),i.isSupported===void 0?t=!0:i.isSupported&&(r=!0);r?this.supportStatus.hasSupportedCodec=!0:t?this.supportStatus.hasSupportedCodec=void 0:this.supportStatus.hasSupportedCodec=!1,this.supportStatus.hasCodecWithUndefinedSupport=t}getRepresentation(e){return Q(this.representations,({id:t})=>e===t)}getMetadataSnapshot(){let e=[],t=this.representations;for(let r of t)e.push(r.getMetadataSnapshot());return{id:this.id,type:this.type,supportStatus:this.supportStatus,language:this.language,isForcedSubtitles:this.isForcedSubtitles,isClosedCaption:this.isClosedCaption,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted,normalizedLanguage:this.normalizedLanguage,representations:e,label:this.label,isDub:this.isDub}}};function Ss(){let{FORCE_SHOULD_UNSET_MEDIA_KEYS:n}=O.getCurrent();return n||V.browser===V.BROWSERS.Ie11}function En(n){return new Promise(e=>{setTimeout(e,n)})}function Ts(){let{FORCE_SHOULD_AWAIT_SET_MEDIA_KEYS:n}=O.getCurrent();return n||V.device===V.DEVICES.WebOs2021||V.device===V.DEVICES.WebOs2022||V.device===V.DEVICES.WebOsOther}function Es(n,e,t){let r=n.setMediaKeys(e,t).then(()=>{m.info("DRM","MediaKeys updated with success")}).catch(i=>{if(t===null){m.error("DRM","Could not reset MediaKeys",i instanceof Error?i:"Unknown Error");return}throw m.error("DRM","Could not update MediaKeys",i instanceof Error?i:"Unknown Error"),i});return Ts()?r:Promise.race([r,En(1e3)])}var Pt=new WeakMap,Ze={async attach(n,e){let t=Pt.get(n),r=Ag(n,t,e).then(()=>{Pt.set(n,{pendingTask:null,mediaKeysState:e})},()=>{Pt.set(n,{pendingTask:null,mediaKeysState:null})});return Pt.set(n,{pendingTask:r,mediaKeysState:e}),r},getAwaitedState(n){var t;let e=Pt.get(n);return(t=e==null?void 0:e.mediaKeysState)!=null?t:null},async getAttachedMediaKeysState(n){let e=Pt.get(n);return e===void 0?null:e.pendingTask!==null?(await e.pendingTask,this.getAttachedMediaKeysState(n)):e.mediaKeysState},clearMediaKeys(n){let e=Pt.get(n),t=Mg(n,e).then(()=>{Pt.set(n,{pendingTask:null,mediaKeysState:null})},()=>{Pt.set(n,{pendingTask:null,mediaKeysState:null})});return Pt.set(n,{pendingTask:t,mediaKeysState:null}),t}};async function Dc(n){let e=n.pendingTask;if(!E(e)){m.info("DRM","Awaiting previous MediaKeys attachment operation");try{await n.pendingTask}catch(t){m.info("DRM","previous MediaKeys attachment operation failed",t instanceof Error?t:"Unknown error")}}}async function Ag(n,e,t){if(e!==void 0&&(e.pendingTask!==null&&await Dc(e),await(!E(e.mediaKeysState)&&e.mediaKeysState.loadedSessionsStore!==t.loadedSessionsStore?e.mediaKeysState.loadedSessionsStore.closeAllSessions():Promise.resolve()),n.mediaKeys===t.mediaKeys)){m.debug("DRM","Right MediaKeys already set");return}m.info("DRM","Attaching MediaKeys to the media element");try{await Es(t.emeImplementation,n,t.mediaKeys),m.info("DRM","MediaKeys attached with success")}catch(r){let i=r instanceof Error?r.toString():"Unknown Error";throw new be("MEDIA_KEYS_ATTACHMENT_ERROR","Could not attach the MediaKeys to the media element: "+i,{keyStatuses:void 0,keySystemConfiguration:t.mediaKeySystemAccess.getConfiguration(),keySystem:t.mediaKeySystemAccess.keySystem})}}async function Mg(n,e){if(e===void 0||(e.pendingTask!==null&&await Dc(e),e.mediaKeysState===null))return;m.info("DRM","Disposing of the current MediaKeys");let{loadedSessionsStore:t}=e.mediaKeysState;return await t.closeAllSessions(),Es(e.mediaKeysState.emeImplementation,n,null)}async function qn(n){return Ze.clearMediaKeys(n)}async function zo(n){if(m.info("DRM","Clearing-up DRM session."),Ss())return m.info("DRM","disposing current MediaKeys."),qn(n);let e=await Ze.getAttachedMediaKeysState(n);return e!==null&&e.keySystemOptions.closeSessionsOnStop===!0?(m.info("DRM","closing all current sessions."),e.loadedSessionsStore.closeAllSessions()):(m.info("DRM","Nothing to clear. Returning right away.",{noState:e===null}),Promise.resolve())}function ct(n,e){let t;return new Promise((r,i)=>{if(n.cancellationError!==null)return i(n.cancellationError);let o=!1;t=e(function(d){n.deregister(a),o=!0,r(d)},function(d){n.deregister(a),o=!0,i(d)}),o||n.register(a);function a(s){t!==void 0&&t(),i(s)}})}function en(n,e){return ct(e,t=>{let r=setTimeout(()=>t(),n);return()=>clearTimeout(r)})}function Wo(n){let e=new U;return Promise.race([n.close().then(()=>{e.cancel()}),n.closed.then(()=>{e.cancel()}),t()]);async function t(){try{await en(1e3,e.signal),await r()}catch(i){if(i instanceof we)return;let o=i instanceof Error?i.message:"Unknown error made it impossible to close the session";m.error("DRM","Error made it impossible to close the session",`${o}`)}}async function r(){try{await n.update(new Uint8Array(1))}catch(i){if(e.isUsed()||i instanceof Error&&i.message==="The session is already closed.")return;await en(1e3,e.signal)}if(!e.isUsed())throw new Error("Compat: Couldn't know if session is closed")}}var xg=["","webkit","moz","ms"];function wg(n,e){let t=document.createElement(n.tagName),r="on"+e;return r in t?!0:(t.setAttribute(r,"return;"),typeof t[r]=="function")}function Og(n,e){return e.filter(t=>wg(n,t))[0]}function Dg(n,e){return n.reduce((t,r)=>t.concat((e===void 0?xg:e).map(i=>i+r)),[])}function Pe(n,e){let t,r=Dg(n,e);return(i,o,a)=>{if(!a.isCancelled()){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement)if(typeof t=="undefined"&&(t=Og(i,r)),w(t))i.addEventListener(t,o),a.register(()=>{t!==void 0&&i.removeEventListener(t,o)});else{m.warn("utils",`element ${i.tagName} does not support any of these events: `+r.join(", "));return}r.forEach(s=>{let d=!1;typeof i.addEventListener=="function"?i.addEventListener(s,o):(d=!0,i["on"+s]=o),a.register(()=>{typeof i.removeEventListener=="function"&&i.removeEventListener(s,o),d&&delete i["on"+s]})})}}}function Lg(n){let e,t=document;E(t.hidden)?E(t.mozHidden)?E(t.msHidden)?E(t.webkitHidden)||(e="webkit"):e="ms":e="moz":e="";let r=w(e)?e+"Hidden":"hidden",i=w(e)?e+"visibilitychange":"visibilitychange",o=document[r],a=new j(!o,n);return _n(document,i,()=>{let s=!document[r];a.setValueIfChanged(s)},n),a}function Lc(n,e){if(n.webkitSupportsPresentationMode===!0&&typeof n.webkitSetPresentationMode=="function"){let i=n.webkitPresentationMode==="picture-in-picture",o=new j({isEnabled:i,pipWindow:null},e);return _n(n,"webkitpresentationmodechanged",()=>{let a=n.webkitPresentationMode==="picture-in-picture";o.setValue({isEnabled:a,pipWindow:null})},e),o}let t=document.pictureInPictureElement===n,r=new j({isEnabled:t,pipWindow:null},e);return _n(n,"enterpictureinpicture",i=>{var o;r.setValue({isEnabled:!0,pipWindow:(o=i.pictureInPictureWindow)!=null?o:null})},e),_n(n,"leavepictureinpicture",()=>{r.setValue({isEnabled:!1,pipWindow:null})},e),r}function Nc(n,e){let t=Lg(e),r,i=new j(!0,e);return e.register(()=>{clearTimeout(r),r=void 0}),t.onUpdate(o,{clearSignal:e}),n.onUpdate(o,{clearSignal:e}),o(),i;function o(){if(clearTimeout(r),r=void 0,n.getValue().isEnabled||t.getValue())i.setValueIfChanged(!0);else{let{INACTIVITY_DELAY:a}=O.getCurrent();r=setTimeout(()=>{i.setValueIfChanged(!1)},a)}}}function Uc(n){var o,a;let e=E(Z.devicePixelRatio)||Z.devicePixelRatio===0?1:Z.devicePixelRatio,t=new j({width:(o=Z.screen)==null?void 0:o.width,height:(a=Z.screen)==null?void 0:a.height,pixelRatio:e},n),r=setInterval(i,2e4);return n.register(function(){clearInterval(r)}),t;function i(){let s=t.getValue();(s.width!==screen.width||s.height!==screen.height||s.pixelRatio!==e)&&t.setValue({width:screen.width,height:screen.height,pixelRatio:e})}}function Bc(n,e,t){let r=E(Z.devicePixelRatio)||Z.devicePixelRatio===0?1:Z.devicePixelRatio,i=new j({width:n.clientWidth,height:n.clientHeight,pixelRatio:r},t),o=te;e.onUpdate(s,{clearSignal:t}),_n(Z,"resize",s,t),_n(n,"enterpictureinpicture",s,t),_n(n,"leavepictureinpicture",s,t);let a=setInterval(s,2e4);return s(),t.register(function(){o(),clearInterval(a)}),i;function s(){o();let d=e.getValue(),{pipWindow:u}=d;if(d.isEnabled)if(E(u)){let l=i.getValue();(l.width!==void 0||l.height!==void 0||l.pixelRatio!==r)&&i.setValue({width:void 0,height:void 0,pixelRatio:r})}else{let l=()=>{c()};u.addEventListener("resize",l),o=()=>{u.removeEventListener("resize",l),o=te},c()}else{let l=i.getValue();(l.width!==n.clientWidth||l.height!==n.clientHeight||l.pixelRatio!==r)&&i.setValue({width:n.clientWidth,height:n.clientHeight,pixelRatio:r})}function c(){let l=i.getValue();(l.width!==(u==null?void 0:u.width)||l.height!==(u==null?void 0:u.height)||l.pixelRatio!==r)&&i.setValue({width:u==null?void 0:u.width,height:u==null?void 0:u.height,pixelRatio:r})}}}var dC=Pe(["loadedmetadata"]),uC=Pe(["timeupdate"]),lC=Pe(["addtrack"]),cC=Pe(["removetrack"]),Gn=Pe(["sourceopen","webkitsourceopen"]),Ho=Pe(["sourceclose","webkitsourceclose"]),qo=Pe(["sourceended","webkitsourceended"]),Fc=Pe(["update"]),Kc=Pe(["removesourcebuffer"]),Go=Pe(["keymessage","message"]),Vc=Pe(["keyadded","ready"]),jo=Pe(["keyerror","error"]),zc=Pe(["keystatuseschange"]),Wc=Pe(["seeking"]),Hc=Pe(["seeked"]),qc=Pe(["ended"]);function _n(n,e,t,r){n.addEventListener(e,t),r.register(()=>{n.removeEventListener(e,t)})}function Lt(n){try{let e=n();return typeof e=="object"&&e!==null&&typeof e.then=="function"?e:Promise.resolve(e)}catch(e){return Promise.reject(e)}}var Nt,{MSMediaKeys:Br}=Z;Br!==void 0&&Br.prototype!==void 0&&typeof Br.isTypeSupported=="function"&&typeof Br.prototype.createSession=="function"&&(Nt=Br);var _s=class extends se{constructor(e){super(),this.expiration=NaN,this.keyStatuses=new Map,this._mk=e,this._sessionClosingCanceller=new U,this.closed=new Promise(t=>{this._sessionClosingCanceller.signal.register(()=>t("closed-by-application"))}),this.update=t=>new Promise((r,i)=>{if(this._ss===void 0)return i("MediaKeySession not set.");try{r(this._ss.update(t,""))}catch(o){i(o)}})}generateRequest(e,t){return new Promise(r=>{let i;t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t.buffer),this._ss=this._mk.createSession("video/mp4",i),Go(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"message",o)},this._sessionClosingCanceller.signal),Vc(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyadded",o)},this._sessionClosingCanceller.signal),jo(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyerror",o)},this._sessionClosingCanceller.signal),r()})}close(){return new Promise(e=>{E(this._ss)||(this._ss.close(),this._ss=void 0),this._sessionClosingCanceller.cancel(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._ss)==null?void 0:e.sessionId)!=null?t:""}},Yo=class{constructor(e){if(Nt===void 0)throw new Error("No MSMediaKeys API.");this._mediaKeys=new Nt(e)}_setVideo(e){return Lt(()=>{this._videoElement=e,this._videoElement.msSetMediaKeys!==void 0&&this._videoElement.msSetMediaKeys(this._mediaKeys)})}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new _s(this._mediaKeys)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function vs(){return{isTypeSupported:(r,i)=>{if(Nt===void 0)throw new Error("No MSMediaKeys API.");return i!==void 0?Nt.isTypeSupported(r,i):Nt.isTypeSupported(r)},createCustomMediaKeys:r=>new Yo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Yo))throw new Error("Custom setMediaKeys is supposed to be called with IE11 custom MediaKeys.");return i._setVideo(r)}}}var tn,{MozMediaKeys:Fr}=Z;Fr!==void 0&&Fr.prototype!==void 0&&typeof Fr.isTypeSupported=="function"&&typeof Fr.prototype.createSession=="function"&&(tn=Fr);function Rs(){return{isTypeSupported:(r,i)=>{if(tn===void 0)throw new Error("No MozMediaKeys API.");return i!==void 0?tn.isTypeSupported(r,i):tn.isTypeSupported(r)},createCustomMediaKeys:r=>{if(tn===void 0)throw new Error("No MozMediaKeys API.");return new tn(r)},setMediaKeys:(r,i)=>Lt(()=>{if(r.mozSetMediaKeys===void 0||typeof r.mozSetMediaKeys!="function")throw new Error("Can't set video on MozMediaKeys.");return r.mozSetMediaKeys(i)})}}var Ut=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"],Gc=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];function Qo(n){if(n>=Gc.length)throw new Error("Unable to parse base64 string.");let e=Gc[n];if(e===255)throw new Error("Unable to parse base64 string.");return e}function $o(n){let e="",t,r=n.length;for(t=2;t<r;t+=3)e+=Ut[n[t-2]>>2],e+=Ut[(n[t-2]&3)<<4|n[t-1]>>4],e+=Ut[(n[t-1]&15)<<2|n[t]>>6],e+=Ut[n[t]&63];return t===r+1&&(e+=Ut[n[t-2]>>2],e+=Ut[(n[t-2]&3)<<4],e+="=="),t===r&&(e+=Ut[n[t-2]>>2],e+=Ut[(n[t-2]&3)<<4|n[t-1]>>4],e+=Ut[(n[t-1]&15)<<2],e+="="),e}function St(n){let e=n.length%4,t=n;e!==0&&(m.warn("utils","base64ToBytes: base64 given miss padding",{padding:e}),t+=e===3?"=":e===2?"==":"===");let r=t.indexOf("=");if(r!==-1&&r<t.length-2)throw new Error("Unable to parse base64 string.");let i=t.endsWith("==")?2:t.endsWith("=")?1:0,o=t.length,a=new Uint8Array(o/4*3),s;for(let d=0,u=0;d<o;d+=4,u+=3)s=Qo(t.charCodeAt(d))<<18|Qo(t.charCodeAt(d+1))<<12|Qo(t.charCodeAt(d+2))<<6|Qo(t.charCodeAt(d+3)),a[u]=s>>16,a[u+1]=s>>8&255,a[u+2]=s&255;return a.subarray(0,a.length-i)}function de(...n){let e=n.length,t=-1,r=0,i;for(;++t<e;)i=n[t],r+=typeof i=="number"?i:i.length;let o=new Uint8Array(r),a=0;for(t=-1;++t<e;)i=n[t],typeof i=="number"?a+=i:i.length>0&&(o.set(i,a),a+=i.length);return o}function Xo(n,e){return(n[e+0]<<8)+(n[e+1]<<0)}function Zo(n,e){return n[e+0]*65536+n[e+1]*256+n[e+2]}function J(n,e){return n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function jc(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]|0}function qe(n,e){return(n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3])*4294967296+n[e+4]*16777216+n[e+5]*65536+n[e+6]*256+n[e+7]}function me(n){return new Uint8Array([n>>>8&255,n&255])}function _e(n){return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function nn(n){let e=n%4294967296,t=(n-e)/4294967296;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function Yc(n,e){return(n[e+0]<<0)+(n[e+1]<<8)}function Qc(n,e){return n[e+0]+n[e+1]*256+n[e+2]*65536+n[e+3]*16777216}function $c(n){return new Uint8Array([n&255,n>>>8&255])}function Kr(n){return new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255])}function Bt(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer)}function Ps(n){return typeof(n==null?void 0:n.webkitGenerateKeyRequest)=="function"}var ks=class extends se{constructor(e,t){super(),this._vid=e,this._key=t,this.sessionId="",this._closeSession=te,this.keyStatuses=new Map,this.expiration=NaN;let r=i=>{this.trigger(i.type,i)};this.closed=new Promise(i=>{this._closeSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(o=>{e.removeEventListener(o,r),e.removeEventListener(`webkit${o}`,r)}),i("closed-by-application")}}),["keymessage","message","keyadded","ready","keyerror","error"].forEach(i=>{e.addEventListener(i,r),e.addEventListener(`webkit${i}`,r)})}update(e){return new Promise((t,r)=>{try{if(this._key.indexOf("clearkey")>=0){let i=Bt(e),o=JSON.parse(ce(i)),a=St(o.keys[0].k),s=St(o.keys[0].kid);t(this._vid.webkitAddKey(this._key,a,s,""))}else t(this._vid.webkitAddKey(this._key,e,null,""))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{this._vid.webkitGenerateKeyRequest(this._key,t),r()})}close(){return new Promise(e=>{this._closeSession(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}},Jo=class{constructor(e){this._keySystem=e}_setVideo(e){return Lt(()=>{if(!Ps(e))throw new Error("Video not attached to the MediaKeys");this._videoElement=e})}createSession(){if(E(this._videoElement))throw new Error("Video not attached to the MediaKeys");return new ks(this._videoElement,this._keySystem)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function Cs(){return{isTypeSupported:function(r){let i=document.querySelector("video");return E(i)&&(i=document.createElement("video")),!E(i)&&typeof i.canPlayType=="function"?!!i.canPlayType("video/mp4",r):!1},createCustomMediaKeys:r=>new Jo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Jo))throw new Error("Custom setMediaKeys is supposed to be called with old webkit custom MediaKeys.");return i._setVideo(r)}}}function As(n,e){let t=Bt(n),r=Bt(e);if(Qc(t,0)+4!==t.length)throw new Error("Unsupported WebKit initData.");let o=Ko(t),a=o.indexOf("skd://"),s=a>-1?o.substring(a+6):o,d=Fo(s),u=0,c=new Uint8Array(t.byteLength+4+d.byteLength+4+r.byteLength);return c.set(t),u+=t.length,c.set(Kr(d.byteLength),u),u+=4,c.set(d,u),u+=d.byteLength,c.set(Kr(r.byteLength),u),u+=4,c.set(r,u),c}function Ct(){let{WebKitMediaKeys:n}=Z;if(n!==void 0&&typeof n.isTypeSupported=="function"&&typeof n.prototype.createSession=="function"&&typeof HTMLMediaElement.prototype.webkitSetMediaKeys=="function")return n}function Ug(n){return Ce(n,"com.apple.fps")}function Xc(n,e){return Lt(()=>{if(n.webkitSetMediaKeys===void 0)throw new Error("No webKitMediaKeys API.");n.webkitSetMediaKeys(e)})}var Ms=class extends se{constructor(e,t,r){super(),this._serverCertificate=r,this._videoElement=e,this._keyType=t,this._unbindSession=te,this._closeSession=te,this.closed=new Promise(i=>{this._closeSession=i}),this.keyStatuses=new Map,this.expiration=NaN}update(e){return new Promise((t,r)=>{if(this._nativeSession===void 0||this._nativeSession.update===void 0||typeof this._nativeSession.update!="function")return r("Unavailable WebKit key session.");try{let i=Bt(e);t(this._nativeSession.update(i))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{var s;let i=this._videoElement;if(((s=i.webkitKeys)==null?void 0:s.createSession)===void 0)throw new Error("No WebKitMediaKeys API.");let o;if(Ug(this._keyType)){if(this._serverCertificate===void 0)throw new Error("A server certificate is needed for creating fairplay session.");o=As(t,this._serverCertificate)}else o=t;let a=i.webkitKeys.createSession("video/mp4",o);if(a==null)throw new Error("Impossible to get the key sessions");this._listenEvent(a),this._nativeSession=a,r()})}close(){return new Promise((e,t)=>{if(this._unbindSession(),this._closeSession("closed-by-application"),this._nativeSession===void 0){t("No session to close.");return}this._nativeSession.close(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._nativeSession)==null?void 0:e.sessionId)!=null?t:""}_listenEvent(e){this._unbindSession();let t=r=>{this.trigger(r.type,r)};["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.addEventListener(r,t),e.addEventListener(`webkit${r}`,t)}),this._unbindSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.removeEventListener(r,t),e.removeEventListener(`webkit${r}`,t)})}}},ea=class{constructor(e){let t=Ct();if(t===void 0)throw new Error("No WebKitMediaKeys API.");this._keyType=e,this._mediaKeys=new t(e)}_setVideo(e){if(this._videoElement=e,this._videoElement===void 0)throw new Error("Video not attached to the MediaKeys");return Xc(this._videoElement,this._mediaKeys)}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new Ms(this._videoElement,this._keyType,this._serverCertificate)}setServerCertificate(e){return this._serverCertificate=e,Promise.resolve(!0)}};function ta(){let n=Ct();if(n===void 0)throw new Error("No WebKitMediaKeys API.");return{isTypeSupported:n.isTypeSupported,createCustomMediaKeys:i=>new ea(i),setMediaKeys:(i,o)=>{if(o===null)return Xc(i,o);if(!(o instanceof ea))throw new Error("Custom setMediaKeys is supposed to be called with webkit custom MediaKeys.");return o._setVideo(i)}}}function xs(){let{FORCE_SHOULD_FAVOUR_CUSTOM_SAFARI_EME:n}=O.getCurrent();return n?!0:(V.browser===V.BROWSERS.SafariDesktop||V.browser===V.BROWSERS.SafariMobile)&&Ct()!==void 0}var Vr=class{constructor(e,t,r){this._keyType=e;this._mediaKeys=t;this._configuration=r}get keySystem(){return this._keyType}createMediaKeys(){return new Promise(e=>e(this._mediaKeys))}getConfiguration(){return this._configuration}};function ws(n){var o;let e,t,r=Bg,i;if(n==="standard"||n==="auto"&&!xs()){if($t||E(navigator.requestMediaKeySystemAccess))return null;e=(...a)=>navigator.requestMediaKeySystemAccess(...a),t=Pe(["encrypted"]),i="standard"}else{let a,s;if(n==="webkit"&&Ct()!==void 0){let d=ta();t=Zc(),a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(Ps((o=Z.HTMLVideoElement)==null?void 0:o.prototype)){t=Pe(["needkey"]);let d=Cs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="older-webkit"}else if(Ct()!==void 0){t=Zc();let d=ta();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(V.browser===V.BROWSERS.Ie11&&Nt!==void 0){t=Pe(["encrypted","needkey"]);let d=vs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="ms"}else if(tn!==void 0){t=Pe(["encrypted","needkey"]);let d=Rs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="moz"}else{t=Pe(["encrypted","needkey"]);let d=Z.MediaKeys,u=()=>{if(d===void 0)throw new re("MEDIA_KEYS_NOT_SUPPORTED","No `MediaKeys` implementation found in the current browser.");if(typeof d.isTypeSupported=="undefined"){let c="This browser seems to be unable to play encrypted contents currently.Note: Some browsers do not allow decryption in some situations, like when not using HTTPS.";throw new Error(c)}};a=c=>(u(),ne(typeof d.isTypeSupported=="function"),d.isTypeSupported(c)),s=c=>(u(),new d(c)),i="unknown"}e=function(d,u){if(!a(d))return Promise.reject(new Error("Unsupported key type"));for(let c=0;c<u.length;c++){let l=u[c],{videoCapabilities:f,audioCapabilities:p,initDataTypes:h,distinctiveIdentifier:I}=l,g=!0;if(g=g&&(E(h)||h.some(b=>b==="cenc")),g=g&&I!=="required",g){let b={initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]};f!==void 0&&(b.videoCapabilities=f),p!==void 0&&(b.audioCapabilities=p);let T=s(d);return Promise.resolve(new Vr(d,T,b))}}return Promise.reject(new Error("Unsupported configuration"))}}return{requestMediaKeySystemAccess:e,onEncrypted:t,setMediaKeys:r,implementation:i}}function Zc(){let n=Pe(["needkey"],void 0);return(t,r,i)=>{n(t,o=>{let a=Y(o,{forceSessionRecreation:!0});r(a)},i)}}function Bg(n,e){try{let t;return typeof n.setMediaKeys=="function"?t=n.setMediaKeys(e):typeof n.webkitSetMediaKeys=="function"?t=n.webkitSetMediaKeys(e):typeof n.mozSetMediaKeys=="function"?t=n.mozSetMediaKeys(e):typeof n.msSetMediaKeys=="function"&&e!==null&&(t=n.msSetMediaKeys(e)),typeof t=="object"&&t!==null&&typeof t.then=="function"?t:Promise.resolve(t)}catch(t){return Promise.reject(t)}}function At(n,e){let t=n.length,r=0;for(;r+8<=t;){let i=J(n,r);if(i===0)i=t-r;else if(i===1){if(r+16>t)return-1;i=qe(n,r+8)}if(isNaN(i)||i<=0)return-1;if(J(n,r+4)===e)return r+i<=t?r:-1;r+=i}return-1}function na(n){let e=0,t=[],r=null;for(;e<=n.length;){if(e===n.length){r=null;break}r=n.subarray(e,1/0);let i=At(r,1836019558);if(i<0)break;let o=J(n,i+e),a=e+i+o;if(a>n.length)break;let s=At(r,1835295092);if(s<0)break;let d=J(n,s+e),u=e+s+d;if(u>n.length)break;let c=Math.max(a,u),l=n.subarray(e,c);t.push(l),e=c}return t.length===0?[null,r]:[t,r]}function Fg(n,e,t){return new Uint8Array(Array.prototype.slice.call(n,e,t))}function Kg(n,e,t){return n.slice(e,t)}var Os=typeof Uint8Array.prototype.slice=="function"?Kg:Fg;function Ds(n,e){let t=n;for(let r of e){let i=Ee(t,r);if(i===null)return null;t=i}return t}function Ee(n,e){let t=Ge(n,e);return t!==null?n.subarray(t[1],t[2]):null}function Jc(n,e){let t=[],r=n;for(;;){let i=Ge(r,e);if(i===null)return t;ne(i[2]!==0&&r.length!==0),t.push(r.subarray(i[1],i[2])),r=r.subarray(i[2])}}function Ls(n,e){let t=Ge(n,e);return t!==null?n.subarray(t[0],t[2]):null}function Ge(n,e){let t=n.length,r=0,i,o=0,a;for(;r+8<=t;){if(a=r,o=J(n,a),a+=4,i=J(n,a),a+=4,o===0)o=t-r;else if(o===1){if(a+8>t)return null;o=qe(n,a),a+=8}if(o<0)throw new Error("ISOBMFF: Size out of range");if(i===e)return e===1970628964&&(a+=16),[r,a,r+o];r+=o}return null}function vn(n,e,t,r,i){let o=n.length,a;for(let s=0;s<o;s+=a){let d=s;a=J(n,d),d+=4;let u=J(n,d);if(d+=4,a===0)a=o-s;else if(a===1){if(d+8>o)return;a=qe(n,d),d+=8}if(u===1970628964&&d+16<=o&&J(n,d)===e&&J(n,d+4)===t&&J(n,d+8)===r&&J(n,d+12)===i)return d+=16,n.subarray(d,s+a)}}function Ns(n){let e=n.length;if(e<8)return m.warn("isobmff","box inferior to 8 bytes, cannot find offsets"),null;let t=0,r=J(n,t);t+=4;let i=J(n,t);if(t+=4,r===0)r=e;else if(r===1){if(t+8>e)return m.warn("isobmff","box too short, cannot find offsets"),null;r=qe(n,t),t+=8}if(r<0)throw new Error("ISOBMFF: Size out of range");return i===1970628964&&(t+=16),[0,t,r]}function ra(n){let e=0,t=Ee(n,1836019574);if(t===null)return[];let r=[];for(;e<t.length;){let i;try{i=Ge(t,1886614376)}catch(s){let d=s instanceof Error?s:"";return m.warn("isobmff","Error while removing PSSH from ISOBMFF",d),r}if(i===null)return r;let o=Os(t,i[0],i[2]),a=ia(o,i[1]-i[0]);a!==void 0&&r.push({systemId:a,data:o}),t[i[0]+4]=102,t[i[0]+5]=114,t[i[0]+6]=101,t[i[0]+7]=101,e=i[2]}return r}function ia(n,e){if(n[e]>1){m.warn("isobmff","un-handled PSSH version");return}let t=e+4;if(t+16>n.length)return;let r=Os(n,t,t+16);return Ne(r)}var zr=Math.pow(2,32)-1;var Us={};function ef(n){if(Us[n]!==void 0)return Us[n];let e=Te(n);return Us[n]=e,e}function le(n,e){let t=e.length+8;return t<=zr?de(_e(t),ef(n),e):de(_e(1),ef(n),nn(t+8),e)}function Ue(n,e){return le(n,de(...e))}function Wr(n){let e=Ee(n,1836019558);return e===null?null:Ee(e,1953653094)}function Bs(n){return Jc(n,1836019558).reduce((t,r)=>{let i=Ee(r,1953653094);return i!==null&&t.push(i),t},[])}function Rn(n){return Ee(n,1835295092)}function Fs(n){let e=Ee(n,1836019574);if(e===null)return null;let t=Ee(e,1953653099);return t===null?null:Ee(t,1835297121)}function tf(n,e=0){return Ee(n.subarray(e),1701671783)}function Hr(n){let e=Yc(n,8),t=Ko(n.subarray(10,e+10)),i=new DOMParser().parseFromString(t,"application/xml").querySelector("KID");if(i===null)throw new Error("Cannot parse PlayReady private data: invalid XML");let o=i.textContent===null?"":i.textContent,a=Vo(St(o));return Ne(a).toLowerCase()}function qr(n,e){let t=Ge(n,1936286840);if(t===null)return null;let r=e,i=t[2]-t[0],o=t[1],a=n[o];o+=8;let s=J(n,o);o+=4;let d;if(a===0)d=J(n,o),o+=4,r+=J(n,o)+i,o+=4;else if(a===1)d=qe(n,o),o+=8,r+=qe(n,o)+i,o+=8;else return null;let u=[];o+=2;let c=Xo(n,o);for(o+=2;--c>=0;){let l=J(n,o);o+=4;let f=(l&2147483648)>>>31,p=l&2147483647;if(f===1)throw new Error("sidx with reference_type `1` not yet implemented");let h=J(n,o);o+=4,o+=4,u.push({time:d,duration:h,timescale:s,range:[r,r+p-1]}),d+=h,r+=p}return u}function Gr(n){let e=Wr(n);if(e===null)return;let t=Ee(e,1952867444);if(t===null)return;let r=t[0];if(r===1)return qe(t,4);if(r===0)return J(t,4)}function nf(n){let e=Ee(n,1952868452);if(e===null)return;let t=1,r=Zo(e,t);t+=3;let i=(r&1)>0,o=(r&2)>0;return(r&8)>0?(t+=4,i&&(t+=8),o&&(t+=4),J(e,t)):void 0}function rf(n){let e=Bs(n),t=[];for(let r of e){let i=Ee(r,1953658222);if(i===null)continue;let o=0,a=i[o];if(o+=1,a>1)return[];let s=Zo(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=nf(r),u===void 0))return[];let c=(s&1)>0,l=(s&4)>0,f=(s&512)>0,p=(s&1024)>0,h=(s&2048)>0,I=J(i,o);o+=4,c&&(o+=4),l&&(o+=4);let g=I;for(;g-- >0;){let b,T,v,_;d?(b=J(i,o),o+=4):b=u,f&&(T=J(i,o),o+=4),p&&(v=J(i,o),o+=4),h&&(_=a===0?J(i,o):jc(i,o),o+=4),t.push({duration:b,compositionTimeOffset:_,size:T,flags:v})}}return t}function jr(n){let e=Bs(n);if(e.length===0)return;let t=0;for(let r of e){let i=Ee(r,1953658222);if(i===null)return;let o=0,a=i[o];if(o+=1,a>1)return;let s=Zo(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=nf(r),u===void 0))return;let c=(s&1)>0,l=(s&4)>0,f=(s&512)>0,p=(s&1024)>0,h=(s&2048)>0,I=J(i,o);o+=4,c&&(o+=4),l&&(o+=4);let g=I,b=0;for(;g-- >0;)d?(b+=J(i,o),o+=4):b+=u,f&&(o+=4),p&&(o+=4),h&&(o+=4);t+=b}return t}function Yr(n){let e=Fs(n);if(e===null)return;let t=Ee(e,1835296868);if(t===null)return;let r=0,i=t[r];if(r+=4,i===1)return J(t,r+16);if(i===0)return J(t,r+8)}function Ks(n){let e=n.length;if(e<4)throw new Error("Cannot update box length: box too short");let t=J(n,0);if(t===0)if(e>zr){let r=new Uint8Array(e+8);return r.set(_e(1),0),r.set(n.subarray(4,8),4),r.set(nn(e+8),8),r.set(n.subarray(8,e),16),r}else return n.set(_e(e),0),n;else if(t===1){if(e<16)throw new Error("Cannot update box length: box too short");return n.set(nn(e),8),n}else{if(e<=zr)return n.set(_e(e),0),n;{let r=new Uint8Array(e+8);return r.set(_e(1),0),r.set(n.subarray(4,8),4),r.set(nn(e+8),8),r.set(n.subarray(8,e),16),r}}}function of(n){let e=[],t=0;for(;t<n.length;){let r=tf(n,t);if(r===null)break;let i=r.length;t+=i;let o=r[0];if(o!==0)m.warn("isobmff","EMSG version "+o.toString()+" not supported.");else{let a=4,{end:s,string:d}=Is(r,a);a=s;let{end:u,string:c}=Is(r,a);a=u;let l=J(r,a);a+=4;let f=J(r,a);a+=4;let p=J(r,a);a+=4;let h=J(r,a);a+=4;let I=r.subarray(a,i),g={schemeIdUri:d,value:c,timescale:l,presentationTimeDelta:f,eventDuration:p,id:h,messageData:I};e.push(g)}}if(e.length!==0)return e}function af(n){let e=Ds(n,[1836019574,1953653099,1835297121,1835626086,1937007212,1937011556]);if(e===null)return null;let t=e.subarray(8),r=Ee(t,1701733238),i=0;if(r===null?(i=28,r=Ee(t,1701733217)):i=78,r===null)return null;let o=Ds(r.subarray(i),[1936289382,1935894633,1952804451]);if(o===null||o.byteLength<24)return null;let a=o.subarray(8,24);return a.every(s=>s===0)?null:a}var oa=J(Te("pssh"),0);function Vg(n){m.info("DRM","Trying to move CENC PSSH from init data at the end of it.");let e=!1,t=new Uint8Array,r=new Uint8Array,i=0;for(;i<n.length;){if(n.length<i+8||J(n,i+4)!==oa)throw m.warn("DRM","unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let o=J(new Uint8Array(n),i);if(i+o>n.length)throw m.warn("DRM","unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let a=n.subarray(i,i+o);if(n[i+12]===16&&n[i+13]===119&&n[i+14]===239&&n[i+15]===236&&n[i+16]===192&&n[i+17]===178&&n[i+18]===77&&n[i+19]===2&&n[i+20]===172&&n[i+21]===227&&n[i+22]===60&&n[i+23]===30&&n[i+24]===82&&n[i+25]===226&&n[i+26]===251&&n[i+27]===75){let s=Ns(a),d=s===null?void 0:a[s[1]];m.info("DRM","CENC PSSH found with version",d),d===void 0?m.warn("DRM","could not read version of CENC PSSH"):e===(d===1)?t=de(t,a):d===1?(m.warn("DRM","cenc version 1 encountered, removing every other cenc pssh box."),t=a,e=!0):m.warn("DRM","filtering out cenc pssh box with wrong version",d)}else r=de(r,a);i+=o}if(i!==n.length)throw m.warn("DRM","unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");return de(r,t)}function Qr(n,e,t){m.debug("DRM","Calling generateRequest on the MediaKeySession");let r;try{r=Vg(t)}catch(o){r=t}let i=e!=null?e:"";return n.generateRequest(i,r).catch(o=>{if(i!==""||!(o instanceof TypeError))throw o;return m.warn("DRM",'error while calling `generateRequest` with an empty initialization data type. Retrying with a default "cenc" value.',o),n.generateRequest("cenc",r)})}function zg(n){let e=[],t=0;for(;t<n.length;){if(n.length<t+8||J(n,t+4)!==oa)return m.warn("DRM","Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let r=J(new Uint8Array(n),t);if(t+r>n.length)return m.warn("DRM","Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let i=n.subarray(t,t+r),a={systemId:ia(i,8),data:i};Wg(e,a)?m.warn("DRM","Duplicated PSSH found in initialization data, removing it."):e.push(a),t+=r}return t!==n.length?(m.warn("DRM","Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}]):e}function Wg(n,e){for(let t=0;t<n.length;t++){let r=n[t];if((e.systemId===void 0||r.systemId===void 0||e.systemId===r.systemId)&&Se(e.data,r.data))return!0}return!1}function aa(n){let{initData:e,initDataType:t,forceSessionRecreation:r}=n;if(E(e))return m.warn("DRM","No init data found on media encrypted event."),null;let i=new Uint8Array(e),o=zg(i);return{type:t,values:o,forceSessionRecreation:r}}var Hg=100;async function $r(n,e){m.info("DRM","Load persisted session",{sessionId:e});let t=await n.load(e);return!t||n.keyStatuses.size>0?t:new Promise(r=>{n.addEventListener("keystatuseschange",o);let i=setTimeout(o,Hg);function o(){a(),r(t)}function a(){clearTimeout(i),n.removeEventListener("keystatuseschange",o)}})}var sf=ws;function $(n,e,t){if(typeof Array.prototype.includes=="function")return n.includes(e,t);let r=n.length>>>0;if(r===0)return!1;let i=t|0,o=i>=0?Math.min(i,r-1):Math.max(r+i,0),a=(s,d)=>s===d||typeof s=="number"&&typeof d=="number"&&isNaN(s)&&isNaN(d);for(;o<r;){if(a(n[o],e))return!0;o++}return!1}function Xr(n){if(n.sessionId==="")return!1;let e=n.keyStatuses,t=[];return e.forEach(r=>{t.push(r)}),t.length<=0?(m.debug("DRM","isSessionUsable: MediaKeySession given has an empty keyStatuses",{sessionId:n.sessionId}),!1):$(t,"expired")?(m.debug("DRM","isSessionUsable: MediaKeySession given has an expired key",{sessionId:n.sessionId}),!1):$(t,"internal-error")?(m.debug("DRM","isSessionUsable: MediaKeySession given has a key with an internal-error",{sessionId:n.sessionId}),!1):(m.debug("DRM","isSessionUsable: MediaKeySession is usable",{sessionId:n.sessionId}),!0)}function Vs(n,e,t,r){let{loadedSessionsStore:i,persistentSessionsStore:o}=n;return t==="temporary"?df(i,e):o===null?(m.warn("DRM","Cannot create persistent MediaKeySession, PersistentSessionsStore not created."),df(i,e)):qg(i,o,e,r)}function df(n,e){m.info("DRM","Creating a new temporary session");let t=n.createSession(e,"temporary");return Promise.resolve({type:"created-session",value:t})}async function qg(n,e,t,r){if(r.cancellationError!==null)throw r.cancellationError;m.info("DRM","Creating persistent MediaKeySession");let i=n.createSession(t,"persistent-license"),o=e.getAndReuse(t);if(o===null)return{type:"created-session",value:i};try{let s=await n.loadPersistentSession(i.mediaKeySession,o.sessionId);if(!s){m.warn("DRM","No data stored for the loaded session",{sessionId:o.sessionId}),e.delete(o.sessionId),n.removeSessionWithoutClosingIt(i.mediaKeySession);let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}return s&&Xr(i.mediaKeySession)?(e.add(t,t.keyIds,i.mediaKeySession),m.info("DRM","Succeeded to load persistent session."),{type:"loaded-persistent-session",value:i}):(m.warn("DRM","Previous persistent session not usable anymore."),a())}catch(s){return m.warn("DRM","Unable to load persistent session: "+(s instanceof Error?s.toString():"Unknown Error")),a()}async function a(){if(r.cancellationError!==null)throw r.cancellationError;m.info("DRM","Removing previous persistent session.");let s=e.get(t);s!==null&&e.delete(s.sessionId);try{await n.closeSession(i.mediaKeySession)}catch(u){if(i.mediaKeySession.sessionId!=="")throw u;n.removeSessionWithoutClosingIt(i.mediaKeySession)}if(r.cancellationError!==null)throw r.cancellationError;let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}}async function zs(n,e){if(e<0||e>=n.getLength())return;m.info("DRM","LSS cache limit exceeded",{limit:e,length:n.getLength()});let t=[],r=n.getAll().slice(),i=r.length-e;for(let o=0;o<i;o++){let a=r[o];t.push(n.closeSession(a.mediaKeySession))}await Promise.all(t)}async function Ws(n,e,t,r,i){let o=null,{loadedSessionsStore:a,persistentSessionsStore:s}=e,d=a.reuse(n);if(d!==null){if(o=d.mediaKeySession,Xr(o))return m.info("DRM","Reuse loaded session",{sessionId:o.sessionId}),{type:"loaded-open-session",value:{mediaKeySession:o,sessionType:d.sessionType,keySessionRecord:d.keySessionRecord}};s!==null&&d.mediaKeySession.sessionId!==""&&s.delete(d.mediaKeySession.sessionId)}if(o!==null&&(await a.closeSession(o),i.cancellationError!==null)||(await zs(a,r<=0?r:r-1),i.cancellationError!==null))throw i.cancellationError;let u=await Vs(e,n,t,i);return{type:u.type,value:{mediaKeySession:u.value.mediaKeySession,sessionType:u.value.sessionType,keySessionRecord:u.value.keySessionRecord}}}function Hs(){let{FORCE_CANNOT_REUSE_MEDIA_KEYS:n}=O.getCurrent();return!n&&V.device!==V.DEVICES.WebOs2021&&V.device!==V.DEVICES.WebOs2022&&V.device!==V.DEVICES.WebOsOther&&V.device!==V.DEVICES.PhilipsNetTv&&V.device!==V.DEVICES.Panasonic&&V.device!==V.DEVICES.A1KStb40xx}function uf(n){let{FORCE_CANNOT_RELY_ON_REQUEST_MEDIA_KEY_SYSTEM_ACCESS:e}=O.getCurrent();return!(e||(V.browser===V.BROWSERS.EdgeChromium||V.browser===V.BROWSERS.Firefox)&&n.indexOf("playready")!==-1)}var lf='<WRMHEADER xmlns="http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader" version="4.0.0.0"><DATA><PROTECTINFO><KEYLEN>16</KEYLEN><ALGID>AESCTR</ALGID></PROTECTINFO><KID>ckB07BNLskeUq0qd83fTbA==</KID><DS_ID>yYIPDBca1kmMfL60IsfgAQ==</DS_ID><CUSTOMATTRIBUTES xmlns=""><encryptionref>312_4024_2018127108</encryptionref></CUSTOMATTRIBUTES><CHECKSUM>U/tsUYRgMzw=</CHECKSUM></DATA></WRMHEADER>';function cf(n){let e=Fo(n),t=$c(e.length),r=new Uint8Array([1,0]),i=new Uint8Array([1,0]),o=Kr(e.length+6),a=de(o,i,r,t,e),s=Xe("9a04f07998404286ab92e65be0885f95");return Gg(a,s)}function Gg(n,e){let t=Te("pssh"),r=new Uint8Array([0,0,0,0]),i=_e(n.length),o=_e(32+n.length);return de(o,t,r,e,i,n)}function qs(n){let{FORCE_SHOULD_RENEW_MEDIA_KEY_SYSTEM_ACCESS:e}=O.getCurrent();return e?!0:n.indexOf("playready")!==-1&&(V.browser===V.BROWSERS.Ie11||V.browser===V.BROWSERS.EdgeChromium||V.browser===V.BROWSERS.Firefox)}function jg(n,e){let{mimeType:t,codecs:r}=sa(n),{mimeType:i,codecs:o}=sa(e);if(t!==i||r===""||o==="")return!1;let a=r.split(".")[0];a=a==="hev1"?"hvc1":a;let s=o.split(".")[0];return s=s==="hev1"?"hvc1":s,a===s}var Yg=7;function sa(n){var i;let[e,...t]=n.split(";"),r=(i=Q(t,o=>Ce(o,"codecs=")))!=null?i:"";return r=r.substring(Yg),r[0]==='"'&&(r=r.substring(1,r.length-1)),{mimeType:e,codecs:r}}var da=jg;function jn(n,e){return typeof Array.prototype.flatMap=="function"?n.flatMap(e):n.reduce((t,r)=>{let i=e(r);return Array.isArray(i)?(t.push(...i),t):(t.push(i),t)},[])}function Qg(n,e){var c,l,f,p,h,I,g,b,T,v;if(n.label!==e.label)return!1;let t=(c=e.distinctiveIdentifier)!=null?c:"optional",r=(l=n.distinctiveIdentifier)!=null?l:"optional";if(t!==r)return!1;let i=(f=e.persistentState)!=null?f:"optional",o=(p=n.persistentState)!=null?p:"optional";if(i!==o)return!1;let a=(h=e.initDataTypes)!=null?h:[],s=(I=n.initDataTypes)!=null?I:[];if(!mf(s,a))return!1;let d=(g=e.sessionTypes)!=null?g:[],u=(b=n.sessionTypes)!=null?b:[];if(!mf(u,d))return!1;for(let _ of["audioCapabilities","videoCapabilities"]){let R=(T=n[_])!=null?T:[],k=(v=e[_])!=null?v:[];if(!R.every(P=>{var M,L,F,D,B,A;for(let C=0;C<k.length;C++){let N=k[C];if(((M=N.robustness)!=null?M:"")===((L=P.robustness)!=null?L:"")||((F=N.encryptionScheme)!=null?F:null)===((D=P.encryptionScheme)!=null?D:null)||((B=N.robustness)!=null?B:"")===((A=P.robustness)!=null?A:""))return!0}return!1}))return!1}return!0}function $g(n){let{EME_KEY_SYSTEMS:e}=O.getCurrent();for(let t of Object.keys(e))if($(e[t],n))return t}function Xg(n){let{keyName:e,keyType:t,keySystemOptions:r}=n,i,o="optional",a="optional";Array.isArray(r.wantedSessionTypes)?(i=r.wantedSessionTypes,$(r.wantedSessionTypes,"persistent-license")&&!E(r.persistentLicenseConfig)&&(o="required")):E(r.persistentLicenseConfig)?i=["temporary"]:(o="required",i=["persistent-license"]),E(r.persistentState)||(o=r.persistentState),E(r.distinctiveIdentifier)||(a=r.distinctiveIdentifier);let{EME_DEFAULT_AUDIO_CODECS:s,EME_DEFAULT_VIDEO_CODECS:d,EME_DEFAULT_WIDEVINE_ROBUSTNESSES:u,EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:c}=O.getCurrent(),l,f,{audioCapabilitiesConfig:p,videoCapabilitiesConfig:h}=r;if((p==null?void 0:p.type)==="full")l=p.value;else{let g;(p==null?void 0:p.type)==="robustness"?g=p.value:e==="widevine"?g=u:t==="com.microsoft.playready.recommendation"?g=c:g=[],g.length===0&&g.push(void 0);let b=(p==null?void 0:p.type)==="contentType"?p.value:s;l=jn(g,T=>b.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}if((h==null?void 0:h.type)==="full")f=h.value;else{let g;(h==null?void 0:h.type)==="robustness"?g=h.value:e==="widevine"?g=u:t==="com.microsoft.playready.recommendation"?g=c:g=[],g.length===0&&g.push(void 0);let b=(h==null?void 0:h.type)==="contentType"?h.value:d;f=jn(g,T=>b.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}let I={initDataTypes:["cenc"],videoCapabilities:f,audioCapabilities:l,distinctiveIdentifier:a,persistentState:o,sessionTypes:i};return p!==void 0?h!==void 0?[I]:[I,ue(ae({},I),{videoCapabilities:void 0})]:h!==void 0?[I,ue(ae({},I),{audioCapabilities:void 0})]:[I,ue(ae({},I),{audioCapabilities:void 0,videoCapabilities:void 0})]}function ff(n,e){var u,c,l,f,p,h;let t=(c=(u=n.audioCapabilities)==null?void 0:u.map(I=>I.contentType))!=null?c:[],r=(f=(l=n.videoCapabilities)==null?void 0:l.map(I=>I.contentType))!=null?f:[],i=t.concat(r).filter(I=>I!==void 0),o=(p=e.videoCapabilities)==null?void 0:p.map(I=>I.contentType),a=(h=e.audioCapabilities)==null?void 0:h.map(I=>I.contentType),s=[...o!=null?o:[],...a!=null?a:[]].filter(I=>I!==void 0);return s.length===0?[]:i.map(I=>{let{codecs:g,mimeType:b}=sa(I),T=$(s,I);return{codec:g,mimeType:b,result:T}})}function Gs(n,e,t,r){m.info("DRM","Searching for compatible MediaKeySystemAccess");let i=t.reduce((a,s)=>{let{EME_KEY_SYSTEMS:d}=O.getCurrent(),u=d[s.type],c;if(!E(u))c=u.map(l=>({keyName:s.type,keyType:l,keySystemOptions:s}));else{let l=$g(s.type),f=s.type;c=[{keyName:l,keyType:f,keySystemOptions:s}]}return a.concat(c)},[]);return o(0);async function o(a){if(a>=i.length)throw new be("INCOMPATIBLE_KEYSYSTEMS","No key system compatible with your wanted configuration has been found in the current browser.",{keyStatuses:void 0,keySystemConfiguration:void 0,keySystem:void 0});if(E(n.requestMediaKeySystemAccess))throw new Error("requestMediaKeySystemAccess is not implemented in your browser.");let s=i[a],{keyType:d,keySystemOptions:u}=s,c=Xg(s);m.debug("DRM","Request keysystem access",{keyType:d,index:a,length:i.length});let l,f=await Ze.getAttachedMediaKeysState(e);for(let p=0;p<c.length;p++){let h=c[p];if(f!==null&&!qs(f.mediaKeySystemAccess.keySystem)&&d===f.mediaKeySystemAccess.keySystem&&n.implementation===f.emeImplementation.implementation&&Qg(h,f.askedConfiguration))return m.info("DRM","Found cached compatible keySystem"),Promise.resolve({type:"reuse-media-key-system-access",value:{mediaKeySystemAccess:f.mediaKeySystemAccess,askedConfiguration:f.askedConfiguration,options:u,codecSupport:ff(f.askedConfiguration,f.mediaKeySystemAccess.getConfiguration())}});try{return l=await Zg(n,d,[h]),m.info("DRM","Found compatible keysystem",{keyType:d,index:a,configIndex:p}),{type:"create-media-key-system-access",value:{options:u,mediaKeySystemAccess:l,askedConfiguration:h,codecSupport:ff(h,l.getConfiguration())}}}catch(I){if(m.debug("DRM","Rejected access to keysystem",{keyType:d,index:a,configIndex:p}),r.cancellationError!==null)throw r.cancellationError}}return o(a+1)}}async function Zg(n,e,t){let r=await n.requestMediaKeySystemAccess(e,t);if(!uf(e))try{let o=(await r.createMediaKeys()).createSession(),a=cf(lf);await o.generateRequest("cenc",a),o.close().catch(()=>{m.warn("DRM","Failed to close the dummy session")})}catch(i){throw m.debug("DRM","KeySystemAccess was granted but it is not usable"),i}return r}function mf(n,e){for(let t=0;t<n.length;t++)if(!$(e,n[t]))return!1;return!0}function Yn(n,e){for(let t of n)if(!e.some(i=>Se(i,t)))return!1;return!0}function pf(n,e){for(let t of n)if(e.some(i=>Se(i,t)))return!0;return!1}var Zr=class{constructor(e){this._initializationData=e,this._keyIds=null}associateKeyIds(e){this._keyIds===null&&(this._keyIds=[]);let t=Array.from(e);for(let r of t)this.isAssociatedWithKeyId(r)||this._keyIds.push(r)}isAssociatedWithKeyId(e){if(this._keyIds===null)return!1;for(let t of this._keyIds)if(Se(t,e))return!0;return!1}getAssociatedKeyIds(){return this._keyIds===null?[]:this._keyIds}isCompatibleWith(e){let{keyIds:t}=e;if(t!==void 0&&t.length>0){if(this._keyIds!==null&&Yn(t,this._keyIds))return!0;if(this._initializationData.keyIds!==void 0)return Yn(t,this._initializationData.keyIds)}return this._checkInitializationDataCompatibility(e)}_checkInitializationDataCompatibility(e){return e.keyIds!==void 0&&e.keyIds.length>0&&this._initializationData.keyIds!==void 0?Yn(e.keyIds,this._initializationData.keyIds):this._initializationData.type!==e.type?!1:this._initializationData.values.isCompatibleWith(e.values)}};var Jr=class{constructor(e){this._mediaKeys=e,this._storage=[]}createSession(e,t){let r=new Zr(e);m.debug("DRM","calling `createSession`",{sessionType:t});let i=this._mediaKeys.createSession(t),o={mediaKeySession:i,sessionType:t,keySessionRecord:r,isGeneratingRequest:!1,isLoadingPersistentSession:!1,closingStatus:{type:"none"}};return E(i.closed)||i.closed.then(()=>{m.info("DRM","session was closed, removing it.",{sessionId:i.sessionId});let a=this.getIndex(r);a>=0&&this._storage[a].mediaKeySession===i&&this._storage.splice(a,1)}).catch(a=>{m.warn("DRM",`MediaKeySession.closed rejected: ${a}`)}),this._storage.push(ae({},o)),m.debug("DRM","MediaKeySession added",{sessionType:o.sessionType,currentlyLoaded:this._storage.length}),o}reuse(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.keySessionRecord.isCompatibleWith(e))return this._storage.splice(t,1),this._storage.push(r),m.debug("DRM","Reusing session:",{sessionId:r.mediaKeySession.sessionId,sessionType:r.sessionType}),ae({},r)}return null}getEntryForSession(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.mediaKeySession===e)return ae({},r)}return null}async generateLicenseRequest(e,t,r){let i;for(let o of this._storage)if(o.mediaKeySession===e){i=o;break}if(i===void 0)return m.error("DRM","generateRequest error. No MediaKeySession found with the given initData and initDataType"),Qr(e,t,r);if(i.isGeneratingRequest=!0,i.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");try{await Qr(e,t,r)}catch(o){throw i===void 0||(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start()),o}i!==void 0&&(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start())}async loadPersistentSession(e,t){let r;for(let o of this._storage)if(o.mediaKeySession===e){r=o;break}if(r===void 0)return m.error("DRM","loadPersistentSession error. No MediaKeySession found with the given initData and initDataType"),$r(e,t);if(r.isLoadingPersistentSession=!0,r.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");let i;try{i=await $r(e,t)}catch(o){throw r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),o}return r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),i}async closeSession(e){let t;for(let r of this._storage)if(r.mediaKeySession===e){t=r;break}return t===void 0?(m.warn("DRM","No MediaKeySession found with the given initData and initDataType"),Promise.resolve(!1)):this._closeEntry(t)}getLength(){return this._storage.length}getAll(){return this._storage}async closeAllSessions(){let e=this._storage;m.debug("DRM","Closing all current MediaKeySessions",{numberOfEntries:e.length}),this._storage=[];let t=e.map(r=>this._closeEntry(r));await Promise.all(t)}removeSessionWithoutClosingIt(e){ne(e.sessionId==="","Initialized `MediaKeySession`s should always be properly closed");for(let t=this._storage.length-1;t>=0;t--)if(this._storage[t].mediaKeySession===e)return m.debug("DRM","Removing session without closing it",{sessionId:e.sessionId}),this._storage.splice(t,1),!0;return!1}getIndex(e){for(let t=0;t<this._storage.length;t++)if(this._storage[t].keySessionRecord===e)return t;return-1}async _closeEntry(e){let{mediaKeySession:t}=e;return new Promise((r,i)=>{e!==void 0&&(e.isLoadingPersistentSession||e.isGeneratingRequest)?e.closingStatus={type:"awaiting",start:o}:o();function o(){e!==void 0&&(e.closingStatus={type:"pending"}),Jg(t).then(()=>{e!==void 0&&(e.closingStatus={type:"done"}),r(!0)}).catch(a=>{e!==void 0&&(e.closingStatus={type:"failed"}),i(a)})}})}};async function Jg(n){let e=n.sessionId;m.debug("DRM","Trying to close a MediaKeySession",{sessionId:e});try{await Wo(n),m.debug("DRM","Succeeded to close MediaKeySession",{sessionId:e});return}catch(t){m.error("DRM","Could not close MediaKeySession: "+(t instanceof Error?t.toString():"Unknown error"),{sessionId:e});return}}function rn(n){let e=0,t;for(let r=0;r<n.length;r++)t=n[r],e=(e<<5)-e+t,e=e&e;return e}var ft=class{constructor(e){this.initData=e}toJSON(){return $o(this.initData)}static decode(e){return St(e)}};function Qn(n,e){var t,r;return(r=(t=gf(n,e))!=null?t:gf(e,n))!=null?r:!1}function gf(n,e){if(n.length===0)return!1;if(e.length<n.length)return null;let t=n[0],r=0,i=0;for(;i<e.length;i++){let o=e[i];if(o.systemId!==t.systemId)continue;if(o.hash!==t.hash)return!1;let a;t.data instanceof Uint8Array?a=t.data:typeof t.data=="string"?a=ft.decode(t.data):a=t.data.initData;let s;if(o.data instanceof Uint8Array?s=o.data:typeof o.data=="string"?s=ft.decode(o.data):s=o.data.initData,!Se(a,s))return!1;if(e.length-i<n.length)return null;for(r=1;r<n.length;r++){let d=n[r];for(i+=1;i<e.length;i++){let u=e[i];if(d.systemId!==u.systemId)continue;if(d.hash!==u.hash)return!1;let c;d.data instanceof Uint8Array?c=d.data:typeof d.data=="string"?c=ft.decode(d.data):c=d.data.initData;let l;if(u.data instanceof Uint8Array?l=u.data:typeof u.data=="string"?l=ft.decode(u.data):l=u.data.initData,!Se(c,l))return!1;break}if(r===e.length)return null}return!0}return null}function eh(n){yc(n,{save:"function",load:"function"},"persistentLicenseConfig")}var ei=class{constructor(e){eh(e),this._entries=[],this._storage=e;try{let t=this._storage.load();Array.isArray(t)||(t=[]),this._entries=t}catch(t){m.warn("DRM","Persistent store: Could not get entries from license storage",t instanceof Error?t:""),this.dispose()}}getLength(){return this._entries.length}getAll(){return this._entries}get(e){let t=this._getIndex(e);return t===-1?null:this._entries[t]}getAndReuse(e){let t=this._getIndex(e);if(t===-1)return null;let r=this._entries.splice(t,1)[0];return this._entries.push(r),r}add(e,t,r){var s;if(E(r)||!w(r.sessionId)){m.warn("DRM","Persistent Store: Invalid Persisten Session given.");return}let{sessionId:i}=r,o=this._getIndex(e);if(o>=0){let d=t===void 0?3:4,u=this._entries[o];if(((s=u.version)!=null?s:-1)>=d&&i===u.sessionId)return;m.info("DRM","Persistent Store: Updating session info.",{sessionId:i}),this._entries.splice(o,1)}else m.info("DRM","Persistent Store: Add new session",{sessionId:i});let a=th(e.values.getFormattedValues());t===void 0?this._entries.push({version:3,sessionId:i,values:a,initDataType:e.type}):this._entries.push({version:4,sessionId:i,keyIds:t.map(d=>new ft(d)),values:a,initDataType:e.type}),this._save()}delete(e){let t=-1;for(let i=0;i<this._entries.length;i++)if(this._entries[i].sessionId===e){t=i;break}if(t===-1){m.warn("DRM","Persistent Store: initData to delete not found in persistent store.");return}let r=this._entries[t];m.warn("DRM","Persistent Store: Delete session from persistent store",{sessionId:r.sessionId}),this._entries.splice(t,1),this._save()}deleteOldSessions(e){m.info("DRM","Persistent Store: Deleting last sessions.",{sessionsToDelete:e}),!(e<=0)&&(e<=this._entries.length?this._entries.splice(0,e):(m.warn("DRM","Persistent Store: Asked to remove more information that it contains",e,this._entries.length),this._entries=[]),this._save())}dispose(){this._entries=[],this._save()}_getIndex(e){let t=null;function r(){if(t===null){let i=e.values.constructRequestData();t={initData:i,initDataHash:rn(i)}}return t}for(let i=0;i<this._entries.length;i++){let o=this._entries[i];if(o.initDataType===e.type)switch(o.version){case 4:if(Array.isArray(e.keyIds)&&e.keyIds.length>0){if(e.keyIds.every(s=>{let d=$o(s);for(let u of o.keyIds)if(typeof u=="string"){if(d===u)return m.debug("DRM","Persistent Store: Found wanted kid stored on entry",{index:i,keyId:d,sessionId:o.sessionId}),!0}else if(Se(u.initData,s))return m.hasLevel("DEBUG")&&m.debug("DRM","Persistent Store: Found wanted kid stored on entry",{index:i,keyId:d,sessionId:o.sessionId}),!0;return!1}))return m.debug("DRM","Persistent Store: Found compatible entry of v4",{index:i,sessionId:o.sessionId}),i}else{let a=e.values.getFormattedValues();if(Qn(a,o.values))return m.debug("DRM","Persistent Store: Found compatible entry of v4 without init data",{index:i,sessionId:o.sessionId}),i}break;case 3:{let a=e.values.getFormattedValues();if(Qn(a,o.values))return m.debug("DRM","Persistent Store: Found compatible entry of v3 - same values",{index:i,sessionId:o.sessionId}),i;break}case 2:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s)try{let d=typeof o.initData=="string"?ft.decode(o.initData):o.initData.initData;if(Se(d,a))return m.debug("DRM","Persistent Store: Found compatible entry of v2 - same concatenated init data",{index:i,sessionId:o.sessionId}),i}catch(d){m.warn("DRM","Persistent Store: Could not decode initialization data.",d instanceof Error?d:"")}break}case 1:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s){if(typeof o.initData.length=="undefined")return m.debug("DRM","Persistent Store: Found compatible entry of v1 - same hash only",{index:i,sessionId:o.sessionId,hash:s}),i;if(Se(o.initData,a))return m.debug("DRM","Persistent Store: Found compatible entry of v1 - same hash and initData",{index:i,sessionId:o.sessionId,hash:s}),i}break}default:{let{initDataHash:a}=r();if(o.initData===a)return m.debug("DRM","Persistent Store: Found compatible entry - same hash only",{index:i,sessionId:o.sessionId,hash:a}),i}}}return-1}_save(){try{this._storage.save(this._entries)}catch(e){let t=e instanceof Error?e:void 0;m.warn("DRM","Persistent Store: Could not save MediaKeySession information",t)}}};function th(n){return n.map(({systemId:e,data:t,hash:r})=>({systemId:e,hash:r,data:new ft(t)}))}var ua=new WeakMap,kn={prepare(n){ua.set(n,null)},set(n,e){let t=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),r=rn(t);ua.set(n,{hash:r,serverCertificate:t})},hasOne(n){let e=ua.get(n);if(e===void 0)return!1;if(e!==null)return!0},has(n,e){let t=ua.get(n);if(t==null)return!1;let{hash:r,serverCertificate:i}=t,o=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer);if(rn(o)!==r||i.length!==o.length)return!1;for(let s=0;s<i.length;s++)if(i[s]!==o[s])return!1;return!0}};function nh(n){let{persistentLicenseConfig:e}=n;return E(e)?null:(m.debug("DRM","Set the given license storage"),new ei(e))}async function js(n,e,t,r){let i=await Gs(n,e,t,r);if(r.cancellationError!==null)throw r.cancellationError;let{options:o,mediaKeySystemAccess:a,askedConfiguration:s,codecSupport:d}=i.value,u=await Ze.getAttachedMediaKeysState(e),c=nh(o);if(i.value.options.reuseMediaKeys!==!1&&Hs()&&u!==null&&i.type==="reuse-media-key-system-access"){m.debug("DRM","Reusing already created MediaKeys");let{mediaKeys:p,loadedSessionsStore:h}=u;if(kn.hasOne(p)===!1||!E(o.serverCertificate)&&kn.has(p,o.serverCertificate))return{mediaKeys:p,mediaKeySystemAccess:a,askedConfiguration:s,stores:{loadedSessionsStore:h,persistentSessionsStore:c},options:o,codecSupport:d}}let l=await rh(a);m.info("DRM","MediaKeys created with success");let f=new Jr(l);return{mediaKeys:l,mediaKeySystemAccess:a,askedConfiguration:s,stores:{loadedSessionsStore:f,persistentSessionsStore:c},options:o,codecSupport:d}}async function rh(n){m.info("DRM","Calling createMediaKeys on the MediaKeySystemAccess");try{return await n.createMediaKeys()}catch(e){let t=e instanceof Error?e.message:"Unknown error when creating MediaKeys.";throw new be("CREATE_MEDIA_KEYS_ERROR",t,{keyStatuses:void 0,keySystemConfiguration:n.getConfiguration(),keySystem:n.keySystem})}}async function Ys(n,e,t,r){let i=await js(n,e,t,r),{mediaKeys:o}=i;return e.mediaKeys!==null&&e.mediaKeys!==void 0&&o!==e.mediaKeys&&(m.debug("DRM","Disabling old MediaKeys"),await Ze.clearMediaKeys(e)),i}function ti(n){let e=(Math.random()*2-1)*.3;return n*(e+1)}function Qs(n,e,t){let{baseDelay:r,maxDelay:i,totalRetry:o,shouldRetry:a,onRetry:s}=e,d=0;return u();async function u(){if(t.cancellationError!==null)throw t.cancellationError;try{return await n()}catch(c){if(t.cancellationError!==null)throw t.cancellationError;if(!E(a)&&!a(c)||d++>=o)throw c;typeof s=="function"&&s(c,d);let l=ih(r,d,i);return await En(l),u()}}}function ih(n,e,t){let r=n*Math.pow(2,e-1),i=ti(r);return Math.min(i,t)}function $s(n,e){return n.indexOf("playready")!==-1&&(V.browser===V.BROWSERS.EdgeChromium||V.browser===V.BROWSERS.Ie11||V.browser===V.BROWSERS.OtherIeOrEdgePreEdgeChromium)?Vo(e):e}var $n=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.reason=e}},Xs={EXPIRED:"expired",INTERNAL_ERROR:"internal-error",OUTPUT_RESTRICTED:"output-restricted"};function Zs(n,e,t){let{onKeyInternalError:r,onKeyOutputRestricted:i,onKeyExpiration:o}=e,a=[],s=[],d=[];n.keyStatuses.forEach((c,l)=>{let[f,p]=typeof c=="string"?[c,l]:[l,c],h=$s(t.keySystem,new Uint8Array(p)),I={keyId:h.buffer,keyStatus:f};switch(m.hasLevel("DEBUG")&&m.debug("DRM","key status update",{keyId:Ne(h),keyStatus:f}),f){case Xs.EXPIRED:{let g=new be("KEY_STATUS_CHANGE_ERROR",`A decryption key expired (${Ne(h)})`,{keyStatuses:[I,...d],keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()});if(o==="error"||o===void 0)throw g;switch(o){case"close-session":throw new $n(g);case"fallback":a.push(h);break;default:o==="continue"||o===void 0?s.push(h):ze(o);break}d.push(I);break}case Xs.INTERNAL_ERROR:{let g=new be("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ne(h)})`,{keyStatuses:[I,...d],keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()});switch(r){case void 0:case"error":throw g;case"close-session":throw new $n(g);case"fallback":a.push(h);break;case"continue":s.push(h);break;default:if(r!==void 0)ze(r);else throw g}d.push(I);break}case Xs.OUTPUT_RESTRICTED:{let g=new be("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ne(h)})`,{keyStatuses:[I,...d],keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()});switch(i){case void 0:case"error":throw g;case"fallback":a.push(h);break;case"continue":s.push(h);break;default:if(i!==void 0)ze(i);else throw g}d.push(I);break}default:s.push(h);break}});let u;return d.length>0&&(u=new be("KEY_STATUS_CHANGE_ERROR","One or several problematic key statuses have been encountered",{keyStatuses:d,keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()})),{warning:u,blacklistedKeyIds:a,whitelistedKeyIds:s}}function Js(n,e,t,r,i){m.info("DRM","Binding session events",{sessionId:n.sessionId});let{getLicenseConfig:o={}}=e,a=new U;a.linkToSignal(i),E(n.closed)||n.closed.then(()=>a.cancel()).catch(c=>{i.isCancelled()||(a.cancel(),r.onError(c))}),jo(n,c=>{a.cancel(),r.onError(new be("KEY_ERROR",c.type,{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem}))},a.signal),zc(n,()=>{m.info("DRM","keystatuseschange event received",{sessionId:n.sessionId});try{s()}catch(c){if(i.isCancelled()||a.isUsed()&&c instanceof Tr)return;a.cancel(),r.onError(c)}},a.signal),Go(n,c=>{let l=c,f=new Uint8Array(l.message),p=w(l.messageType)?l.messageType:"license-request";m.info("DRM","Received message event",{messageType:p,sessionId:n.sessionId});let h=u(o.retry);Qs(()=>d(f,p),h,a.signal).then(async I=>{if(!a.isUsed())if(E(I))m.info("DRM","No license given, skipping session.update");else try{await oh(n,I,t)}catch(g){a.cancel(),r.onError(g)}},I=>{if(a.isUsed())return;a.cancel();let g=hf(I,t);if(!E(I)){let{fallbackOnLastTry:b}=I;if(b===!0){m.warn("DRM","Last `getLicense` attempt failed. Blacklisting the current session."),r.onError(new Xn(g));return}}r.onError(g)})},a.signal),m.info("DRM","transmitting current keystatuses",{sessionId:n.sessionId}),s();return;function s(){if(a.isUsed()||n.keyStatuses.size===0)return;let{warning:c,blacklistedKeyIds:l,whitelistedKeyIds:f}=Zs(n,e,t);c!==void 0&&(r.onWarning(c),a.isUsed())||r.onKeyUpdate({whitelistedKeyIds:f,blacklistedKeyIds:l})}function d(c,l){let f;return new Promise((p,h)=>{try{m.debug("DRM","Calling `getLicense`",{messageType:l});let b=e.getLicense(c,l),T=E(o.timeout)?10*1e3:o.timeout;T>=0&&(f=setTimeout(()=>{h(new ni(`"getLicense" timeout exceeded (${T} ms)`))},T)),Promise.resolve(b).then(I,g)}catch(b){g(b)}function I(b){f!==void 0&&clearTimeout(f),p(b)}function g(b){f!==void 0&&clearTimeout(f),h(b)}})}function u(c){return{totalRetry:c!=null?c:2,baseDelay:200,maxDelay:3e3,shouldRetry:l=>l instanceof ni||E(l)||l.noRetry!==!0,onRetry:l=>r.onWarning(hf(l,t))}}}function hf(n,e){if(n instanceof ni)return new be("KEY_LOAD_TIMEOUT","The license server took too much time to respond.",{keyStatuses:void 0,keySystemConfiguration:e.getConfiguration(),keySystem:e.keySystem});let t=new be("KEY_LOAD_ERROR","An error occured when calling `getLicense`.",{keyStatuses:void 0,keySystemConfiguration:e.getConfiguration(),keySystem:e.keySystem});return!E(n)&&w(n.message)&&(t.message=n.message),t}async function oh(n,e,t){m.info("DRM","Updating MediaKeySession with message");try{await n.update(e)}catch(r){let i=r instanceof Error?r.toString():"`session.update` failed";throw new be("KEY_UPDATE_ERROR",i,{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem})}m.info("DRM","MediaKeySession update succeeded.")}var Xn=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.sessionError=e}},ni=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Xn.prototype),this.message=e}};async function ah(n,e,t){try{return await n.setServerCertificate(e)}catch(r){m.warn("DRM","mediaKeys.setServerCertificate returned an error",r instanceof Error?r:"");let i=r instanceof Error?r.toString():"`setServerCertificate` error";throw new be("LICENSE_SERVER_CERTIFICATE_ERROR",i,{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem})}}async function ed(n,e,t){if(kn.hasOne(n)===!0)return m.info("DRM","The MediaKeys already has a server certificate, skipping..."),{type:"already-has-one"};if(typeof n.setServerCertificate!="function")return m.warn("DRM","Could not set the server certificate. mediaKeys.setServerCertificate is not a function"),{type:"method-not-implemented"};m.info("DRM","Setting server certificate on the MediaKeys"),kn.prepare(n);try{let r=await ah(n,e,t);return kn.set(n,e),{type:"success",value:r}}catch(r){return{type:"error",value:Zt(r)?r:new be("LICENSE_SERVER_CERTIFICATE_ERROR","Unknown error when setting the server certificate.",{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem})}}}function td(n,e){if(isNaN(e)||e<0||e>=n.getLength())return;let t=n.getLength(),r=t-e;m.info("DRM","Too many stored persistent sessions, removing some.",{numberOfPersistentSessions:t,toDelete:r}),n.deleteOldSessions(r)}function nd(n){if(Ce(n,"com.microsoft.playready")||n==="com.chromecast.playready"||n==="com.youtube.playready")return"9a04f07998404286ab92e65be0885f95";if(n==="com.widevine.alpha")return"edef8ba979d64acea3c827dcd51d21ed";if(Ce(n,"com.apple.fps"))return"94ce86fb07ff4f43adb893d2fa968ca2";if(Ce(n,"com.nagra."))return"adb41c242dbf4a6d958b4457c0d27b95"}var ri=class n{constructor(e){this._innerValues=e,this._lazyFormattedValues=null}constructRequestData(){return de(...this._innerValues.map(e=>e.data))}isCompatibleWith(e){let t=e instanceof n?e.getFormattedValues():e;return Qn(this.getFormattedValues(),t)}getFormattedValues(){return this._lazyFormattedValues===null&&(this._lazyFormattedValues=sh(this._innerValues)),this._lazyFormattedValues}};function sh(n){return n.slice().sort((e,t)=>e.systemId===t.systemId?0:e.systemId===void 0?1:t.systemId===void 0||e.systemId<t.systemId?-1:1).map(({systemId:e,data:t})=>({systemId:e,data:t,hash:rn(t)}))}function rd(n,e,t){let r=`${n};codecs="${e}"`,i=t.filter(o=>o.mimeType===n);if(i.length!==0)for(let{codec:o,mimeType:a,result:s}of i){let d=`${a};codecs="${o}"`;if(da(r,d))return s}}var ii=class extends se{constructor(e,t,r){super(),m.debug("DRM","Starting ContentDecryptor logic.");let i=new U;this._currentSessions=[],this._canceller=i,this._initDataQueue=[],this._stateData={state:0,isMediaKeysAttached:0,isInitDataQueueLocked:!0,data:null},this._supportedCodecWhenEncrypted=[],this.error=null,this._eme=e,this._eme.onEncrypted(t,o=>{m.debug("DRM","Encrypted event received from media element.");let a=aa(o);a!==null&&this.onInitializationData(a)},i.signal),Ys(this._eme,t,r,i.signal).then(o=>{let{options:a,mediaKeySystemAccess:s}=o;this._supportedCodecWhenEncrypted=o.codecSupport;let d;(E(a.persistentLicenseConfig)||a.persistentLicenseConfig.disableRetroCompatibility===!0)&&(d=nd(s.keySystem)),this.systemId=d,this._stateData.state===0&&(m.debug("DRM","Waiting for attachment."),this._stateData={state:1,isInitDataQueueLocked:!0,isMediaKeysAttached:0,data:{mediaKeysInfo:o,mediaElement:t}},this.trigger("stateChange",this._stateData.state))}).catch(o=>{this._onFatalError(o)})}getState(){return this._stateData.state}attach(){if(this._stateData.state!==1)throw new Error("`attach` should only be called when in the WaitingForAttachment state");if(this._stateData.isMediaKeysAttached!==0){m.warn("DRM","ContentDecryptor's `attach` method called more than once.");return}let{mediaElement:e,mediaKeysInfo:t}=this._stateData.data,{options:r,mediaKeys:i,mediaKeySystemAccess:o,stores:a,askedConfiguration:s}=t;if(r.disableMediaKeysAttachmentLock===!0&&(m.debug("DRM","disabling MediaKeys attachment lock. Ready for content"),this._stateData={state:2,isInitDataQueueLocked:!0,isMediaKeysAttached:1,data:{mediaKeysInfo:t,mediaElement:e}},this.trigger("stateChange",this._stateData.state),this._isStopped()))return;this._stateData.isMediaKeysAttached=1;let u={emeImplementation:this._eme,loadedSessionsStore:a.loadedSessionsStore,mediaKeySystemAccess:o,mediaKeys:i,askedConfiguration:s,keySystemOptions:r};m.debug("DRM","Attaching current MediaKeys"),Ze.attach(e,u).then(async()=>{if(this._isStopped())return;this._stateData.isMediaKeysAttached=2;let{serverCertificate:c}=r;if(!E(c)){let f=await ed(i,c,o);f.type==="error"&&this.trigger("warning",f.value)}if(this._isStopped())return;let l=this._stateData.state;this._stateData={state:2,isMediaKeysAttached:2,isInitDataQueueLocked:!1,data:{mediaKeysData:t}},l!==2&&this.trigger("stateChange",2),this._isStopped()||this._processCurrentInitDataQueue()}).catch(c=>{this._onFatalError(c)})}dispose(){this.removeEventListener(),this._stateData={state:4,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("stateChange",this._stateData.state)}isCodecSupported(e,t){if(this._stateData.state===0){m.error("DRM","Asking for codec support while the ContentDecryptor is still initializing");return}return(this._stateData.state===3||this._stateData.state===4)&&m.error("DRM","Asking for codec support while the ContentDecryptor is disposed"),rd(e,t,this._supportedCodecWhenEncrypted)}onInitializationData(e){if(this._stateData.isInitDataQueueLocked!==!1){if(this._isStopped())throw new Error("ContentDecryptor either disposed or stopped.");this._initDataQueue.push(e);return}let{mediaKeysData:t}=this._stateData.data,r=ue(ae({},e),{values:new ri(e.values)});this._processInitializationData(r,t).catch(i=>{this._onFatalError(i)})}async _processInitializationData(e,t){var I,g,b;m.hasLevel("DEBUG")&&m.debug("DRM","processing init data",(I=e.content)==null?void 0:I.adaptation.type,(g=e.content)==null?void 0:g.representation.bitrate,((b=e.keyIds)!=null?b:[]).map(T=>Ne(T)).join(", "));let{mediaKeySystemAccess:r,stores:i,options:o}=t;if(this._tryToUseAlreadyCreatedSession(e,t)||this._isStopped())return;if(o.singleLicensePer==="content"){let T=Q(this._currentSessions,v=>v.source==="created-session");if(T!==void 0){let v=e.keyIds;if(v===void 0){e.content===void 0?m.warn("DRM","Unable to fallback from a non-decipherable quality."):(m.debug("DRM","Blacklisting new init data (due to singleLicensePer content policy)"),this.trigger("blackListProtectionData",e));return}if(T.record.associateKeyIds(v),e.content===void 0)m.warn("DRM","Unable to fallback from a non-decipherable quality.");else{if(m.hasLevel("DEBUG")){let _=v.reduce((R,k)=>`${R}, ${Ne(k)}`,"");m.debug("DRM","Blacklisting new key ids",_)}this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:v,delistedKeyIds:[]})}return}}else if(o.singleLicensePer==="periods"&&e.content!==void 0){let{period:T}=e.content,v=this._currentSessions.filter(R=>R.source==="created-session"),_=new Set;od(_,T);for(let R of v){let k=Array.from(_);for(let x of k)if(R.record.isAssociatedWithKeyId(x)){R.record.associateKeyIds(_.values());for(let P of k)!R.keyStatuses.whitelisted.some(M=>Se(M,P))&&!R.keyStatuses.blacklisted.some(M=>Se(M,P))&&R.keyStatuses.blacklisted.push(P);m.hasLevel("DEBUG")&&m.debug("DRM","Session already created for",Ne(x),'under singleLicensePer "periods" policy'),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:R.keyStatuses.whitelisted,blacklistedKeyIds:R.keyStatuses.blacklisted,delistedKeyIds:[]});return}}}this._lockInitDataQueue();let a;dh(r)&&(!E(o.persistentLicenseConfig)||!uh(r))?a="persistent-license":a="temporary";let{EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:s,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:d}=O.getCurrent(),u=typeof o.maxSessionCacheSize=="number"?o.maxSessionCacheSize:s,c=await Ws(e,i,a,u,this._canceller.signal);if(this._isStopped())return;let l={record:c.value.keySessionRecord,source:c.type,keyStatuses:{whitelisted:[],blacklisted:[]},blacklistedSessionError:null};this._currentSessions.push(l);let{mediaKeySession:f,sessionType:p}=c.value,h=!1;if(Js(f,o,r,{onKeyUpdate:T=>{let v=fh(e,l.record,o.singleLicensePer,l.source==="created-session",T.whitelistedKeyIds,T.blacklistedKeyIds);if(l.record.associateKeyIds(v.whitelisted),l.record.associateKeyIds(v.blacklisted),l.keyStatuses={whitelisted:v.whitelisted,blacklisted:v.blacklisted},l.record.getAssociatedKeyIds().length!==0&&p==="persistent-license"&&i.persistentSessionsStore!==null&&!h){let{persistentSessionsStore:_}=i;td(_,d-1),_.add(e,l.record.getAssociatedKeyIds(),f),h=!0}e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:v.whitelisted,blacklistedKeyIds:v.blacklisted,delistedKeyIds:[]}),this._unlockInitDataQueue()},onWarning:T=>{this.trigger("warning",T)},onError:T=>{var v;if(T instanceof $n){m.warn("DRM","A session's closing condition has been triggered"),this._lockInitDataQueue();let _=this._currentSessions.indexOf(l);_>=0&&this._currentSessions.splice(_),e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:[],delistedKeyIds:l.record.getAssociatedKeyIds()}),(v=i.persistentSessionsStore)==null||v.delete(f.sessionId),i.loadedSessionsStore.closeSession(f).catch(R=>{let k=R instanceof Error?R:"unknown error";m.warn("DRM","failed to close expired session",k)}).then(()=>this._unlockInitDataQueue()).catch(R=>this._onFatalError(R)),this._isStopped()||this.trigger("warning",T.reason);return}if(!(T instanceof Xn)){this._onFatalError(T);return}l.blacklistedSessionError=T,e.content!==void 0&&(m.info("DRM","blacklisting Representations based on protection data."),this.trigger("blackListProtectionData",e)),this._unlockInitDataQueue()}},this._canceller.signal),(o.singleLicensePer===void 0||o.singleLicensePer==="init-data")&&this._unlockInitDataQueue(),c.type==="created-session"){let T=e.values.constructRequestData();try{await i.loadedSessionsStore.generateLicenseRequest(f,e.type,T)}catch(v){let _=i.loadedSessionsStore.getEntryForSession(f);if(_===null||_.closingStatus.type!=="none"){let R=this._currentSessions.indexOf(l);return R>=0&&this._currentSessions.splice(R,1),Promise.resolve()}throw new be("KEY_GENERATE_REQUEST_ERROR",v instanceof Error?v.toString():"Unknown error",{keyStatuses:void 0,keySystemConfiguration:r.getConfiguration(),keySystem:r.keySystem})}}return Promise.resolve()}_tryToUseAlreadyCreatedSession(e,t){let{stores:r,options:i}=t,o=Q(this._currentSessions,c=>c.record.isCompatibleWith(e));if(o===void 0)return!1;if(e.forceSessionRecreation===!0)return this.removeSessionForInitData(e,t),!1;let s=o.blacklistedSessionError;if(!E(s))return e.type===void 0||e.content===void 0?(m.error("DRM","This initialization data has already been blacklisted but the current content is not known."),!0):(m.info("DRM","This initialization data has already been blacklisted. Blacklisting the related content."),this.trigger("blackListProtectionData",e),!0);if(e.keyIds!==void 0){let c;if(i.singleLicensePer===void 0||i.singleLicensePer==="init-data"){let{blacklisted:l}=o.keyStatuses;c=pf(e.keyIds,l)}else{let{whitelisted:l}=o.keyStatuses;c=!Yn(e.keyIds,l)}if(c)return e.content===void 0?(m.error("DRM","Cannot forbid key id, the content is unknown."),!0):(m.info("DRM","Current initialization data is linked to blacklisted keys. Marking Representations as not decipherable"),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:e.keyIds,delistedKeyIds:[]}),!0)}if(r.loadedSessionsStore.reuse(e)!==null)return m.debug("DRM","Init data already processed. Skipping it."),!0;let u=this._currentSessions.indexOf(o);return u===-1?m.error("DRM","Unable to remove processed init data: not found."):(m.debug("DRM","A session from a processed init data is not available anymore. Re-processing it."),this._currentSessions.splice(u,1)),!1}removeSessionForInitData(e,t){let{stores:r}=t,i=r.loadedSessionsStore.reuse(e);i!==null&&r.loadedSessionsStore.closeSession(i.mediaKeySession).catch(()=>m.error("DRM","Cannot close the session from the loaded session store"));let o=Q(this._currentSessions,s=>s.record.isCompatibleWith(e));if(o===void 0)return;let a=this._currentSessions.indexOf(o);a!==-1&&(m.debug("DRM","A session from a processed init is removed due to forceSessionRecreation policy."),this._currentSessions.splice(a,1))}_onFatalError(e){if(this._canceller.isUsed())return;let t=e instanceof Error?e:new We("NONE","Unknown decryption error");this.error=t,this._initDataQueue.length=0,this._stateData={state:3,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("error",t),this._stateData.state===3&&this.trigger("stateChange",this._stateData.state)}_isStopped(){return this._stateData.state===4||this._stateData.state===3}_processCurrentInitDataQueue(){for(;this._stateData.isInitDataQueueLocked===!1;){let e=this._initDataQueue.shift();if(e===void 0)return;this.onInitializationData(e)}}_lockInitDataQueue(){this._stateData.isInitDataQueueLocked===!1&&(this._stateData.isInitDataQueueLocked=!0)}_unlockInitDataQueue(){if(this._stateData.isMediaKeysAttached!==2){m.error("DRM","Trying to unlock in the wrong state");return}this._stateData.isInitDataQueueLocked=!1,this._processCurrentInitDataQueue()}};function dh(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&$(e,"persistent-license")}function uh(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&$(e,"temporary")}function yf(n,e){return n.filter(t=>!e.some(r=>Se(r,t)))}function lh(n,e){let t=n.getAssociatedKeyIds(),r=yf(t,e);return r.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM","KeySessionRecord's keys missing in the license, blacklisting them",r.map(i=>Ne(i)).join(", ")),r}function ch(n,e){let t=[],{keyIds:r}=n;return r!==void 0&&(t=yf(r,e)),t.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM","init data keys missing in the license, blacklisting them",t.map(i=>Ne(i)).join(", ")),t}function fh(n,e,t,r,i,o){var u;let a=[...i,...o],s=lh(e,a),d=a.concat(s);if(t!==void 0&&t!=="init-data"){let c=ch(n,d);d.push(...c);let{content:l}=n;if(r&&l!==void 0){if(t==="content"){let f=new Set,{manifest:p}=l;for(let h of p.periods)od(f,h);id(f,d)}else if(t==="periods"){let{manifest:f}=l;for(let p of f.periods){let h=new Set;if(od(h,p),((u=n.content)==null?void 0:u.period.id)===p.id)id(h,d);else{let I=Array.from(h);for(let g of I)if(d.some(T=>Se(T,g))){id(h,d);break}}}}}}return{whitelisted:i,blacklisted:d.slice(i.length)}}function id(n,e){let t=Array.from(n.values());for(let r of t)e.some(o=>Se(o,r))||e.push(r)}function od(n,e){let t=e.adaptations,r=Cr(t).reduce((i,o)=>E(o)?i:i.concat(o),[]);for(let i of r)for(let o of i.representations)if(o.contentProtections!==void 0&&o.contentProtections.keyIds!==void 0)for(let a of o.contentProtections.keyIds)n.add(a)}function Zn(n){let e=Ze.getAwaitedState(n);return e===null?null:[e.mediaKeySystemAccess.keySystem,e.mediaKeySystemAccess.getConfiguration()]}var If=ii;function bf(n){var t,r,i,o,a;let e=[];for(let s of n.periods){let d=[...(t=s.adaptations.video)!=null?t:[],...(r=s.adaptations.audio)!=null?r:[]];for(let u of d)if(u.supportStatus.hasCodecWithUndefinedSupport)for(let c of u.representations)c.isSupported===void 0&&e.push({mimeType:(i=c.mimeType)!=null?i:"",codec:(a=(o=c.codecs)==null?void 0:o[0])!=null?a:""})}return e}var Sf=[];function Ft(n){$(Sf,n)||(console.warn(n),Sf.push(n))}var oi=class{constructor(e){this.supportMap=new Map,this.addCodecs(e)}addCodecs(e){for(let t of e){let r=this.supportMap.get(t.mimeType);r===void 0&&(r=new Map,this.supportMap.set(t.mimeType,r)),r.set(t.codec,{supported:t.supported,supportedIfEncrypted:t.supportedIfEncrypted})}}isSupported(e,t,r){let i=this.supportMap.get(e);if(i===void 0)return;let o=i.get(t);if(o!==void 0)return r?o.supportedIfEncrypted:o.supported}};var ai=class{constructor(e,t,r){if(this.id=e.id,this.adaptations=mh(e.adaptations,t,r),Tf(this.adaptations.video)&&Tf(this.adaptations.audio))throw new re("MANIFEST_PARSE_ERROR","The manifest has no video nor audio tracks.");this.thumbnailTracks=e.thumbnailTracks.map(i=>({id:i.id,mimeType:i.mimeType,index:i.index,cdnMetadata:i.cdnMetadata,height:i.height,width:i.width,horizontalTiles:i.horizontalTiles,verticalTiles:i.verticalTiles,start:i.start,end:i.end,tileDuration:i.tileDuration})),this.duration=e.duration,this.start=e.start,!E(this.duration)&&!E(this.start)&&(this.end=this.start+this.duration),this.streamEvents=e.streamEvents===void 0?[]:e.streamEvents}refreshCodecSupport(e,t){Object.keys(this.adaptations).forEach(r=>{let i=this.adaptations[r];if(i!==void 0)for(let o of i){if(!o.supportStatus.hasCodecWithUndefinedSupport)continue;let a=o.supportStatus.hasSupportedCodec;o.refreshCodecSupport(t),a!==!1&&o.supportStatus.hasSupportedCodec===!1&&e.push(o)}},{})}getAdaptations(){return ys(this)}getAdaptationsForType(e){let t=this.adaptations[e];return t!=null?t:[]}getAdaptation(e){return Q(this.getAdaptations(),({id:t})=>e===t)}getSupportedAdaptations(e){return Ot(this,e)}containsTime(e,t){return hs(this,e,t)}getMetadataSnapshot(){let e={},t=this.getAdaptations();for(let r of t){let i=e[r.type];i===void 0&&(i=[],e[r.type]=i),i.push(r.getMetadataSnapshot())}return{start:this.start,end:this.end,id:this.id,streamEvents:this.streamEvents,adaptations:e,thumbnailTracks:this.thumbnailTracks.map(r=>({id:r.id,mimeType:r.mimeType,height:r.height,width:r.width,horizontalTiles:r.horizontalTiles,verticalTiles:r.verticalTiles,start:r.start,end:r.end,tileDuration:r.tileDuration}))}}};function Tf(n){return Array.isArray(n)?n.length===0:!0}function mh(n,e,t){let r={};for(let[i,o]of Object.entries(n))E(o)||(r[i]=o.map(a=>new Ur(a,e,{representationFilter:t})).filter(a=>a.representations.length>0));return r}function si(n,e,t){let r={updatedAdaptations:[],removedAdaptations:[],addedAdaptations:[],updatedThumbnailTracks:[],removedThumbnailTracks:[],addedThumbnailTracks:[]};n.start=e.start,n.end=e.end,n.duration=e.duration,n.streamEvents=e.streamEvents;let i=n.thumbnailTracks,o=e.thumbnailTracks;for(let d=0;d<i.length;d++){let u=i[d],c=Ie(o,l=>l.id===u.id);if(c===-1){m.warn("manifest",'ThumbnailTrack "'+i[d].id+'" not found when merging.');let[l]=i.splice(d,1);d--,r.removedThumbnailTracks.push({id:l.id})}else{let[l]=o.splice(c,1);u.mimeType=l.mimeType,u.height=l.height,u.width=l.width,u.horizontalTiles=l.horizontalTiles,u.verticalTiles=l.verticalTiles,u.start=l.start,u.end=l.end,u.tileDuration=l.tileDuration,u.cdnMetadata=l.cdnMetadata,t===0?u.index._replace(l.index):u.index._update(l.index),r.updatedThumbnailTracks.push({id:u.id,mimeType:u.mimeType,height:u.height,width:u.width,horizontalTiles:u.horizontalTiles,verticalTiles:u.verticalTiles,start:u.start,end:u.end,tileDuration:u.tileDuration})}}o.length>0&&(m.warn("manifest",`${o.length} new Thumbnail tracks found when merging.`),r.addedThumbnailTracks.push(...o.map(d=>({id:d.id,mimeType:d.mimeType,height:d.height,width:d.width,horizontalTiles:d.horizontalTiles,verticalTiles:d.verticalTiles,start:d.start,end:d.end,tileDuration:d.tileDuration}))),n.thumbnailTracks.push(...o));let a=n.getAdaptations(),s=e.getAdaptations();for(let d=0;d<a.length;d++){let u=a[d],c=Ie(s,l=>l.id===u.id);if(c===-1){m.warn("manifest",'Adaptation "'+a[d].id+'" not found when merging.');let[l]=a.splice(d,1);d--,r.removedAdaptations.push({id:l.id,trackType:l.type})}else{let[l]=s.splice(c,1),f=[],p=[],h=[];r.updatedAdaptations.push({adaptation:u.id,trackType:u.type,updatedRepresentations:f,addedRepresentations:p,removedRepresentations:h});let I=u.representations,g=l.representations.slice();for(let b=0;b<I.length;b++){let T=I[b],v=Ie(g,_=>_.id===T.id);if(v===-1){m.warn("manifest",`Representation "${I[b].id}" not found when merging.`);let[_]=I.splice(b,1);b--,h.push(_.id)}else{let[_]=g.splice(v,1);f.push(T.getMetadataSnapshot()),T.cdnMetadata=_.cdnMetadata,t===0?T.index._replace(_.index):T.index._update(_.index)}}g.length>0&&(m.warn("manifest",`${g.length} new Representations found when merging.`),u.representations.push(...g),p.push(...g.map(b=>b.getMetadataSnapshot())))}}if(s.length>0){m.warn("manifest",`${s.length} new Adaptations found when merging.`);for(let d of s){let u=n.adaptations[d.type];u===void 0?n.adaptations[d.type]=[d]:u.push(d),r.addedAdaptations.push(d.getMetadataSnapshot())}}return r}function Ef(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]},r=0;for(let o=0;o<e.length;o++){let a=e[o],s=r,d=n[s];for(;d!==void 0&&d.id!==a.id;)s++,d=n[s];if(d!==void 0){let u=si(d,a,0);t.updatedPeriods.push({period:{id:d.id,start:d.start,end:d.end,duration:d.duration,streamEvents:d.streamEvents},result:u});let c=e.slice(r,o),l=s-r,f=n.splice(r,l,...c);t.removedPeriods.push(...f.map(p=>({id:p.id,start:p.start,end:p.end}))),t.addedPeriods.push(...c.map(p=>p.getMetadataSnapshot())),r=o+1}}if(r>n.length)return m.error("manifest","error when updating Periods"),t;if(r<n.length){let o=n.splice(r,n.length-r);t.removedPeriods.push(...o.map(a=>({id:a.id,start:a.start,end:a.end})))}let i=e.slice(r,e.length);return i.length>0&&(n.push(...i),t.addedPeriods.push(...i.map(o=>o.getMetadataSnapshot()))),t}function _f(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]};if(n.length===0)return n.splice(0,0,...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t;if(e.length===0)return t;let r=n[n.length-1];if(r.start<e[0].start){if(r.end!==e[0].start)throw new re("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");return n.push(...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t}let i=Ie(n,({id:s})=>s===e[0].id);if(i<0)throw new re("MANIFEST_UPDATE_ERROR","Cannot perform partial update: incoherent data");let o=si(n[i],e[0],1);t.updatedPeriods.push({period:Y(n[i].getMetadataSnapshot(),{adaptations:void 0}),result:o});let a=i+1;for(let s=1;s<e.length;s++){let d=e[s],u=-1;for(let c=a;c<n.length;c++)if(d.id===n[c].id){u=c;break}if(u<0){let c=-1;for(let p=a;p<n.length;p++)if(d.start<n[p].start){c=p;break}let l=c-a,f=n.splice(a,l,d);t.addedPeriods.push(d.getMetadataSnapshot()),t.removedPeriods.push(...f.map(p=>({id:p.id,start:p.start,end:p.end})))}else{if(u>a){m.warn("manifest","old Periods not found in new when updating, removing");let l=n.splice(a,u-a);t.removedPeriods.push(...l.map(f=>({id:f.id,start:f.start,end:f.end}))),u=a}let c=si(n[u],d,0);t.updatedPeriods.push({period:Y(n[u].getMetadataSnapshot(),{adaptations:void 0}),result:c})}a++}if(a<n.length){m.warn("manifest","Ending Periods not found in new when updating, removing");let s=n.splice(a,n.length-a);t.removedPeriods.push(...s.map(d=>({id:d.id,start:d.start,end:d.end})))}return t}var ph=rt(),di=class extends se{constructor(e,t){var o;super();let{representationFilter:r,manifestUpdateUrl:i}=t;this.manifestFormat=0,this.id=ph(),this.expired=(o=e.expired)!=null?o:null,this.transport=e.transportType,this.clockOffset=e.clockOffset,this._cachedCodecSupport=new oi([]),this.periods=e.periods.map(a=>new ai(a,this._cachedCodecSupport,r)).sort((a,s)=>a.start-s.start),this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.timeBounds=e.timeBounds,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.uris=e.uris===void 0?[]:e.uris,this.updateUrl=i,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.availabilityStartTime=e.availabilityStartTime,this.publishTime=e.publishTime}updateCodecSupport(e=[]){if(e.length===0)return null;this._cachedCodecSupport.addCodecs(e);let t=[];for(let r of this.periods)r.refreshCodecSupport(t,this._cachedCodecSupport);return this.trigger("supportUpdate",null),t.length>0?new re("MANIFEST_INCOMPATIBLE_CODECS_ERROR","An Adaptation contains only incompatible codecs.",{tracks:t.map(Tn)}):null}getPeriod(e){return Q(this.periods,t=>e===t.id)}getPeriodForTime(e){return Hn(this,e)}getNextPeriod(e){return Q(this.periods,t=>t.start>e)}getPeriodAfter(e){return Do(this,e)}getUrls(){return this.uris}replace(e){this._performUpdate(e,0)}update(e){this._performUpdate(e,1)}getMinimumSafePosition(){return bn(this)}getLivePosition(){return Sn(this)}getMaximumSafePosition(){return kt(this)}updateCodecSupportList(e){this._cachedCodecSupport=e}updateRepresentationsDeciperability(e){let t=gh(this,e);t.length>0&&this.trigger("decipherabilityUpdate",t)}addRepresentationsToAvoid(e){let t=[];for(let r of e){let i=this.getPeriod(r.period.id);if(i===void 0)continue;let o=i.getAdaptation(r.adaptation.id);if(o===void 0)continue;let a=o.getRepresentation(r.representation.id);a!==void 0&&(a.shouldBeAvoided=!0,t.push({manifest:this,period:i,adaptation:o,representation:a}))}t.length>0&&this.trigger("representationAvoidanceUpdate",t)}getAdaptations(){Ft("manifest.getAdaptations() is deprecated. Please use manifest.period[].getAdaptations() instead");let e=this.periods[0];if(e===void 0)return[];let t=e.adaptations,r=[];for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let o=t[i];r.push(...o)}return r}getAdaptationsForType(e){Ft("manifest.getAdaptationsForType(type) is deprecated. Please use manifest.period[].getAdaptationsForType(type) instead");let t=this.periods[0];if(t===void 0)return[];let r=t.adaptations[e];return r===void 0?[]:r}getAdaptation(e){return Ft("manifest.getAdaptation(id) is deprecated. Please use manifest.period[].getAdaptation(id) instead"),Q(this.getAdaptations(),({id:t})=>e===t)}getMetadataSnapshot(){let e=[];for(let t of this.periods)e.push(t.getMetadataSnapshot());return{manifestFormat:1,id:this.id,periods:e,isDynamic:this.isDynamic,isLive:this.isLive,isLastPeriodKnown:this.isLastPeriodKnown,suggestedPresentationDelay:this.suggestedPresentationDelay,clockOffset:this.clockOffset,uris:this.uris,availabilityStartTime:this.availabilityStartTime,timeBounds:this.timeBounds}}getCodecsWithUnknownSupport(){return bf(this)}_performUpdate(e,t){this.availabilityStartTime=e.availabilityStartTime,this.expired=e.expired,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.transport=e.transport,this.publishTime=e.publishTime;let r;if(t===0)this.timeBounds=e.timeBounds,this.uris=e.uris,r=Ef(this.periods,e.periods);else{this.timeBounds.maximumTimeData=e.timeBounds.maximumTimeData,this.updateUrl=e.uris[0],r=_f(this.periods,e.periods);let i=this.getMinimumSafePosition();for(;this.periods.length>0;){let o=this.periods[0];if(o.end===void 0||o.end>i)break;this.periods.shift()}}this.updateCodecSupport(),this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.trigger("manifestUpdate",r)}};function gh(n,e){let t=[];for(let r of n.periods)for(let i of r.getAdaptations()){let o=!0;for(let a of i.representations){let s={manifest:n,period:r,adaptation:i,representation:a},d=e(s);d!==!1&&(o=!1),d!==a.decipherable&&(t.push(s),a.decipherable=d,d===!0?i.supportStatus.isDecipherable=!0:d===void 0&&i.supportStatus.isDecipherable===!1&&(i.supportStatus.isDecipherable=void 0),m.debug("manifest",`Decipherability changed for "${a.id}"`,`(${a.bitrate})`,String(a.decipherable)))}o&&(i.supportStatus.isDecipherable=!1)}return t}function Dt(n,e){return n.segment.id===e.segment.id&&n.representation.uniqueId===e.representation.uniqueId}function bt(n){if(E(n))return null;let{period:e,adaptation:t,representation:r,segment:i}=n;return{t:t.type[0],p:e.id,a:t.id,r:r.id,ss:i.isInit?null:i.time,se:i.isInit||!i.complete?null:i.end}}var Jn=di;function mt(n){return n instanceof Ae?new ut("PIPELINE_LOAD_ERROR",n):Me(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function hh(n){return n instanceof Ae?n.type===yn.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412:n.type===yn.TIMEOUT||n.type===yn.ERROR_EVENT:n instanceof dt?typeof n.canRetry=="boolean"?n.canRetry:n.xhr!==void 0?n.xhr.status>=500||n.xhr.status===404||n.xhr.status===415||n.xhr.status===412:!1:Zt(n)&&n.code==="INTEGRITY_ERROR"}async function ui(n,e,t,r,i){if(i.cancellationError!==null)return Promise.reject(i.cancellationError);let{baseDelay:o,maxDelay:a,maxRetry:s,onRetry:d}=r;n!==null&&n.length===0&&m.warn("utils","No CDN given to `scheduleRequestWithCdns`.");let u=new Map,c=l();if(c===void 0)throw new Error("No CDN to request");return f(c);function l(){if(n===null){let g=u.get(null);return g!==void 0&&g.isBlacklisted?void 0:null}else{if(e===null)return I(n);{let g=e.getCdnPreferenceForResource(n);return I(g)}}}async function f(g){try{return await t(g,i)}catch(b){if(U.isCancellationError(b))throw b;g!==null&&e!==null&&e.downgradeCdn(g);let T=u.get(g);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(g,T)):T.errorCounter++,!hh(b))return T.blockedUntil=void 0,T.isBlacklisted=!0,p(b);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let v=T.errorCounter,_=Math.min(o*Math.pow(2,v-1),a),R=ti(_);T.blockedUntil=z()+R}return p(b)}}async function p(g){let b=l();if(i.isCancelled())throw i.cancellationError;if(b===void 0)throw g;if(d(g),i.isCancelled())throw i.cancellationError;return h(b,g)}function h(g,b){let T=u.get(g);if(T===void 0||T.blockedUntil===void 0)return f(g);let v=z(),_=T.blockedUntil-v;if(_<=0)return f(g);let R=new U,k=R.linkToSignal(i);return new Promise((x,P)=>{e==null||e.addEventListener("priorityChange",()=>{let F=l();if(i.isCancelled())throw i.cancellationError;if(F===void 0)return L(b);F!==g&&(R.cancel(),h(F,b).then(M,L))},R.signal),en(_,R.signal).then(()=>f(g).then(M,L),te);function M(F){k(),x(F)}function L(F){k(),P(F)}})}function I(g){var T;if(u.size===0)return g[0];let b=z();return(T=g.filter(v=>{var _;return((_=u.get(v))==null?void 0:_.isBlacklisted)!==!0}).reduce((v,_)=>{var k;let R=(k=u.get(_))==null?void 0:k.blockedUntil;return R!==void 0&&R<=b&&(R=void 0),v===void 0?[_,R]:v[1]===void 0?v:R===void 0?[_,void 0]:R<v[1]?[_,R]:v},void 0))==null?void 0:T[0]}}function ad(n,e,t){return ui(null,null,n,e,t)}var li=class extends se{constructor(e,t,r){super(),this.scheduleManualRefresh=te,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new U,this._isStarted=!1,this._isRefreshPending=!1,this._consecutiveUnsafeMode=0,this._prioritizedContentUrl=null}dispose(){this._canceller.cancel(),this.removeEventListener()}start(){if(this._isStarted)return;this._isStarted=!0;let e,t=this._settings.initialManifest;t instanceof Jn?e=Promise.resolve({manifest:t}):t!==void 0?e=this.parse(t,{previousManifest:null,unsafeMode:!1},void 0):e=this._fetchManifest(void 0).then(r=>r.parse({previousManifest:null,unsafeMode:!1})),e.then(r=>{this.trigger("manifestReady",r.manifest),this._canceller.isUsed()||this._recursivelyRefreshManifest(r.manifest,r)}).catch(r=>this._onFatalError(r))}updateContentUrls(e,t){var r;this._prioritizedContentUrl=(r=e==null?void 0:e[0])!=null?r:void 0,t&&this.scheduleManualRefresh({enablePartialRefresh:!1,delay:0,canUseUnsafeMode:!1})}async _fetchManifest(e){var u;let t=this._canceller.signal,r=this._settings,i=this._transportName,o=this._pipelines,a=e!=null?e:(u=this._manifestUrls)==null?void 0:u[0],s=this._getBackoffSetting(c=>{this.trigger("warning",mt(c))});try{let c=await d(a);return{parse:l=>this._parseLoadedManifest(c,l,a)}}catch(c){throw mt(c)}function d(c){var g;let{loadManifest:l}=o,f=r.requestTimeout===void 0?O.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,p=r.connectionTimeout===void 0?O.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;f<0&&(f=void 0),p<0&&(p=void 0);let h={timeout:f,connectionTimeout:p,cmcdPayload:(g=r.cmcdDataBuilder)==null?void 0:g.getCmcdDataForManifest(i)};return ad(()=>l(c,h,t),s,t)}}parse(e,t,r){return this._parseLoadedManifest({responseData:e,size:void 0,requestDuration:void 0},t,r)}async _parseLoadedManifest(e,t,r){var I;let i=z(),o=this._canceller.signal,a=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(g=>{this.trigger("warning",mt(g))}),c=r!=null?r:(I=this._manifestUrls)==null?void 0:I[0],l={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:c};try{let g=this._pipelines.parseManifest(e,l,p,o,f);if(yh(g)){let{manifest:b}=await g;return h(b)}else return h(g.manifest)}catch(g){throw Me(g,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function f(g){try{return await ad(g,u,o)}catch(b){throw mt(b)}}function p(g){for(let b of g){if(o.isCancelled())return;let T=Me(b,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});a("warning",T)}}function h(g){let b=z()-i;return m.info("MF",`Manifest parsed in ${b}ms`),{manifest:g,sendingTime:s,receivedTime:d,parsingTime:b}}}_getBackoffSetting(e){let{DEFAULT_MAX_MANIFEST_REQUEST_RETRY:t,INITIAL_BACKOFF_DELAY_BASE:r,MAX_BACKOFF_DELAY_BASE:i}=O.getCurrent(),{lowLatencyMode:o,maxRetry:a}=this._settings,s=o?r.LOW_LATENCY:r.REGULAR,d=o?i.LOW_LATENCY:i.REGULAR,u=a!=null?a:t;return{onRetry:e,baseDelay:s,maxDelay:d,maxRetry:u}}_recursivelyRefreshManifest(e,{sendingTime:t,parsingTime:r,updatingTime:i}){let{MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:o,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:a}=O.getCurrent(),s=r!==void 0?r+(i!=null?i:0):void 0,d=!1;this._consecutiveUnsafeMode>0?d=this._consecutiveUnsafeMode<o:s!==void 0&&(d=s>=a);let u=t===void 0?0:z()-t,c=Math.max(this._settings.minimumManifestUpdateInterval-u,0),l=new U;if(l.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=f=>{let{enablePartialRefresh:p,delay:h,canUseUnsafeMode:I}=f,g=I&&d,b=t===void 0?0:z()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-b,0),v=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:p,unsafeMode:g})},Math.max((h!=null?h:0)-b,T));l.signal.register(()=>{clearTimeout(v)})},e.expired!==null){let f=setTimeout(()=>{var p;(p=e.expired)==null||p.then(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},te)},c);l.signal.register(()=>{clearTimeout(f)})}if(e.lifetime!==void 0&&e.lifetime>=0){let f=e.lifetime*1e3-u,p;s===void 0?p=f:e.lifetime<3&&s>=100?(p=Math.min(Math.max(3e3-u,Math.max(f,0)+s),f*6),m.info("MF","Manifest update rythm is too frequent. Postponing next request.",{regularRefreshDelay:f,newRefreshDelay:p})):s>=e.lifetime*1e3/10?(p=Math.min(Math.max(f,0)+s,f*6),m.info("MF","Manifest took too long to parse. Postponing next request",{regularRefreshDelay:f,newRefreshDelay:p})):p=f;let h=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(p,c));l.signal.register(()=>{clearTimeout(h)})}}_triggerNextManifestRefresh(e,{enablePartialRefresh:t,unsafeMode:r}){let i=e.updateUrl,o,a;this._prioritizedContentUrl!==null?(o=!0,a=this._prioritizedContentUrl,this._prioritizedContentUrl=null):(o=!t||i===void 0,a=o?e.getUrls()[0]:i);let s=e.clockOffset;r?(this._consecutiveUnsafeMode+=1,m.info("MF",'Refreshing the Manifest in "unsafeMode" for the '+String(this._consecutiveUnsafeMode)+" consecutive time.")):this._consecutiveUnsafeMode>0&&(m.info("MF",'Not parsing the Manifest in "unsafeMode" anymore after '+String(this._consecutiveUnsafeMode)+" consecutive times."),this._consecutiveUnsafeMode=0),!this._isRefreshPending&&(this._isRefreshPending=!0,this._fetchManifest(a).then(d=>d.parse({externalClockOffset:s,previousManifest:e,unsafeMode:r})).then(d=>{this._isRefreshPending=!1;let{manifest:u,sendingTime:c,parsingTime:l}=d,f=z();if(o)e.replace(u);else try{e.update(u)}catch(h){let I=h instanceof Error?h.message:"unknown error";m.warn("MF",`Attempt to update Manifest failed: ${I}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:g}=O.getCurrent(),b=c===void 0?0:z()-c,T=Math.max(this._settings.minimumManifestUpdateInterval-b,0),v=te,_=setTimeout(()=>{v(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(g-b,T));v=this._canceller.signal.register(()=>{clearTimeout(_)});return}let p=z()-f;this._recursivelyRefreshManifest(e,{sendingTime:c,parsingTime:l,updatingTime:p})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose())}};function yh(n){return n instanceof Promise}var sd=li;function dd(n,e){let t=new WeakMap;return{createRequest(r,i,o,a){let s=u=>e(r,o,u),d=n.create(s,i,o,a);return t.set(d,s),d},updatePriority(r,i){let o=t.get(r);if(o===void 0){m.warn("SF","Cannot update the priority of a request: task not found.");return}n.updatePriority(o,i)}}}var ud=class{constructor(){this._cache=new WeakMap}add({representation:e,segment:t},r){t.isInit&&this._cache.set(e,r)}get({representation:e,segment:t}){if(t.isInit){let r=this._cache.get(e);if(r!==void 0)return r}return null}},vf=ud;var Ih=rt();function ld({bufferType:n,pipeline:e,cdnPrioritizer:t,cmcdDataBuilder:r,eventListeners:i,requestOptions:o}){let a;o.connectionTimeout===void 0||o.connectionTimeout<0?a=void 0:a=o.connectionTimeout;let s={timeout:o.requestTimeout<0?void 0:o.requestTimeout,connectionTimeout:a,cmcdPayload:void 0},d=$(["audio","video"],n)?new vf:void 0,{loadSegment:u,parseSegment:c}=e;return async function(f,p,h){var q,X,W;let{segment:I,adaptation:g,representation:b,manifest:T,period:v}=f,_=bt(f),R=Ih(),k,x=[],P=0,M=!1,L={segment:I,type:g.type,language:g.language,isLive:T.isLive,periodStart:v.start,periodEnd:v.end,mimeType:b.mimeType,codecs:b.codecs[0],manifestPublishTime:T.publishTime},F={onProgress(H){var G;k===void 0&&H.totalSize!==void 0&&H.size<H.totalSize&&((G=i.onProgress)==null||G.call(i,{duration:H.duration,size:H.size,totalSize:H.totalSize,timestamp:z(),id:R}))},onNewChunk(H){p.onChunk(C(H,!0))}},D=d!==void 0?d.get(f):null;if(D!==null)return m.debug("SF","Found wanted segment in cache",_),p.onChunk(C(D,!1)),Promise.resolve();m.debug("SF","Beginning request",_),(q=i.onRequestBegin)==null||q.call(i,{requestTimestamp:z(),id:R,content:f}),h.register(B);try{let H=await ui(f.representation.cdnMetadata,t,A,Y({onRetry:N},o),h);if(H.resultType==="segment-loaded"){let G=H.resultData.responseData;d!==void 0&&d.add(f,H.resultData.responseData),p.onChunk(C(G,!1))}else H.resultType==="segment-created"&&p.onChunk(C(H.resultData,!1));m.debug("SF","Segment request ended with success",_),p.onAllChunksReceived(),H.resultType!=="segment-created"?(k=H.resultData,K()):k=null,h.isCancelled()||(X=i.onRequestEnd)==null||X.call(i,{id:R}),h.deregister(B)}catch(H){throw h.deregister(B),k=null,H instanceof we?(m.debug("SF","Segment request aborted",_),H):(m.debug("SF","Segment request failed",_),(W=i.onRequestEnd)==null||W.call(i,{id:R}),mt(H))}function B(){var H;k===void 0&&(m.debug("SF","Segment request cancelled",_),k=null,(H=i.onRequestEnd)==null||H.call(i,{id:R}))}function A(H){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(f),u(H,L,s,h,F)}function C(H,G){x.push(!1);let ie=x.length-1;return function(fe){let Re={data:H,isChunked:G};try{let ge=c(Re,L,fe);return x[ie]||(P=P!==void 0&&ge.segmentType==="media"&&ge.chunkInfos!==null&&ge.chunkInfos.duration!==void 0?P+ge.chunkInfos.duration:void 0,x[ie]=!0,K()),ge}catch(ge){throw Me(ge,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function N(H){p.onRetry(mt(H))}function K(){var H;M||!E(k)&&k.size!==void 0&&k.requestDuration!==void 0&&x.length>0&&x.every(G=>G)&&(M=!0,(H=i.onMetrics)==null||H.call(i,{size:k.size,requestDuration:k.requestDuration,content:f,segmentDuration:P}))}}}function Rf({maxRetry:n,lowLatencyMode:e,requestTimeout:t,connectionTimeout:r}){let{DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:i,DEFAULT_REQUEST_TIMEOUT:o,DEFAULT_CONNECTION_TIMEOUT:a,INITIAL_BACKOFF_DELAY_BASE:s,MAX_BACKOFF_DELAY_BASE:d}=O.getCurrent();return{maxRetry:n!=null?n:i,baseDelay:e?s.LOW_LATENCY:s.REGULAR,maxDelay:e?d.LOW_LATENCY:d.REGULAR,requestTimeout:t===void 0?o:t,connectionTimeout:r===void 0?a:r}}var ci=class extends se{constructor(e,t){super(),this._segmentFetcher=e,this._currentContentInfo=null,this.isMediaSegmentQueueInterrupted=t}getRequestedInitSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.initSegmentRequest)==null?void 0:t.segment)!=null?r:null}getRequestedMediaSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.mediaSegmentRequest)==null?void 0:t.segment)!=null?r:null}resetForContent(e,t){var a;(a=this._currentContentInfo)==null||a.currentCanceller.cancel();let r=new j({initSegment:null,segmentQueue:[]}),i=new U;i.signal.register(()=>{r.finish()});let o={content:e,downloadQueue:r,initSegmentInfoRef:t?new j(void 0):new j(null),currentCanceller:i,initSegmentRequest:null,mediaSegmentRequest:null,mediaSegmentAwaitingInitMetadata:null};return this._currentContentInfo=o,this.isMediaSegmentQueueInterrupted.onUpdate(s=>{s||(m.debug("SF","Media segment can be loaded again, restarting queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o))},{clearSignal:i.signal}),r.onUpdate(s=>{let{segmentQueue:d}=s;if(d.length>0&&d[0].segment.id===o.mediaSegmentAwaitingInitMetadata)return;let u=o.mediaSegmentRequest;if(d.length===0){if(u===null)return;m.debug("SF","no more media segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o);return}else if(u===null){m.debug("SF","Media segments now need to be requested. Starting queue.",{type:e.adaptation.type,queueLength:d.length}),this._restartMediaSegmentDownloadingQueue(o);return}else{let c=d[0];if(u.segment.id!==c.segment.id){m.debug("SF","Next media segment changed, cancelling previous",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o);return}u.priority!==c.priority&&(m.debug("SF","Priority of next media segment changed, updating",{type:e.adaptation.type,prevPriority:u.priority,newPriority:c.priority}),this._segmentFetcher.updatePriority(u.request,c.priority));return}},{emitCurrentValue:!0,clearSignal:i.signal}),r.onUpdate(s=>{var u;let d=o.initSegmentRequest;if(s.initSegment!==null&&d!==null){s.initSegment.priority!==d.priority&&this._segmentFetcher.updatePriority(d.request,s.initSegment.priority);return}else if(((u=s.initSegment)==null?void 0:u.segment.id)===(d==null?void 0:d.segment.id))return;s.initSegment===null&&m.debug("SF","no more init segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartInitSegmentDownloadingQueue(o,s.initSegment)},{emitCurrentValue:!0,clearSignal:i.signal}),r}stop(){var e;(e=this._currentContentInfo)==null||e.currentCanceller.cancel(),this._currentContentInfo=null}_restartMediaSegmentDownloadingQueue(e){e.mediaSegmentRequest!==null&&e.mediaSegmentRequest.canceller.cancel();let{downloadQueue:t,content:r,initSegmentInfoRef:i,currentCanceller:o}=e,a=()=>{var v;if(this.isMediaSegmentQueueInterrupted.getValue()){m.debug("SF","Segment fetching postponed because it cannot stream now.");return}let{segmentQueue:s}=t.getValue(),d=s[0];if(o!==null&&o.isUsed()){e.mediaSegmentRequest=null;return}if(d===void 0){e.mediaSegmentRequest=null,this.trigger("emptyQueue",null);return}let u=new U,c=o===null?te:u.linkToSignal(o.signal),{segment:l,priority:f}=d,p=Y({segment:l,nextSegment:(v=s[1])==null?void 0:v.segment},r),h=!1,I=!1;u.signal.register(()=>{e.mediaSegmentRequest=null,!h&&(e.mediaSegmentAwaitingInitMetadata===l.id&&(e.mediaSegmentAwaitingInitMetadata=null),h=!0,I=!1)});let g=_=>{ne(_.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",Y({},_,{segment:l}))},b=()=>{let _=t.getValue().segmentQueue;if(_.length===0){h=!0,this.trigger("emptyQueue",null);return}else _[0].segment.id===l.id&&_.shift();h=!0,a()},T=this._segmentFetcher.createRequest(p,f,{onRetry:_=>{this.trigger("requestRetry",{segment:l,error:_})},beforeInterrupted(){m.info("SF","segment request interrupted temporarly.",{segmentId:l.id,segmentTime:l.time})},onChunk:_=>{let R=i.getValue();R!==void 0?g(_(R!=null?R:void 0)):(I=!0,i.waitUntilDefined(k=>{g(_(k!=null?k:void 0))},{clearSignal:u.signal}))},onAllChunksReceived:()=>{I?(e.mediaSegmentAwaitingInitMetadata=l.id,i.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,I=!1,this.trigger("fullyLoadedSegment",l)},{clearSignal:u.signal})):this.trigger("fullyLoadedSegment",l)},beforeEnded:()=>{c(),e.mediaSegmentRequest=null,I?i.waitUntilDefined(b,{clearSignal:u.signal}):b()}},u.signal);T.catch(_=>{c(),h||(h=!0,this.stop(),this.trigger("error",_))}),e.mediaSegmentRequest={segment:l,priority:f,request:T,canceller:u}};a()}_restartInitSegmentDownloadingQueue(e,t){let{content:r,initSegmentInfoRef:i}=e;if(e.initSegmentRequest!==null&&e.initSegmentRequest.canceller.cancel(),t===null)return;let o=new U,a=e.currentCanceller===null?te:o.linkToSignal(e.currentCanceller.signal),{segment:s,priority:d}=t,u=Y({segment:s,nextSegment:void 0},r),c=!1,l=this._segmentFetcher.createRequest(u,d,{onRetry:f=>{this.trigger("requestRetry",{segment:s,error:f})},beforeInterrupted:()=>{m.info("SF","init segment request interrupted temporarly.",{segmentId:s.id})},beforeEnded:()=>{a(),e.initSegmentRequest=null,c=!0},onChunk:f=>{var h;let p=f(void 0);ne(p.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",Y({},p,{segment:s})),p.segmentType==="init"&&i.setValue((h=p.initTimescale)!=null?h:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",s)}},o.signal);l.catch(f=>{a(),c||(c=!0,this.stop(),this.trigger("error",f))}),o.signal.register(()=>{e.initSegmentRequest=null,!c&&(c=!0)}),e.initSegmentRequest={segment:s,priority:d,request:l,canceller:o}}};var mi=class{constructor({prioritySteps:e}){if(this._minPendingPriority=null,this._waitingQueue=[],this._pendingTasks=[],this._prioritySteps=e,this._prioritySteps.high>=this._prioritySteps.low)throw new Error("The max high level priority should be given a lowerpriority number than the min low priority.")}create(e,t,r,i){let o;return ct(i,(a,s)=>(o={hasEnded:!1,priority:t,trigger:()=>{if(o.hasEnded)return;let u=()=>{p(),this._endTask(o)},c=h=>{r.beforeEnded(),u(),a(h)},l=h=>{u(),s(h)},f=new U,p=f.linkToSignal(i);o.interrupter=f,f.signal.register(()=>{o.interrupter=null,i.isCancelled()||r.beforeInterrupted()}),this._minPendingPriority=this._minPendingPriority===null?o.priority:Math.min(this._minPendingPriority,o.priority),this._pendingTasks.push(o),o.taskFn(f.signal).then(c).catch(h=>{!i.isCancelled()&&f.isUsed()&&h instanceof we||l(h)})},taskFn:e,interrupter:null},this._canBeStartedNow(o)?(o.trigger(),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()):this._waitingQueue.push(o),()=>this._endTask(o)))}_endTask(e){e.hasEnded=!0;let t=fi(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=fi(e.taskFn,this._pendingTasks);if(r<0)return;this._pendingTasks.splice(r,1),this._pendingTasks.length>0?this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))):this._minPendingPriority=null,this._loopThroughWaitingQueue()}}updatePriority(e,t){let r=fi(e,this._waitingQueue);if(r>=0){let s=this._waitingQueue[r];if(s.priority===t||(s.priority=t,!this._canBeStartedNow(s)))return;this._findAndRunWaitingQueueTask(r),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks();return}let i=fi(e,this._pendingTasks);if(i<0){m.warn("SF","request to update the priority of a non-existent task");return}let o=this._pendingTasks[i];if(o.priority===t)return;let a=o.priority;o.priority=t,this._minPendingPriority===null||t<this._minPendingPriority?this._minPendingPriority=t:this._minPendingPriority===a&&(this._pendingTasks.length===1?this._minPendingPriority=t:this._minPendingPriority=Math.min(...this._pendingTasks.map(s=>s.priority)),this._loopThroughWaitingQueue()),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()}_loopThroughWaitingQueue(){let e=this._waitingQueue.reduce((t,r)=>t===null||t>r.priority?r.priority:t,null);if(!(e===null||this._minPendingPriority!==null&&this._minPendingPriority<e))for(let t=0;t<this._waitingQueue.length;t++){let r=this._minPendingPriority===null?e:Math.min(this._minPendingPriority,e);this._waitingQueue[t].priority<=r&&(this._findAndRunWaitingQueueTask(t),t--)}}_interruptCancellableTasks(){for(let e of this._pendingTasks)if(e.priority>=this._prioritySteps.low)return this._interruptPendingTask(e),this._interruptCancellableTasks()}_findAndRunWaitingQueueTask(e){return e>=this._waitingQueue.length||e<0?(m.warn("SF","Tried to start a non existing task"),!1):(this._waitingQueue.splice(e,1)[0].trigger(),!0)}_interruptPendingTask(e){var r;let t=fi(e.taskFn,this._pendingTasks);if(t<0){m.warn("SF","Interrupting a non-existent pending task. Aborting...");return}this._pendingTasks.splice(t,1),this._waitingQueue.push(e),this._pendingTasks.length===0?this._minPendingPriority=null:this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))),(r=e.interrupter)==null||r.cancel()}_canBeStartedNow(e){return this._minPendingPriority===null||e.priority<=this._minPendingPriority}_isRunningHighPriorityTasks(){return this._minPendingPriority!==null&&this._minPendingPriority<=this._prioritySteps.high}};function fi(n,e){return Ie(e,t=>t.taskFn===n)}var pi=class{constructor(e,t,r,i){let{MIN_CANCELABLE_PRIORITY:o,MAX_HIGH_PRIORITY_LEVEL:a}=O.getCurrent();this._transport=e,this._prioritizer=new mi({prioritySteps:{high:a,low:o}}),this._cdnPrioritizer=t,this._backoffOptions=i,this._cmcdDataBuilder=r}createSegmentQueue(e,t,r){let i=Rf(this._backoffOptions),o=this._transport[e],a=ld({bufferType:e,pipeline:o,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=dd(this._prioritizer,a);return new ci(s,r)}};var cd=pi;function fd(n,e){let{loadThumbnail:t}=n,r=[];return async function(o,a){a.register(T);let s,d=Q(r,({thumbnailContext:R})=>R.period.id===o.period.id&&R.track.id===o.track.id&&R.segment.id===o.segment.id);if(d!==void 0){m.debug("Thumbnails","Requesting same thumbnail than the pending one",{time:o.segment.time}),s=d,s.referenceCount++;let R;try{R=await s.promise}catch(k){throw a.deregister(T),k}return a.deregister(T),R}let{segment:u,track:c}=o,l=bh({}),f;l.connectionTimeout===void 0||l.connectionTimeout<0?f=void 0:f=l.connectionTimeout;let p={timeout:l.requestTimeout<0?void 0:l.requestTimeout,connectionTimeout:f,cmcdPayload:void 0},h=new U,I=b();s={thumbnailContext:o,promise:I,referenceCount:1},r.push(s);let g=()=>{let R=r.indexOf(s);R>=0&&r.splice(R,1)};try{let R=await I;return g(),R}catch(R){throw g(),R}async function b(){m.debug("Thumbnails","Beginning thumbnail request",{time:u.time});let R;try{if(R=await ui(c.cdnMetadata,e,v,Y({onRetry:_},l),h.signal),a.isCancelled())return Promise.reject(a.cancellationError);m.debug("Thumbnails","Thumbnail request ended with success",{time:u.time}),a.deregister(T)}catch(k){throw a.deregister(T),k instanceof we?(m.debug("Thumbnails","Thumbnail request aborted",{time:u.time}),k):(m.debug("Thumbnails","Thumbnail request failed",{time:u.time}),mt(k))}try{return n.parseThumbnail(R.responseData,{thumbnail:u,thumbnailTrack:c})}catch(k){throw Me(k,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}function T(){m.debug("Thumbnails","Thumbnail request cancelled",{time:u.time});let R=r.indexOf(s);R<0||(r[R].referenceCount--,r[R].referenceCount<=0&&(h.cancel(),r.splice(R,1)))}function v(R){return t(R,u,p,a)}function _(R){let k=mt(R);m.warn("Thumbnails","Thumbnail request retry ",{time:u.time},k)}}}function bh({maxRetry:n,requestTimeout:e,connectionTimeout:t}){let{DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:r,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:i,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:o,INITIAL_BACKOFF_DELAY_BASE:a,MAX_BACKOFF_DELAY_BASE:s}=O.getCurrent();return{maxRetry:n!=null?n:r,baseDelay:a.REGULAR,maxDelay:s.REGULAR,requestTimeout:e===void 0?i:e,connectionTimeout:t===void 0?o:t}}var md=fd;var Pn=class{constructor(e){this._array=[],this._sortingFn=e}add(...e){e.sort(this._sortingFn);let t=0;for(let r=0;r<e.length;r++){let i=e[r],o=!1;for(;!o&&t<this._array.length;)this._sortingFn(i,this._array[t])<0?(this._array.splice(t,0,i),o=!0):t++;o||this._array.push(i)}}length(){return this._array.length}get(e){if(e<0||e>=this._array.length)throw new Error("Invalid index.");return this._array[e]}toArray(){return this._array.slice()}findFirst(e){return Q(this._array,e)}has(e){return $(this._array,e)}removeElement(e){let t=this._array.indexOf(e);if(t>=0)return this._array.splice(t,1),t}head(){return this._array[0]}last(){return this._array[this._array.length-1]}shift(){return this._array.shift()}pop(){return this._array.pop()}};var gi=class extends se{constructor(e,t,r){super(),this._canceller=new U,this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new pd(e);this._maximumPositionCalculator=i;let o=this._canceller.signal;It(()=>{t.listen(({position:a})=>{let s=a.getWanted();if(s<e.getMinimumSafePosition()){let d=new re("MEDIA_TIME_BEFORE_MANIFEST","The current position is behind the earliest time announced in the Manifest.");this.trigger("warning",d)}else if(s>i.getMaximumAvailablePosition()){let d=new re("MEDIA_TIME_AFTER_MANIFEST","The current position is after the latest time announced in the Manifest.");this.trigger("warning",d)}},{includeLastObservation:!1,clearSignal:o})}),e.addEventListener("manifestUpdate",()=>{this.trigger("endingPositionChange",this._getManifestEndTime()),!o.isCancelled()&&this._checkEndOfStream()},o)}getCurrentEndingTime(){return this._getManifestEndTime()}onAdaptationChange(e,t,r){if(this._manifest.isLastPeriodKnown){let i=this._manifest.periods[this._manifest.periods.length-1];if(t.id===(i==null?void 0:i.id)&&(e==="audio"||e==="video")){e==="audio"?this._maximumPositionCalculator.updateLastAudioAdaptation(r):this._maximumPositionCalculator.updateLastVideoAdaptation(r);let o=this._maximumPositionCalculator.getEndingPosition(),a=o!==void 0?{isEnd:!0,endingPosition:o}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()};this.trigger("endingPositionChange",a)}}this._canceller.isUsed()||r===null&&this._addActivelyLoadedPeriod(t,e)}onRepresentationChange(e,t){this._addActivelyLoadedPeriod(t,e)}onPeriodCleared(e,t){this._removeActivelyLoadedPeriod(t,e)}onLastSegmentFinishedLoading(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod||(t.hasFinishedLoadingLastPeriod=!0,this._checkEndOfStream())}onLastSegmentLoadingResume(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod&&(t.hasFinishedLoadingLastPeriod=!1,this._checkEndOfStream())}dispose(){this.removeEventListener(),this._canceller.cancel()}_addActivelyLoadedPeriod(e,t){let r=this._lazilyCreateActiveStreamInfo(t);r.activePeriods.has(e)||(r.activePeriods.add(e),this._checkCurrentPeriod())}_removeActivelyLoadedPeriod(e,t){let r=this._activeStreams.get(t);r!==void 0&&r.activePeriods.has(e)&&(r.activePeriods.removeElement(e),this._checkCurrentPeriod())}_checkCurrentPeriod(){if(this._allBufferTypes.length===0)return;let e=this._activeStreams.get(this._allBufferTypes[0]);if(e!==void 0)for(let t of e.activePeriods.toArray()){let r=!0;for(let i of this._allBufferTypes){let o=this._activeStreams.get(i);if(o===void 0)return;if(!o.activePeriods.toArray().some(d=>d.id===t.id)){r=!1;break}}if(r){this._lastCurrentPeriodId!==t.id&&(this._lastCurrentPeriodId=t.id,this.trigger("periodChange",t));return}}}_getManifestEndTime(){let e=this._maximumPositionCalculator.getEndingPosition();return e!==void 0?{isEnd:!0,endingPosition:e}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()}}_lazilyCreateActiveStreamInfo(e){let t=this._activeStreams.get(e);return t===void 0&&(t={activePeriods:new Pn((r,i)=>r.start-i.start),hasFinishedLoadingLastPeriod:!1},this._activeStreams.set(e,t)),t}_checkEndOfStream(){if(!this._manifest.isLastPeriodKnown)return;this._allBufferTypes.every(t=>{let r=this._activeStreams.get(t);return r!==void 0&&r.hasFinishedLoadingLastPeriod})?this.trigger("endOfStream",null):this.trigger("resumeStream",null)}},pd=class{constructor(e){this._manifest=e,this._lastAudioAdaptation=void 0,this._lastVideoAdaptation=void 0}updateLastAudioAdaptation(e){this._lastAudioAdaptation=e}updateLastVideoAdaptation(e){this._lastVideoAdaptation=e}getMaximumAvailablePosition(){if(this._manifest.isDynamic)return this._manifest.getMaximumSafePosition();if(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)return this._manifest.getMaximumSafePosition();if(this._lastAudioAdaptation===null){if(this._lastVideoAdaptation===null)return this._manifest.getMaximumSafePosition();{let e=la(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=la(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=la(this._lastAudioAdaptation),t=la(this._lastVideoAdaptation);return typeof e!="number"||typeof t!="number"?this._manifest.getMaximumSafePosition():Math.min(e,t)}}getEndingPosition(){var e,t;if(!this._manifest.isDynamic)return this.getMaximumAvailablePosition();if(!(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)){if(this._lastAudioAdaptation===null)return this._lastVideoAdaptation===null?void 0:(e=ca(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=ca(this._lastAudioAdaptation))!=null?t:void 0;{let r=ca(this._lastAudioAdaptation),i=ca(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function la(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getLastAvailablePosition();if(o===void 0)return;o!==null&&(t=E(t)?o:Math.min(t,o))}return t}function ca(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getEnd();if(o===void 0)return;o!==null&&(t=E(t)?o:Math.min(t,o))}return t}function gd(n,e,t,r,i,o){o.register(()=>{e.interruptDurationSetting()});let a=new gi(n,t,r.getBufferTypes());o.register(()=>{a.dispose()}),a.addEventListener("warning",d=>i.onWarning(d)),a.addEventListener("periodChange",d=>i.onPeriodChanged(d)),a.addEventListener("endingPositionChange",d=>{e.setDuration(d.endingPosition,d.isEnd)}),a.addEventListener("endOfStream",()=>{m.debug("mse","Start applying end-of-stream order."),e.maintainEndOfStream()}),a.addEventListener("resumeStream",()=>{e.stopEndOfStream()});let s=a.getCurrentEndingTime();return e.setDuration(s.endingPosition,s.isEnd),a}var kf=6,hd=4e3,fa=6e3,Sh=6e4,hi=class{constructor(e){this._segmentSinksStore=e,this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=null,this._lastFlushAttempt=null,this._lastSegmentInfo={audio:[],video:[]}}onNewObservation(e){var g,b;let t=z();if(this._addPositionToHistory(e,t),this._ignoreFreezeUntil!==null&&t<this._ignoreFreezeUntil)return null;this._ignoreFreezeUntil=null;let{UNFREEZING_SEEK_DELAY:r,UNFREEZING_DELTA_POSITION:i,FREEZING_FLUSH_FAILURE_DELAY:o}=O.getCurrent(),{readyState:a,rebuffering:s,freezing:d,fullyLoaded:u}=e,c=e.position.getPolled(),l=Pf(e.bufferGap);if(!(d!==null||a===1&&(l>=kf||u)))return this._decipherabilityFreezeStartingTimestamp=null,null;let p=(b=(g=d==null?void 0:d.timestamp)!=null?g:s==null?void 0:s.timestamp)!=null?b:null;if(m.info("Freeze","Freeze detected",{freezeStart:p,timeFrozen:t-(p!=null?p:t)}),this._lastFlushAttempt!==null&&t-this._lastFlushAttempt.timestamp<o.MAXIMUM&&t-this._lastFlushAttempt.timestamp>=o.MINIMUM&&Math.abs(c-this._lastFlushAttempt.position)<o.POSITION_DELTA){let T=this._getStrategyIfFlushingFails(c);return this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+fa,T}let I=this._checkForDecipherabilityRelatedFreeze(e,t);return I!==null?I:p!==null&&t-p>r?(this._lastFlushAttempt={timestamp:t,position:c+i},m.debug("Freeze","Trying to flush to un-freeze"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+fa,{type:"flush",value:{relativeSeek:i}}):null}_checkForDecipherabilityRelatedFreeze(e,t){let{readyState:r,rebuffering:i,freezing:o,fullyLoaded:a}=e,s=Pf(e.bufferGap),d=i!==null&&t-i.timestamp>hd,{hasUndecipherableData:u,hasEncryptedData:c}=Th(this._segmentSinksStore);if(u===!0)return m.warn("Freeze","we have undecipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+fa,{type:"reload",value:null};let l=o!==null&&t-o.timestamp>hd;return(d||l)&&(s>=kf||a)&&r<=1?this._decipherabilityFreezeStartingTimestamp===null&&(m.debug("Freeze","Start of a potential decipherability freeze detected"),this._decipherabilityFreezeStartingTimestamp=t):this._decipherabilityFreezeStartingTimestamp=null,this._decipherabilityFreezeStartingTimestamp!==null&&z()-this._decipherabilityFreezeStartingTimestamp>hd&&c&&u===!1?(m.warn("Freeze","we are frozen despite only having decipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+fa,{type:"reload",value:null}):null}_getStrategyIfFlushingFails(e){m.warn("Freeze","A recent flush seemed to have no effect on freeze, checking for transitions");let t=[];for(let r of["audio","video"]){let i=this._lastSegmentInfo[r];if(i.length===0)continue;let o=i[i.length-1];if(o.segment===null)continue;let a=o.segment,s;for(let d=i.length-2;d>=0;d--){let u=i[d];if(u.segment===null){s=u;break}else if(u.segment.infos.representation.uniqueId!==a.infos.representation.uniqueId&&o.timestamp-u.timestamp<5e3){s=u;break}else u.segment.start===a.start&&e-u.position<3e3&&(o=u)}if(s===void 0||s.segment===null)m.debug("Freeze","Freeze when beginning to play a content, try avoiding this quality"),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation});else{if(a.infos.period.id!==s.segment.infos.period.id)return m.debug("Freeze","Freeze when switching Period, reloading"),{type:"reload",value:null};a.infos.representation.uniqueId!==s.segment.infos.representation.uniqueId&&(m.warn("Freeze","Freeze when switching Representation, avoiding",{bitrate:a.infos.representation.bitrate}),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation}))}}return t.length>0?{type:"avoid-representations",value:t}:(m.debug("Freeze","Reloading because flush doesn't work"),{type:"reload",value:null})}_addPositionToHistory(e,t){var i,o;let r=e.position.getPolled();for(let a of["audio","video"]){let s=this._segmentSinksStore.getStatus(a);if(s.type==="initialized")for(let c of s.value.getLastKnownInventory())((i=c.bufferedStart)!=null?i:c.start)<=r&&((o=c.bufferedEnd)!=null?o:c.end)>r&&this._lastSegmentInfo[a].push({segment:c,position:r,timestamp:t});else this._lastSegmentInfo[a].push({segment:null,position:r,timestamp:t});if(this._lastSegmentInfo[a].length>100){let c=this._lastSegmentInfo[a].length-100;this._lastSegmentInfo[a].splice(0,c)}let d=t-Sh,u;for(u=0;u<this._lastSegmentInfo[a].length&&!(this._lastSegmentInfo[a][u].timestamp>d);u++);u>0&&this._lastSegmentInfo[a].splice(0,u)}}};function Th(n){let e=!0,t=!0;for(let r of["audio","video"]){let i=n.getStatus(r);if(i.type==="initialized")for(let o of i.value.getLastKnownInventory()){let{representation:a}=o.infos;if(a.decipherable===!1)return{hasUndecipherableData:!0,hasEncryptedData:!0};a.contentProtections!==void 0&&(t=!1,a.decipherable!==!0&&(e=!1))}}return{hasEncryptedData:!t,hasUndecipherableData:e?!1:void 0}}function Pf(n){return n!==void 0&&isFinite(n)?n:0}async function yd(n,e,t,r,i){let o=e.getPeriod(t);if(o===void 0)throw new Error("Wanted Period not found.");let a=Q(o.thumbnailTracks,d=>d.id===r);if(a===void 0)throw new Error("Wanted Period has no thumbnail track.");let s=a.index.getSegments(i,1)[0];if(s===void 0)throw new Error("No thumbnail for the given timestamp");return n({segment:s,track:a,period:o},new U().signal)}function Id(n,e){["video","audio","text"].forEach(t=>{var i;let r=e.getStatus(t);r.type==="initialized"&&r.value.synchronizeInventory((i=n.buffered[t])!=null?i:[])})}function ma({segmentSink:n,playbackObserver:e,maxBufferBehind:t,maxBufferAhead:r},i){let o,a=[];e.listen(d=>{o=d.position.getWanted(),a=d.buffered[n.bufferType],s()},{includeLastObservation:!0,clearSignal:i});function s(){a!==null&&Eh(n,o,a,t.getValue(),r.getValue(),i).catch(d=>{if(i.isCancelled()&&U.isCancellationError(d))return;let u=d instanceof Error?d.message:"Unknown error";m.error("Stream","Could not run BufferGarbageCollector:",u)})}t.onUpdate(s,{clearSignal:i}),r.onUpdate(s,{clearSignal:i}),s()}async function Eh(n,e,t,r,i,o){if(!isFinite(r)&&!isFinite(i))return Promise.resolve();let a=[],{innerRange:s,outerRanges:d}=mc(t,e),u=()=>{if(isFinite(r)){for(let l of d)e-r>=l.end?a.push(l):e>=l.end&&e-r>l.start&&e-r<l.end&&a.push({start:l.start,end:e-r});E(s)||e-r>s.start&&a.push({start:s.start,end:e-r})}},c=()=>{if(isFinite(i)){for(let l of d)e+i<=l.start?a.push(l):e<=l.start&&e+i<l.end&&e+i>l.start&&a.push({start:e+i,end:l.end});E(s)||e+i<s.end&&a.push({start:e+i,end:s.end})}};u(),c();for(let l of a)if(l.start<l.end){if(m.debug("Stream","cleaning range from SegmentSink",{start:l.start,end:l.end}),o.cancellationError!==null)throw o.cancellationError;await n.removeBuffer(l.start,l.end)}}var yi=class{constructor(e,t){this._history=[],this._lifetime=e,this._maxHistoryLength=t}addBufferedSegment(e,t){let r=z();this._history.push({date:r,buffered:t,context:e}),this._cleanHistory(r)}getHistoryFor(e){return this._history.filter(t=>Dt(t.context,e))}_cleanHistory(e){let t=e-this._lifetime,r=0;for(let i of this._history)if(i.date<t)r++;else break;if(r>0&&(this._history=this._history.splice(r)),this._history.length>this._maxHistoryLength){let i=this._history.length-this._maxHistoryLength;this._history=this._history.splice(i)}}};var Ii=class{constructor(){let{BUFFERED_HISTORY_RETENTION_TIME:e,BUFFERED_HISTORY_MAXIMUM_ENTRIES:t}=O.getCurrent();this._inventory=[],this._bufferedHistory=new yi(e,t)}reset(){this._inventory.length=0}synchronizeBuffered(e){var d,u,c,l,f,p,h;let t=this._inventory,r=0,i=t[0],{MINIMUM_SEGMENT_SIZE:o}=O.getCurrent(),a=i==null?void 0:i.infos.adaptation.type;if(m.hasLevel("DEBUG")){let I=e.map(g=>`${g.start}-${g.end}`).join(",");m.debug("SI",`synchronizing ${a!=null?a:"unknown"} buffered ranges:`,I)}let s=e.length;for(let I=0;I<s;I++){if(i===void 0)return;let g=e[I].start,b=e[I].end;if(b-g<o){m.warn("SI","skipped range when synchronizing because it was too small",{t:a,rangeStart:g,rangeEnd:b});continue}let T=r;for(;i!==void 0&&((d=i.bufferedEnd)!=null?d:i.end)-g<o;)i=t[++r];let v=null,_=r-T;if(_>0){let k=t[T+_-1];v={end:(u=k.bufferedEnd)!=null?u:k.end,precizeEnd:k.precizeEnd},m.debug("SI",`${_} segments GCed.`,{t:a});let x=t.splice(T,_);for(let P of x)P.bufferedStart===void 0&&P.bufferedEnd===void 0&&P.status!==2&&this._bufferedHistory.addBufferedSegment(P.infos,null);r=T}if(i===void 0)return;if(b-((c=i.bufferedStart)!=null?c:i.start)>=o){if(_h(i,g,v,a),r===t.length-1){Af(i,b,a);return}i=t[++r];let k=(l=i.bufferedStart)!=null?l:i.start,x=(f=i.bufferedEnd)!=null?f:i.end,P=I<s-1?e[I+1].start:void 0;for(;i!==void 0&&!(b<k||b-k<o&&x-b>=o||P!==void 0&&b-k<x-P);){let M=t[r-1];M.bufferedEnd===void 0&&(i.precizeStart?M.bufferedEnd=i.start:M.infos.segment.complete?M.bufferedEnd=M.end:M.bufferedEnd=i.start,m.debug("SI","calculating buffered end of contiguous segment",{t:a,prevSegmentBufferedEnd:M.bufferedEnd,pse:M.end})),i.bufferedStart=M.bufferedEnd,i=t[++r],i!==void 0&&(k=(p=i.bufferedStart)!=null?p:i.start,x=(h=i.bufferedEnd)!=null?h:i.end)}}let R=t[r-1];R!==void 0&&Af(R,b,a)}if(!E(i)){let{SEGMENT_SYNCHRONIZATION_DELAY:I}=O.getCurrent(),g=z();for(let b=r;b<t.length;b++){let T=t[b];g-T.insertionTs>=I&&(m.debug("SI","A segment at the end has been completely GCed",bt(T.infos)),T.bufferedStart===void 0&&T.bufferedEnd===void 0&&T.status!==2&&this._bufferedHistory.addBufferedSegment(T.infos,null),t.splice(b,1),b--)}}a!==void 0&&m.hasLevel("DEBUG")&&m.debug("SI",`current ${a} inventory timeline:
|
|
2
|
-
`+
|
|
3
|
-
[${d.letter}] P: ${d.periodId} || R: ${d.representationId}(${(u=d.bitrate)!=null?u:"unknown bitrate"})`}),s}function er(n,e){for(let t=0;t<n.length;t++)if(n[t].infos.period.start>=e.start)return t>0?n[t-1]:null;return n.length>0?n[n.length-1]:null}function tr(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var Mf=Ii;var nr=class{constructor(){this._segmentInventory=new Mf}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var bi=class extends nr{constructor(e,t,r){super(),m.info("Stream","calling `mediaSource.addSourceBuffer`",{codec:t});let i=r.addSourceBuffer(e,t);this.bufferType=e,this._sourceBuffer=i,this._lastInitSegmentUniqueId=null,this.codec=t,this._initSegmentsMap=new Map,this._pendingOperations=[]}declareInitSegment(e,t){xf(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){xf(e.data.chunk),m.debug("Stream","queuing push order",bt(e.inventoryInfos));let t=this._getActualDataToPush(e.data);t.length===0&&t.push(new Uint8Array);let r=Promise.all(t.map(a=>{let{codec:s,timestampOffset:d,appendWindow:u}=e.data;return m.debug("Stream","now pushing",bt(e.inventoryInfos)),this._sourceBuffer.appendBuffer(a,{codec:s,timestampOffset:d,appendWindow:u})}));this._addToOperationQueue(r,{type:0,value:e});let i;try{i=await r}catch(a){throw this._segmentInventory.insertChunk(e.inventoryInfos,!1,z()),a}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,z());let o=i[i.length-1];return this._segmentInventory.synchronizeBuffered(o),o}async removeBuffer(e,t){m.debug("Stream","queuing remove order",{bufferType:this.bufferType,start:e,end:t});let r=this._sourceBuffer.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){try{m.debug("Stream","Calling `dispose` on the SourceBufferInterface"),this._sourceBuffer.dispose()}catch(e){m.debug("Stream",`Failed to dispose a ${this.bufferType} SourceBufferInterface:`,e instanceof Error?e:"Unknown Error")}}_getActualDataToPush(e){let t=[];if(e.initSegmentUniqueId!==null&&!this._isLastInitSegment(e.initSegmentUniqueId)){let r=this._initSegmentsMap.get(e.initSegmentUniqueId);if(r===void 0)throw new Error("Invalid initialization segment uniqueId");let i=new ArrayBuffer(r.byteLength),o=new Uint8Array(i);o.set(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer)),r=o,t.push(r),this._lastInitSegmentUniqueId=e.initSegmentUniqueId}return e.chunk!==null&&t.push(e.chunk),t}_isLastInitSegment(e){return this._lastInitSegmentUniqueId===null?!1:this._lastInitSegmentUniqueId===e}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function xf(n){if(y.CURRENT_ENV!==y.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var ga=bi;var Si=class extends nr{constructor(e){m.debug("Stream","Creating TextSegmentSink"),super(),this.bufferType="text",this._sender=e,this._pendingOperations=[],this._sender.reset()}declareInitSegment(e){m.warn("Stream","Declaring initialization segment for Text SegmentSink",{uniqueId:e})}freeInitSegment(e){m.warn("Stream","Freeing initialization segment for Text SegmentSink",{uniqueId:e})}async pushChunk(e){let{data:t}=e;kh(t.chunk);let r=this._sender.pushTextData(ue(ae({},t),{chunk:t.chunk}));this._addToOperationQueue(r,{type:0,value:e});let i=await r;return e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,z()),this._segmentInventory.synchronizeBuffered(i),i}async removeBuffer(e,t){let r=this._sender.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){m.debug("Stream","Disposing TextSegmentSink"),this._sender.reset()}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function kh(n){if(y.CURRENT_ENV!==y.PRODUCTION){if(typeof n!="object"||n===null||E(n.data))throw new Error("Invalid format given to a TextSegmentSink");if(!Ph(n))throw new Error("Invalid format given to a TextSegmentSink");if(typeof n.data!="string"&&typeof n.data.byteLength!="number")throw new Error("Invalid format given to a TextSegmentSink")}}function Ph(n){return!(typeof n!="object"||n===null||typeof n.type!="string"||n.language!==void 0&&typeof n.language!="string"||n.initTimescale!==null&&typeof n.initTimescale!="number"||n.start!==void 0&&typeof n.start!="number"||n.end!==void 0&&typeof n.end!="number")}y.CURRENT_ENV===y.DEV&&(Ch=function(e){function t(r){}});var Ch;var wf=Si;var Ah=["audio","video","text"],Ti=class n{static isNative(e){return Of(e)}constructor(e,t,r){this._mediaSource=e,this._textInterface=r,this._hasVideo=t,this._initializedSegmentSinks={},this._onNativeBufferAddedOrDisabled=[]}getBufferTypes(){let e=this.getNativeBufferTypes();return this._textInterface!==null&&e.push("text"),e}getNativeBufferTypes(){return this._hasVideo?["video","audio"]:["audio"]}getStatus(e){let t=this._initializedSegmentSinks[e];return t===void 0?{type:"uninitialized"}:t===null?{type:"disabled"}:{type:"initialized",value:t}}waitForUsableBuffers(e){return this._areNativeBuffersUsable()?Promise.resolve():ct(e,t=>{let r=te,i=()=>{let o=this._onNativeBufferAddedOrDisabled.indexOf(r);o>=0&&this._onNativeBufferAddedOrDisabled.splice(o,1)};return r=()=>{this._areNativeBuffersUsable()&&(i(),t())},this._onNativeBufferAddedOrDisabled.push(r),i})}disableSegmentSink(e){let t=this._initializedSegmentSinks[e];if(t===null){m.warn("Stream",`The ${e} SegmentSink was already disabled.`);return}if(t!==void 0)throw new Error("Cannot disable an active SegmentSink.");this._initializedSegmentSinks[e]=null,n.isNative(e)&&(this._onNativeBufferAddedOrDisabled.slice().forEach(r=>r()),ne(this._onNativeBufferAddedOrDisabled.length===0))}createSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(Of(e)){if(!E(r))return r instanceof ga&&r.codec!==t?m.warn("Stream","Reusing native SegmentSink with codec",r.codec,"for codec",t):m.info("Stream","Reusing native SegmentSink with codec",t),r;m.info("Stream","Adding native SegmentSink with codec",t);let o=e==="audio"?"audio":"video",a=new ga(o,t,this._mediaSource);return this._initializedSegmentSinks[e]=a,this._onNativeBufferAddedOrDisabled.slice().forEach(s=>s()),ne(this._onNativeBufferAddedOrDisabled.length===0),a}if(!E(r))return m.info("Stream","Reusing a previous custom SegmentSink",{bufferType:e}),r;let i;if(e==="text"){if(m.info("Stream","Creating a new text SegmentSink"),this._textInterface===null)throw new Error("HTML Text track feature not activated");return i=new wf(this._textInterface),this._initializedSegmentSinks.text=i,i}throw m.error("Stream","Unknown buffer type:",{bufferType:e}),new re("BUFFER_TYPE_UNKNOWN","The player wants to create a SegmentSink of an unknown type.")}disposeSegmentSink(e){let t=this._initializedSegmentSinks[e];if(E(t)){m.warn("Stream","Trying to dispose a SegmentSink that does not exist",{bufferType:e});return}m.info("Stream","Aborting SegmentSink",{bufferType:e}),t.dispose(),delete this._initializedSegmentSinks[e]}disposeAll(){Ah.forEach(e=>{this.getStatus(e).type==="initialized"&&this.disposeSegmentSink(e)})}_areNativeBuffersUsable(){let e=this.getNativeBufferTypes();return!(e.some(i=>this._initializedSegmentSinks[i]===void 0)||e.every(i=>this._initializedSegmentSinks[i]===null))}createSegmentSinkMetricsForType(e){var i,o;let t=(i=this._initializedSegmentSinks[e])==null?void 0:i.getLastKnownInventory(),r;if(t!==void 0){r=0;for(let a of t){if(a.chunkSize===void 0||r===void 0){r=void 0;break}r+=a.chunkSize}}return{bufferType:e,sizeEstimate:r,codec:(o=this._initializedSegmentSinks[e])==null?void 0:o.codec,segmentInventory:t==null?void 0:t.map(a=>ue(ae({},a),{infos:Mh(a.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function Of(n){return n==="audio"||n==="video"}function Mh(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var on=Ti;var Ei=class{constructor(e){this._weakMap=new WeakMap,this._fn=e}get(e){let t=this._weakMap.get(e);if(t===void 0){let r=this._fn(e);return this._weakMap.set(e,r),r}else return t}destroy(e){this._weakMap.delete(e)}};function Sd(n,e,t,r,i){let{period:o,adaptation:a,representation:s}=n,d=xh(i,e);if(d===null){if(t===null){if(r&&o.end!==void 0&&e.end>=o.end)return{start:void 0,end:null};let l=s.index.checkDiscontinuity(e.start);if(l!==null)return{start:void 0,end:l}}return null}let u=i[d];if(u.bufferedStart!==void 0&&u.bufferedStart>e.start&&(t===null||u.infos.segment.end<=t)){let l=u.bufferedStart;return!r&&s.index.awaitSegmentBetween(e.start,l)!==!1?null:(m.debug("Stream","current discontinuity encountered",{bufferType:a.type,nextSegmentTime:u.bufferedStart,checkStartTime:e.start}),{start:void 0,end:l})}let c=wh(i,e,d+1);if(c!==null){let l=i[c-1],f=i[c];if(t===null||f.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(l.infos.segment.end,f.infos.segment.time)!==!1)return null;let p=l.bufferedEnd,h=f.bufferedStart;return m.debug("Stream","future discontinuity encountered",{bufferType:a.type,discontinuityStart:p,discontinuityEnd:h}),{start:p,end:h}}}if(t===null){if(r&&o.end!==void 0){if(e.end<o.end)return null;let l=Oh(i,o.end);if(l!==null){let f=i[l];if(f.bufferedEnd!==void 0&&f.bufferedEnd<o.end)return m.debug("Stream","discontinuity encountered at the end of the current period",{bufferType:a.type,segmentsEndTimeFromPeriod:f.bufferedEnd,periodEnd:o.end}),{start:f.bufferedEnd,end:null}}}if(o.end!==void 0&&e.end>=o.end)return null;for(let l=i.length-1;l>=0;l--){let f=i[l];if(f.bufferedStart===void 0)break;if(f.bufferedStart<e.end){if(f.bufferedEnd!==void 0&&f.bufferedEnd<e.end){let p=s.index.checkDiscontinuity(e.end);if(p!==null)return{start:f.bufferedEnd,end:p}}return null}}}return null}function xh(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.bufferedStart===void 0||r.bufferedEnd===void 0||r.bufferedStart>=e.end)return null;if(r.bufferedEnd>e.start)return t}return null}function wh(n,e,t){if(t<=0)return m.error("Stream","Asked to check a discontinuity before the first chunk."),null;for(let r=t;r<n.length;r++){let i=n[r],o=n[r-1];if(i.bufferedStart===void 0||o.bufferedEnd===void 0||i.bufferedStart>=e.end)return null;if(i.bufferedStart-o.bufferedEnd>0)return r}return null}function Oh(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.bufferedStart===void 0)return null;if(r.bufferedStart<e)return t}return null}function Td({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:o,segmentsBeingPushed:a,maxBufferSize:s}){let{adaptation:d,representation:u}=e,c=Dh(n,a,s),l=u.index.getSegments(o.start,o.end-o.start),f=n.filter(R=>!Df(R.infos,e,t,r)),p=Vh(f,o,i),{MINIMUM_SEGMENT_SIZE:h,MIN_BUFFER_AHEAD:I}=O.getCurrent(),g=!1,b=Math.min(1/60,h),T=!1,v=[];return{segmentsToLoad:l.filter(R=>{let k=Y({segment:R},e);if(a.length>0&&a.some(B=>Dt(k,B)))return!1;let{duration:x,time:P,end:M}=R;if(R.isInit)return!0;if(g)return v.push(R),!1;if(R.complete&&x<h||a.length>0&&a.some(B=>{if(B.period.id!==e.period.id||B.adaptation.id!==e.adaptation.id)return!1;let{segment:A}=B;if(A.time-b>P)return!1;if(A.complete){if(A.end+b<M)return!1}else if(Math.abs(P-A.time)>P)return!1;return!Df(B,k,t,r)}))return!1;for(let D of p){let B=D.infos.period.id===e.period.id;if(D.status===1&&B){let A=D.infos.segment;if(P-A.time>-b){if(A.complete){if(A.end-M>-b)return!1}else if(Math.abs(P-A.time)<b)return!1}}}let L=x*e.representation.bitrate;if(c-L<0&&(T=!0,P>o.start+I))return g=!0,v.push(R),!1;let F=i(k);if(F.length>1){let D=F[F.length-1],B=F[F.length-2];if(D.buffered===null&&B.buffered===null)return m.warn("Stream","Segment GCed multiple times in a row, ignoring it.","If this happens a lot and lead to unpleasant experience, please check your device's available memory. If it's low when this message is emitted, you might want to update the RxPlayer's settings (`maxBufferAhead`, `maxVideoBufferSize` etc.) so less memory is used by regular media data buffering.",{bufferType:d.type,representationId:u.id,segmentTime:R.time}),!1}for(let D=0;D<p.length;D++){let B=p[D];if(B.end+b>P){let A=B.start>P+b||Lh(p,D).end<M-b;return A&&(c-=L),A}}return c-=L,!0}),segmentsOnHold:v,isBufferFull:T}}function Dh(n,e,t){let r=t*8e3;return r-=e.reduce((i,o)=>{let{bitrate:a}=o.representation,{duration:s}=o.segment;return i+a*s},0),n.reduce((i,o)=>o.chunkSize!==void 0?i-o.chunkSize*8:i,r)}function Lh(n,e){let t=e+1,{MINIMUM_SEGMENT_SIZE:r}=O.getCurrent(),i=Math.min(1/60,r);for(;t<n.length-1&&n[t-1].end+i>n[t].start;)t++;return t--,n[t]}function Df(n,e,t,r){let{CONTENT_REPLACEMENT_PADDING:i}=O.getCurrent();if(n.period.id!==e.period.id)return!1;let{segment:o}=n;return o.time<t+i?!1:n.adaptation.id!==e.adaptation.id?!0:Nh(n.representation,e.representation,r)}function Nh(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=O.getCurrent();if(t===void 0){let o=r*i;return e.bitrate>o}return r<t&&e.bitrate>r}function Uh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=O.getCurrent();return n.bufferedStart===void 0||e!==null&&e.bufferedEnd!==void 0&&n.bufferedStart-e.bufferedEnd<.1?!1:t<n.bufferedStart&&n.bufferedStart-n.start>r?(m.info("Stream","The start of the wanted segment has been garbage collected",{segmentStart:n.start,currentStartInBuffer:n.bufferedStart}),!0):!1}function Bh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=O.getCurrent();return n.bufferedEnd===void 0||e!==null&&e.bufferedStart!==void 0&&e.bufferedStart-n.bufferedEnd<.1?!1:t>n.bufferedEnd&&n.end-n.bufferedEnd>r?(m.info("Stream","The end of the wanted segment has been garbage collected",{segmentEnd:n.end,currentEndInBuffer:n.bufferedEnd}),!0):!1}function Fh(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.start;if(e!==void 0&&r!==void 0&&e-r>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.start;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function Kh(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.end;if(e!==void 0&&r!==void 0&&r-e>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.end;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function Vh(n,e,t){return n.filter((r,i,o)=>{let a=i===0?null:o[i-1],s=i>=o.length-1?null:o[i+1],d=null;if(Uh(r,a,e.start)){if(d=t(r.infos),Fh(d,r.bufferedStart))return!1;m.debug("Stream","skipping segment gc-ed at the start",{segmentStart:r.start,currentStartInBuffer:r.bufferedStart})}if(Bh(r,s,e.end)){if(d=d!=null?d:t(r.infos),Kh(d,r.bufferedEnd))return!1;m.debug("Stream","skipping segment gc-ed at the end",{segmentEnd:r.end,currentEndInBuffer:r.bufferedEnd})}return!0})}function _i(n,e){let t=n-e,{SEGMENT_PRIORITIES_STEPS:r}=O.getCurrent();for(let i=0;i<r.length;i++)if(t<r[i])return i;return r.length}function Ed(n,e,t,r,i,o,a){var P,M,L;let{representation:s}=n,d=(M=(P=t.getIsPaused())!=null?P:t.getReference().getValue().paused.pending)!=null?M:t.getReference().getValue().paused.last,u=(L=t.getPlaybackRate())!=null?L:t.getReference().getValue().speed,c=e;(d===void 0||u===void 0||d||u<=0)&&(c-=.1);let l=zh(n,c,i),f=s.index.shouldRefresh(l.start,l.end),p=a.getPendingOperations().filter(F=>F.type===2).map(F=>F.value),h=a.getLastKnownInventory(),I=t.getCurrentTime();I===void 0&&(I=t.getReference().getValue().position.getWanted());let g=a.getSegmentHistory.bind(a),{segmentsToLoad:b,segmentsOnHold:T,isBufferFull:v}=Td({content:n,bufferedSegments:h,currentPlaybackTime:I,fastSwitchThreshold:r,getBufferedHistory:g,neededRange:l,segmentsBeingPushed:p,maxBufferSize:o}),_=b.map(F=>({priority:_i(F.time,c),segment:F})),R=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&l.hasReachedPeriodEnd&&_.length===0&&T.length===0,k=null;return p.length>0&&(k=Math.min(...p.map(F=>F.segment.time))),T.length>0&&(k=k!==null?Math.min(k,T[0].time):T[0].time),_.length>0&&(k=k!==null?Math.min(k,_[0].segment.time):_[0].segment.time),{imminentDiscontinuity:Sd(n,l,k,R,h),hasFinishedLoading:R,neededSegments:_,isBufferFull:v,shouldRefreshManifest:f}}function zh(n,e,t){var l;let r,{manifest:i,period:o,representation:a}=n,s=a.index.getLastAvailablePosition(),d=a.index;!E(s)&&on.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&Wh(i,o,e)?r=s-1:r=e-.1;let u=r+t,c;return!a.index.isInitialized()||a.index.isStillAwaitingFutureSegments()||o.end===void 0?c=!1:s===void 0?c=u>=o.end:s===null?c=!0:c=u>=s,{start:Math.max(r,o.start),end:Math.min(u,(l=o.end)!=null?l:1/0),hasReachedPeriodEnd:c}}function Wh(n,e,t){var i;let r=n.getPeriodAfter(e);return e.containsTime(t,r)&&n.isLastPeriodKnown&&e.id===((i=n.periods[n.periods.length-1])==null?void 0:i.id)}async function vi(n,e,t,r,i){try{return await e.pushChunk(t)}catch(o){if(i.isCancelled()&&o instanceof we)throw o;if(!(o instanceof lt)||!o.isBufferFull){let d=o instanceof Error?o.toString():"An unknown error happened when pushing content";throw new re("BUFFER_APPEND_ERROR",d,{tracks:[Tn(t.inventoryInfos.adaptation)]})}let{position:a}=n.getReference().getValue(),s=a.getWanted();try{m.warn("Stream","Running garbage collector");let d=Math.max(s-5,0),u=s+r.getValue()+12;if(d>0&&await e.removeBuffer(0,d),u<Number.MAX_VALUE&&await e.removeBuffer(u,Number.MAX_VALUE),await En(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof we)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new re("BUFFER_FULL_ERROR",u,{tracks:[Tn(t.inventoryInfos.adaptation)]})}}}async function _d({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:o},a){let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=Y({segment:r,chunkSize:void 0,start:0,end:0},e),c=await vi(n,i,{data:d,inventoryInfos:u},o,a);return{content:e,segment:r,buffered:c}}async function vd({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:o,segmentSink:a},s){var k,x;if(i.chunkData===null)return null;let{chunkData:d,chunkInfos:u,chunkOffset:c,chunkSize:l,appendWindow:f}=i,p=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:h}=O.getCurrent(),I=[f[0]!==void 0?Math.max(0,f[0]-h.START):void 0,f[1]!==void 0?f[1]+h.END:void 0],g={initSegmentUniqueId:r,chunk:d,timestampOffset:c,appendWindow:I,codec:p},b=(k=u==null?void 0:u.time)!=null?k:o.time,T=(x=u==null?void 0:u.duration)!=null?x:o.duration,v=b+T;I[0]!==void 0&&(b=Math.max(b,I[0])),I[1]!==void 0&&(v=Math.min(v,I[1]));let _=Y({segment:o,chunkSize:l,start:b,end:v},t),R=await vi(n,a,{data:g,inventoryInfos:_},e,s);return{content:t,segment:o,buffered:R}}function Rd({content:n,options:e,playbackObserver:t,segmentSink:r,segmentQueue:i,terminate:o},a,s){m.debug("Stream","Creating RepresentationStream",{periodStart:n.period.start,bufferType:n.adaptation.type,adaptationId:n.adaptation.id,representationBitrate:n.representation.bitrate,mimeType:n.representation.getMimeTypeString()});let{period:d,adaptation:u,representation:c}=n,{bufferGoal:l,maxBufferSize:f,drmSystemId:p,fastSwitchThreshold:h}=e,I=u.type,g=new U;g.linkToSignal(s);let b={segment:c.index.getInitSegment(),uniqueId:null,isLoaded:!1};g.signal.register(()=>{b.uniqueId!==null&&r.freeInitSegment(b.uniqueId)});let T=b.segment!==null;T||(b.isLoaded=!0);let v=!1;if(p!==void 0){let P=c.getEncryptionData(p);if(P.length>0&&P.every(M=>M.keyIds!==void 0)&&(v=!0,a.encryptionDataEncountered(P.map(M=>Y({content:n},M))),g.isUsed()))return}i.addEventListener("error",P=>{g.signal.isCancelled()||(g.cancel(),a.error(P))}),i.addEventListener("parsedInitSegment",k,g.signal),i.addEventListener("parsedMediaSegment",k,g.signal),i.addEventListener("emptyQueue",R,g.signal),i.addEventListener("requestRetry",P=>{if(a.warning(P.error),g.signal.isCancelled())return;let M=P.segment,{index:L}=c;L.isSegmentStillAvailable(M)===!1?R():L.canBeOutOfSyncError(P.error,M)&&a.manifestMightBeOufOfSync()},g.signal),i.addEventListener("fullyLoadedSegment",P=>{r.signalSegmentComplete(Y({segment:P},n)).catch(x)},g.signal);let _=i.resetForContent(n,T);g.signal.register(()=>{i.stop()}),t.listen(R,{includeLastObservation:!1,clearSignal:g.signal}),n.manifest.addEventListener("manifestUpdate",R,g.signal),l.onUpdate(R,{emitCurrentValue:!1,clearSignal:g.signal}),f.onUpdate(R,{emitCurrentValue:!1,clearSignal:g.signal}),o.onUpdate(R,{emitCurrentValue:!1,clearSignal:g.signal}),R();return;function R(){if(g.isUsed())return;let P=t.getReference().getValue(),M=P.position.getWanted(),L=Ed(n,M,t,h.getValue(),l.getValue(),f.getValue(),r),{neededSegments:F}=L,D=null;if(c.index.isInitialized()){if(F.length>0&&!b.isLoaded&&b.segment!==null){let C=F[0].priority;D={segment:b.segment,priority:C}}}else if(b.segment===null)m.warn("Stream","Uninitialized index without an initialization segment",{bufferType:I,representationBitrate:n.representation.bitrate});else if(b.isLoaded)m.warn("Stream","Uninitialized index with an already loaded initialization segment",{bufferType:I,representationBitrate:n.representation.bitrate});else{let C=P.position.getWanted();D={segment:b.segment,priority:_i(d.start,C)}}let B=o.getValue();if(B===null)_.setValue({initSegment:D,segmentQueue:F});else if(B.urgent){m.debug("Stream","Urgent switch, terminate now.",{bufferType:I,representationBitrate:n.representation.bitrate}),_.setValue({initSegment:null,segmentQueue:[]}),_.finish(),g.cancel(),a.terminating();return}else{let C=F[0],N=i.getRequestedInitSegment(),K=i.getRequestedMediaSegment(),q=K===null||C===void 0||K.id!==C.segment.id?[]:[C],X=N===null?null:D;if(_.setValue({initSegment:X,segmentQueue:q}),q.length===0&&X===null){m.debug("Stream","No request left, terminate",{bufferType:I,representationBitrate:n.representation.bitrate}),_.finish(),g.cancel(),a.terminating();return}}if(a.streamStatusUpdate({period:d,position:P.position.getWanted(),bufferType:I,imminentDiscontinuity:L.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:L.hasFinishedLoading,neededSegments:L.neededSegments}),g.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:A}=O.getCurrent();if(L.isBufferFull){let C=Math.max(0,M-A);C>0&&r.removeBuffer(0,C).catch(x)}L.shouldRefreshManifest&&a.needsManifestRefresh()}function k(P){for(let M of P.protectionData)c.addProtectionData(M.initDataType,M.keyId,M.initData);if(!v){let M=c.getAllEncryptionData();M.length>0&&(a.encryptionDataEncountered(M.map(L=>Y({content:n},L))),v=!0)}if(P.segmentType==="init"){if(!c.index.isInitialized()&&P.segmentList!==void 0&&c.index.initialize(P.segmentList),b.isLoaded=!0,P.initializationData!==null){let M=c.uniqueId;b.uniqueId=M,r.declareInitSegment(M,P.initializationData),_d({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:M,segment:P.segment,segmentData:P.initializationData,segmentSink:r},g.signal).then(L=>{L!==null&&a.addedSegment(L)}).catch(x)}R();return}else{let{inbandEvents:M,predictedSegments:L,needsManifestRefresh:F}=P;if(L!==void 0&&c.index.addPredictedSegments(L,P.segment),F===!0&&(a.needsManifestRefresh(),g.isUsed())||M!==void 0&&M.length>0&&(a.inbandEvent(M),g.isUsed()))return;let D=b.uniqueId;vd({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:D,parsedSegment:P,segment:P.segment,segmentSink:r},g.signal).then(B=>{B!==null&&a.addedSegment(B)}).catch(x)}}function x(P){g.isUsed()&&P instanceof we||(m.warn("Stream","Received fatal buffer error",{bufferType:I,representationBitrate:n.representation.bitrate},P instanceof Error?P:null),g.cancel(),a.error(P))}}var Lf=Rd;function kd(n,e,t,r,i){var f,p,h,I;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let o=r.getLastKnownInventory(),a=[];for(let g of o)g.infos.period.id===n.id&&(g.infos.adaptation.id!==e.id||!$(t.representationIds,g.infos.representation.id))&&vt(a,{start:(f=g.bufferedStart)!=null?f:g.start,end:(p=g.bufferedEnd)!=null?p:g.end});let s=r.getPendingOperations();for(let g of s)if(g.type===0){let b=g.value.inventoryInfos;if(b.period.id===n.id&&(b.adaptation.id!==e.id||!$(t.representationIds,b.representation.id))){let T=b.segment.time,v=T+b.segment.duration;vt(a,{start:T,end:v})}}if(a.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let g=i.getReadyState();if(g===void 0||g>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],c=er(o,n);if(c!==null&&(c.bufferedEnd===void 0||n.start-c.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:g}=O.getCurrent(),b=e.type,T=(h=g[b].before)!=null?h:0,v=(I=g[b].after)!=null?I:0,_=i.getCurrentTime();_===void 0&&(_=i.getReference().getValue().position.getPolled()),u.push({start:_-T,end:_+v})}if(n.end!==void 0){let g=tr(o,n);g!==null&&(g.bufferedStart===void 0||g.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let l=ko(a,u);return l.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:l}:{type:"clean-buffer",value:l}}function Pd({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:o,wantedBufferAhead:a,maxVideoBufferSize:s},d,u){let{manifest:c,period:l,adaptation:f}=e,p=new U;p.linkToSignal(u);let h=new Map,I=new j(null,p.signal),g,b=e.representations.getValue().representationIds,T=Nf(e.adaptation.representations,b),v=new j(T,p.signal),{estimates:_,callbacks:R}=r({manifest:c,period:l,adaptation:f},I,v,n,p.signal),k=new j(!1);n.listen(A=>{var N;let C=(N=A.canStream)!=null?N:!0;k.getValue()===C&&(m.debug("Stream","isMediaSegmentQueueInterrupted updated to",!C),k.setValue(!C))},{clearSignal:p.signal});let x=o.createSegmentQueue(f.type,{onRequestBegin:R.requestBegin,onRequestEnd:R.requestEnd,onProgress:R.requestProgress,onMetrics:R.metrics},k),P=new j(0);_.onUpdate(({bitrate:A,knownStableBitrate:C})=>{t.enableFastSwitching&&P.setValueIfChanged(C),!(A===void 0||A===g)&&(g=A,m.debug("Stream",`new ${f.type} bitrate estimate received from ABR`,{bitrate:A}),d.bitrateEstimateChange({type:f.type,bitrate:A}))},{emitCurrentValue:!0,clearSignal:p.signal});let M;e.representations.onUpdate(A=>{M!==void 0&&M.cancel();let C=e.representations.getValue().representationIds,N=Nf(e.adaptation.representations,C);v.setValueIfChanged(N),M=new U,M.linkToSignal(p.signal),L(A,M.signal).catch(K=>{(M==null?void 0:M.isUsed())===!0&&U.isCancellationError(K)||(p.cancel(),d.error(K))})},{clearSignal:p.signal,emitCurrentValue:!0});return;async function L(A,C){let N=kd(l,f,A,i,n);switch(N.type){case"continue":break;case"needs-reload":return It(()=>{n.listen(()=>{if(C.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:K}=O.getCurrent(),q=K.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:q,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:C})});case"flush-buffer":case"clean-buffer":for(let K of N.value)if(await i.removeBuffer(K.start,K.end),C.isCancelled())return;if(N.type==="flush-buffer"&&(d.needsBufferFlush(),C.isCancelled()))return;break;default:ze(N)}F(C)}function F(A){let C=new U;C.linkToSignal(A);let{representation:N}=_.getValue();if(N===null)return;let K=new j(null,C.signal);_.onUpdate(W=>{if(!(W.representation===null||W.representation.id===N.id))return W.urgent?(m.info("Stream","urgent Representation switch",{bufferType:f.type,estimateBitrate:W.bitrate,prevRepresentationBitrate:N.bitrate,newRepresentationBitrate:W.representation.bitrate}),K.setValue({urgent:!0})):(m.info("Stream","slow Representation switch",{bufferType:f.type,estimateBitrate:W.bitrate,prevRepresentationBitrate:N.bitrate,newRepresentationBitrate:W.representation.bitrate}),K.setValue({urgent:!1}))},{clearSignal:C.signal,emitCurrentValue:!0});let q={type:f.type,adaptation:f,period:l,representation:N};if(I.setValue(N),A.isCancelled()||(d.representationChange(q),A.isCancelled()))return;let X={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(W){p.cancel(),d.error(W)},addedSegment(W){R.addedSegment(W)},terminating(){if(!C.isUsed())return C.cancel(),F(A)}};D(N,K,X,A)}function D(A,C,N,K){let q=!1,X=new U;X.linkToSignal(K);let W=gn(a,ie=>B(A,ie),X.signal),H=f.type==="video"?s:new j(1/0);m.info("Stream","changing representation",{bufferType:f.type,representationId:A.id,representationBitrate:A.bitrate});let G=Y({},N,{error(ie){var fe;if(q){m.warn("Stream","Ignoring RepresentationStream error",ie);return}q=!0;let oe=Me(ie,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(oe.code!=="BUFFER_FULL_ERROR")N.error(ie);else{m.warn("Stream","received BUFFER_FULL_ERROR",{bufferType:f.type,representationBitrate:A.bitrate});let Re=a.getValue(),he=((fe=h.get(A.id))!=null?fe:1)*.7;if(h.set(A.id,he),he<=.05||B(A,Re)<=2){N.error(oe);return}en(4e3,K).then(()=>D(A,C,N,K)).catch(te)}},terminating(){X.cancel(),N.terminating()}});Lf({playbackObserver:n,content:{representation:A,adaptation:f,period:l,manifest:c},segmentSink:i,segmentQueue:x,terminate:C,options:{bufferGoal:W,maxBufferSize:H,drmSystemId:t.drmSystemId,fastSwitchThreshold:P}},G,K),c.addEventListener("manifestUpdate",ie=>{for(let oe of ie.updatedPeriods)if(oe.period.id===l.id){for(let fe of oe.result.updatedAdaptations)if(fe.adaptation===f.id){for(let Re of fe.removedRepresentations)if(Re===A.id)return K.isCancelled()?void 0:d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:0,stayInPeriod:!0})}}else if(oe.period.start>l.start)break},K)}function B(A,C){let N=h.get(A.id),K=N!==void 0?N:1;return N===void 0&&h.set(A.id,K),K<1&&C===1/0?300*1e3*K:C*K}}function Nf(n,e){let t=n.filter(r=>$(e,r.id)&&!r.shouldBeAvoided&&r.isPlayable()!==!1);return t.length>0?t:n.filter(r=>$(e,r.id)&&r.isPlayable()!==!1)}var Uf=Pd;function Cd(n,e,t,r,i,o){var p,h,I,g;if(n.codec!==void 0&&o.onCodecSwitch==="reload"&&!Hh(t,n.codec))return{type:"needs-reload",value:void 0};let a=n.getLastKnownInventory(),s=[];for(let b of a)b.infos.period.id===e.id&&b.infos.adaptation.id!==t.id&&vt(s,{start:(p=b.bufferedStart)!=null?p:b.start,end:(h=b.bufferedEnd)!=null?h:b.end});let d=n.getPendingOperations();for(let b of d)if(b.type===0){let T=b.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let v=T.segment.time,_=v+T.segment.duration;vt(s,{start:v,end:_})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let b=i.getReadyState();if(b===void 0||b>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",c=[],l=er(a,e);if(l!==null&&(l.bufferedEnd===void 0||e.start-l.bufferedEnd<1)&&c.push({start:0,end:e.start+1}),!u){let b=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=O.getCurrent(),v=(I=T[b].before)!=null?I:0,_=(g=T[b].after)!=null?g:0,R=i.getCurrentTime();R===void 0&&(R=i.getReference().getValue().position.getPolled()),c.push({start:R-v,end:R+_})}if(e.end!==void 0){let b=tr(a,e);b!==null&&(b.bufferedStart===void 0||b.bufferedStart-e.end<1)&&c.push({start:e.end-1,end:Number.MAX_VALUE})}let f=ko(s,c);return f.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:f}:{type:"clean-buffer",value:f}}function Hh(n,e){return n.representations.some(t=>t.isPlayable()===!0&&da(t.getMimeTypeString(),e))}function Ad({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:o,segmentSinksStore:a,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},c,l){let{manifest:f,period:p}=e,h=new j(void 0,l);if(c.periodStreamReady({type:n,manifest:f,period:p,adaptationRef:h}),l.isCancelled())return;let I,g=!0;h.onUpdate(v=>{(async()=>{var B;if(v===void 0)return;let _=new U;if(_.linkToSignal(l),I==null||I.cancel(),I=_,v===null){m.info("Stream","Set no Adaptation",{periodStart:p.start,bufferType:n});let A=a.getStatus(n);if(A.type==="initialized"){if(m.info("Stream","Clearing previous SegmentSink",{periodStart:p.start,bufferType:n}),on.isNative(n))return T(0,!0,_.signal);{let C=(B=p.end)!=null?B:1/0;if(p.start>C)m.warn("Stream","Can't free buffer: period's start is after its end",{periodStart:p.start,periodEnd:C,bufferType:n});else if(await A.value.removeBuffer(p.start,C),_.isUsed())return}}else if(A.type==="uninitialized"&&(a.disableSegmentSink(n),_.isUsed()))return;return c.adaptationChange({type:n,adaptation:null,period:p}),_.isUsed()?void 0:Bf(r,d,n,{period:p},c,_.signal)}let R=p.adaptations[n],k=Q(R!=null?R:[],A=>A.id===v.adaptationId);if(k===void 0){I.cancel(),m.warn("Stream","Unfound chosen Adaptation choice",{adaptationId:v.adaptationId});return}let{DELTA_POSITION_AFTER_RELOAD:x}=O.getCurrent(),P=!1,M;if(g)M=0;else if(v.relativeResumingPosition!==void 0)M=v.relativeResumingPosition;else switch(P=!0,n){case"audio":M=x.trackSwitch.audio;break;case"video":M=x.trackSwitch.video;break;default:M=x.trackSwitch.other;break}if(g=!1,on.isNative(n)&&a.getStatus(n).type==="disabled")return T(M,!0,_.signal);f.addEventListener("manifestUpdate",A=>{for(let C of A.updatedPeriods)if(C.period.id===p.id){for(let N of C.result.removedAdaptations)if(N.id===k.id)return T(M,!0,_.signal)}else if(C.period.start>p.start)break},I.signal);let{representations:L}=v;if(m.info("Stream","Updating adaptation",{bufferType:k.type,periodStart:p.start,adaptationId:k.id}),c.adaptationChange({type:n,adaptation:k,period:p}),_.isUsed())return;let F=qh(a,n,k),D=Cd(F,p,k,v.switchingMode,r,s);if(D.type==="needs-reload")return T(M,!0,_.signal);if(await a.waitForUsableBuffers(_.signal),!_.isUsed()){if(D.type==="flush-buffer"||D.type==="clean-buffer"){for(let{start:A,end:C}of D.value)if(await F.removeBuffer(A,C),_.isUsed())return;if(D.type==="flush-buffer"&&(c.needsBufferFlush({relativeResumingPosition:M,relativePosHasBeenDefaulted:P}),_.isUsed()))return}t.get(F)(_.signal),b(k,L,F,_.signal)}})().catch(_=>{_ instanceof we||(I==null||I.cancel(),c.error(_))})},{clearSignal:l,emitCurrentValue:!0});function b(v,_,R,k){let x=jh(r,v.type);Uf({content:{manifest:f,period:p,adaptation:v,representations:_},options:s,playbackObserver:x,representationEstimator:i,segmentSink:R,segmentQueueCreator:o,wantedBufferAhead:d,maxVideoBufferSize:u},ue(ae({},c),{error:P}),k);function P(M){if(!on.isNative(n)){m.error("Stream",`${n} Stream crashed. Aborting it.`,M instanceof Error?M:""),a.disposeSegmentSink(n);let L=Me(M,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return c.warning(L),k.isCancelled()?void 0:Bf(r,d,n,{period:p},c,k)}m.error("Stream",`${n} Stream crashed. Stopping playback.`,M instanceof Error?M:""),c.error(M)}}function T(v,_,R){It(()=>{r.listen(()=>{R.isCancelled()||c.waitingMediaSourceReload({bufferType:n,period:p,timeOffset:v,stayInPeriod:_})},{includeLastObservation:!0,clearSignal:R})})}}function qh(n,e,t){let r=n.getStatus(e);if(r.type==="initialized")return m.info("Stream","Reusing a previous SegmentSink for the type",{bufferType:e}),r.value;let i=Gh(t);return n.createSegmentSink(e,i)}function Gh(n){let e=n.representations.filter(t=>t.isPlayable()!==!1);if(e.length>0)return e[0].getMimeTypeString();if(n.representations.length>0)return n.representations[0].getMimeTypeString();throw new re("NO_PLAYABLE_REPRESENTATION","No Representation in the chosen "+n.type+" Adaptation can be played",{tracks:[Tn(n)]})}function jh(n,e){return n.deriveReadOnlyObserver(function(r,i){let o=new j(a(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),o;function a(){let d=r.getValue(),u=d.buffered[e],c=u!==null?Ro(u,d.position.getWanted()):0;return Y({},d,{bufferGap:c,buffered:u})}function s(){o.setValue(a())}})}function Bf(n,e,t,r,i,o){let{period:a}=r,s=!1;e.onUpdate(d,{emitCurrentValue:!1,clearSignal:o}),n.listen(d,{includeLastObservation:!1,clearSignal:o}),d();function d(){let u=n.getReference().getValue(),c=e.getValue(),l=u.position.getWanted();a.end!==void 0&&l+c>=a.end&&(m.debug("Stream",'full "empty" AdaptationStream',{bufferType:t,periodEnd:a.end,position:l,wantedBufferAhead:c}),s=!0),i.streamStatusUpdate({period:a,bufferType:t,imminentDiscontinuity:null,position:l,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var Ff=Ad;function ha(n,e){if(e.length===0)return[];let t=[],r=n.getLastKnownInventory(),i=n.getPendingOperations();for(let o of r)if(e.some(s=>o.infos.period.id===s.period.id&&o.infos.adaptation.id===s.adaptation.id&&o.infos.representation.id===s.representation.id)){let{bufferedStart:s,bufferedEnd:d}=o;if(s===void 0||d===void 0)return m.warn("Stream","No buffered start or end found from a segment.",{bufferType:o.infos.adaptation.type,segmentStart:o.infos.segment.time}),[{start:0,end:Number.MAX_VALUE}];let u=t[t.length-1];u!==void 0&&u.end===s?u.end=d:t.push({start:s,end:d})}for(let o of i){if(o.type!==0)continue;let a=o.value;e.some(d=>a.inventoryInfos.period.id===d.period.id&&a.inventoryInfos.adaptation.id===d.adaptation.id&&a.inventoryInfos.representation.id===d.representation.id)&&vt(t,{start:a.inventoryInfos.start,end:a.inventoryInfos.end})}return t}function Md(n,e,t,r,i,o,a,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:c,maxBufferBehind:l,wantedBufferAhead:f,maxVideoBufferSize:p}=o,{MINIMUM_MAX_BUFFER_AHEAD:h,MAXIMUM_MAX_BUFFER_AHEAD:I,MAXIMUM_MAX_BUFFER_BEHIND:g}=O.getCurrent(),b=new Ei(_=>{var P,M;let{bufferType:R}=_,k=(P=g[R])!=null?P:1/0,x=(M=I[R])!=null?M:1/0;return L=>{ma({segmentSink:_,playbackObserver:e,maxBufferBehind:gn(l,F=>Math.min(F,k),L),maxBufferAhead:gn(c,F=>{var B;let D=Math.max(F,(B=h[R])!=null?B:0);return Math.min(D,x)},L)},L)}});for(let _ of r.getBufferTypes())T(_,u);function T(_,R){let k=new Pn((D,B)=>D.start-B.start),x=!1,P=new U;return P.linkToSignal(s),e.listen(({position:D})=>{let B=D.getWanted();if(!x||!L(B))return;let A=()=>{var N;return(N=d.getPeriodForTime(B))!=null?N:d.getNextPeriod(B)},C=A();if(!(!E(C)&&k.has(C))){for(m.info("Stream","Destroying all PeriodStreams due to out of bounds situation",{bufferType:_,time:B}),x=!1;k.length()>0;){let N=k.get(k.length()-1);k.removeElement(N),a.periodStreamCleared({type:_,manifest:d,period:N})}if(P.cancel(),P=new U,P.linkToSignal(s),C=A(),C===void 0){m.warn("Stream","The wanted position is not found in the Manifest."),x=!0;return}M(C)}},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",D=>{s.isCancelled()||F(D).catch(B=>{s.isCancelled()||(P.cancel(),a.error(B))})},s),M(R);function M(D){let B=ue(ae({},a),{waitingMediaSourceReload(A){let C=k.head();C===void 0||C.id!==A.period.id?a.lockedStream({bufferType:A.bufferType,period:A.period}):a.needsMediaSourceReload({timeOffset:A.timeOffset,minimumPosition:A.stayInPeriod?A.period.start:void 0,maximumPosition:A.stayInPeriod?A.period.end:void 0})},periodStreamReady(A){x=!0,k.add(A.period),a.periodStreamReady(A)},periodStreamCleared(A){k.removeElement(A.period),a.periodStreamCleared(A)},error(A){P.cancel(),a.error(A)}});v(_,D,B,P.signal)}function L(D){let B=k.head(),A=k.last();return B===void 0||A===void 0?!0:B.start>D||(E(A.end)?1/0:A.end)<D}async function F(D){let B=r.getStatus(_),A=D.filter(W=>W.adaptation.type===_);if(A.length===0||B.type!=="initialized"||A.every(W=>W.representation.decipherable===!0))return;let C=B.value,N=A.filter(W=>W.representation.decipherable===void 0),K=A.filter(W=>W.representation.decipherable===!1),q=ha(C,K),X=ha(C,N);for(x=!1,m.info("Stream","Destroying all PeriodStreams for decipherability matters",{bufferType:_});k.length()>0;){let W=k.get(k.length()-1);k.removeElement(W),a.periodStreamCleared({type:_,manifest:d,period:W})}P.cancel(),P=new U,P.linkToSignal(s);for(let{start:W,end:H}of[...q,...X]){if(s.isCancelled())return;if(W<H){if(s.isCancelled())return;await C.removeBuffer(W,H)}}It(()=>{if(s.isCancelled())return;let W=e.getReference().getValue();if(Kf(W,q)){if(a.needsDecipherabilityFlush(),s.isCancelled())return}else if(Kf(W,X)&&(a.needsBufferFlush(),s.isCancelled()))return;let H=W.position.getWanted(),G=d.getPeriodForTime(H);if(G===void 0){a.error(new re("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}M(G)})}}function v(_,R,k,x){m.info("Stream","Creating new PeriodStream",{bufferType:_,periodStart:R.start});let P=null,M=new U;M.linkToSignal(x),e.listen(({position:A},C)=>{if(R.end!==void 0&&A.getWanted()>=R.end){let N=d.getPeriodAfter(R);if(R.containsTime(A.getWanted(),N))return;m.info("Stream","Destroying PeriodStream as the current playhead moved above it",{bufferType:_,periodStart:R.start,periodEnd:R.end,position:A.getWanted()}),C(),k.periodStreamCleared({type:_,manifest:d,period:R}),M.cancel()}},{clearSignal:x,includeLastObservation:!0});let L={bufferType:_,content:{manifest:d,period:R},garbageCollectors:b,maxVideoBufferSize:p,segmentQueueCreator:i,segmentSinksStore:r,options:o,playbackObserver:e,representationEstimator:t,wantedBufferAhead:f},F=ue(ae({},k),{streamStatusUpdate(A){if(A.hasFinishedLoading){let C=d.getPeriodAfter(R);C!==null&&D(C)}else P!==null&&(m.info("Stream","Destroying next PeriodStream due to current one being active",{bufferType:_,periodStart:R.start,nextPeriodStart:P.period.start}),k.periodStreamCleared({type:_,manifest:d,period:P.period}),P.canceller.cancel(),P=null);k.streamStatusUpdate(A)},error(A){P!==null&&(P.canceller.cancel(),P=null),M.cancel(),k.error(A)}});Ff(L,F,M.signal),B(M.signal);function D(A){if(P!==null){if(P.period.id===A.id)return;m.warn("Stream","Creating next `PeriodStream` while one was already created.",{bufferType:_,nextPeriodStart:A.start}),k.periodStreamCleared({type:_,manifest:d,period:P.period}),P.canceller.cancel()}let C=new U;C.linkToSignal(x),P={canceller:C,period:A},v(_,A,k,P.canceller.signal)}function B(A){d.addEventListener("manifestUpdate",C=>{for(let N of C.removedPeriods)if(N.id===R.id){if(d.periods.length>0&&d.periods[0].start<=N.start)return It(()=>{if(!A.isCancelled())return a.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(N.start>R.start)break;if(C.addedPeriods.length>0&&P!==null){let N=d.getPeriodAfter(R);(N===null||P.period.id!==N.id)&&(m.warn("Stream","Destroying next PeriodStream due to new one being added",{bufferType:_,nextPeriodStart:P.period.start}),k.periodStreamCleared({type:_,manifest:d,period:P.period}),P.canceller.cancel(),P=null)}},A)}}}function Kf(n,e){if(e.length===0)return!1;let t=n.position.getPolled();return n.speed>=0?e[e.length-1].end>=t-5:e[0].start<=t+5}var Vf=Md;var zf=Vf;var Yh={dashParsers:{wasm:null,js:null},createDebugElement:null,directfile:null,decrypt:null,htmlTextDisplayer:null,htmlTextTracksParsers:{},mainThreadMediaSourceInit:null,multithread:null,nativeTextDisplayer:null,nativeTextTracksParsers:{},transports:{}},Ri=Yh;function ya(n){for(let e of n)if(typeof e=="function")e(Ri);else if(!E(e)&&typeof e._addFeature=="function")e._addFeature(Ri);else throw new Error("Unrecognized feature")}var pe=Ri;var Qh={createSync(n){return{syncValue:n,getValueAsAsync(){return Promise.resolve(n)}}},createAsync(n){let e=null;return n.then(t=>{e=t},te),{get syncValue(){return e},getValueAsAsync(){return n}}}},Wf=Qh;var rr=class extends se{};function xd(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=Q(n.sourceBuffers,s=>s.type==="audio"),i=Q(n.sourceBuffers,s=>s.type==="video"),o=r==null?void 0:r.getBuffered();o!==void 0&&(t.audio=o);let a=i==null?void 0:i.getBuffered();return a!==void 0&&(t.video=a),t}function wd(n,{autoPlay:e,initialPlayPerformed:t,manifest:r,mediaSource:i,speed:o,textDisplayer:a},s){return n.deriveReadOnlyObserver(function(u,c){let l=new U;l.linkToSignal(c),l.linkToSignal(s);let f=new j(p(),l.signal);return o.onUpdate(h,{clearSignal:l.signal,emitCurrentValue:!1}),u.onUpdate(h,{clearSignal:l.signal,emitCurrentValue:!1}),i==null||i.addEventListener("streamingChanged",()=>{h()},l.signal),f;function p(){var b;let I=u.getValue(),g=o.getValue();return $h(I,r),{maximumPosition:kt(r),bufferGap:I.bufferGap,position:I.position,buffered:xd(i,a),duration:I.duration,rebuffering:I.rebuffering,freezing:I.freezing,paused:{last:I.paused,pending:Xh(t,e)},readyState:I.readyState,speed:g,canStream:(b=i==null?void 0:i.streaming)!=null?b:!0,fullyLoaded:I.fullyLoaded}}function h(){f.setValue(p())}})}function $h(n,e){if(!e.isDynamic||e.isLastPeriodKnown){let t=e.periods[e.periods.length-1];if(t!==void 0&&t.end!==void 0){let r=n.position.getWanted();if(r>=t.start&&r>=t.end-1){let i=n.buffered;(i.length===0||i.end(i.length-1)<n.duration-1)&&n.position.forceWantedPosition(t.end-1)}}}}function Xh(n,e){return n.getValue()?void 0:!e}function ir(n){let{textTracks:e}=n;if(!E(e)){for(let t=0;t<e.length;t++)e[t].mode="disabled";if(n.hasChildNodes()){let{childNodes:t}=n;for(let r=t.length-1;r>=0;r--)if(t[r].nodeName==="track")try{n.removeChild(t[r])}catch(i){m.warn("media","Could not remove text track child from element.")}}}n.src="",n.removeAttribute("src")}function Od(n,e){if(typeof n.changeType=="function"){try{n.changeType(e)}catch(t){return m.warn("mse","Could not call 'changeType' on the given SourceBuffer:",t instanceof Error?t:""),!1}return!0}return!1}function Zh(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function ki(n,e){if(m.debug("mse","Trying to call endOfStream"),n.readyState!=="open"){m.debug("mse","MediaSource not open, cancel endOfStream");return}let{sourceBuffers:t}=n,r=Zh(t);if(r.length===0){m.info("mse","Triggering end of stream");try{n.endOfStream()}catch(o){m.error("mse","Unable to call endOfStream",o instanceof Error?o:new Error("Unknown error"))}return}m.debug("mse","Waiting SourceBuffers to be updated before calling endOfStream.");let i=new U;i.linkToSignal(e);for(let o of r)Fc(o,()=>{i.cancel(),ki(n,e)},i.signal);Kc(t,()=>{i.cancel(),ki(n,e)},i.signal)}function Hf(n,e){let t=new U;t.linkToSignal(e),Gn(n,()=>{m.debug("mse","MediaSource re-opened while end-of-stream is active"),t.cancel(),t=new U,t.linkToSignal(e),ki(n,t.signal)},e),ki(n,t.signal)}function Dd(){let{FORCE_HAS_ISSUES_WITH_HIGH_MEDIA_SOURCE_DURATION:n}=O.getCurrent();return n||V.device===V.DEVICES.PlayStation5}var Jh=365*24*3600,Pi=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=new U;let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,o=ny(r,i),a=new U;a.linkToSignal(i),o.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(a.cancel(),!o.getValue())return;a=new U,a.linkToSignal(i);let d=ty(r.sourceBuffers,a.signal),u=new U;return u.linkToSignal(a.signal),d.onUpdate(c=>{u.cancel(),u=new U,u.linkToSignal(a.signal),!c&&Gf(r,e,t,u.signal)},{clearSignal:a.signal,emitCurrentValue:!0})}}stopUpdating(){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=null)}};function ey(n,e,t){let r=e;t||(r=Dd()?1/0:qf(e));let i=0;for(let o=0;o<n.sourceBuffers.length;o++){let a=n.sourceBuffers[o],s=a.buffered.length;s>0&&(i=Math.max(i,a.buffered.end(s-1)))}if(r===n.duration)return"success";if(i>r){if(i<n.duration)try{m.info("mse","Updating duration to what is currently buffered",{maxBufferedEnd:i}),n.duration=i}catch(o){return m.warn("mse","Can't update duration on the MediaSource.",o instanceof Error?o:""),"failed"}return"partial"}else{let o=n.duration;try{if(m.info("mse","Updating duration",{newDuration:r}),n.duration=r,n.readyState==="open"&&!isFinite(r)){let s=qf(e);m.info("mse","calling `mediaSource.setLiveSeekableRange`",{maxSeekable:s}),n.setLiveSeekableRange(0,s)}}catch(s){return m.warn("mse","Can't update duration on the MediaSource.",s instanceof Error?s:""),"failed"}let a=Math.abs(n.duration-r);if(a>=.1){let s=Math.abs(n.duration-o);return a<s?"partial":"failed"}return"success"}}function ty(n,e){if(n.length===0){let i=new j(!1);return i.finish(),i}let t=new j(!1,e);r();for(let i=0;i<n.length;i++){let o=n[i];o.addEventListener("updatestart",r),o.addEventListener("update",r),e.register(()=>{o.removeEventListener("updatestart",r),o.removeEventListener("update",r)})}return t;function r(){for(let i=0;i<n.length;i++)if(n[i].updating){t.setValueIfChanged(!0);return}t.setValueIfChanged(!1)}}function ny(n,e){let t=new j(n.readyState==="open",e);return Gn(n,()=>{m.debug("mse","Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),qo(n,()=>{m.debug("mse","Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),Ho(n,()=>{m.debug("mse","Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function Gf(n,e,t,r){if(ey(n,e,t)==="success")return;let o=setTimeout(()=>{a(),Gf(n,e,t,r)},2e3),a=r.register(()=>{clearTimeout(o)})}function qf(n){return Math.max(Math.pow(2,32),n+Jh)}var Ci=class extends se{constructor(e,t){if(super(),this.id=e,this.sourceBuffers=[],this._canceller=new U,E(wt))throw new re("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");m.info("mse","Creating MediaSource");let r=t!==void 0?new t:new wt,i=r.handle;this.handle=E(i)?{type:"media-source",value:r}:{type:"handle",value:i},this._mediaSource=r,this.readyState=r.readyState,this._durationUpdater=new Pi(r),this._endOfStreamCanceller=null,Gn(r,()=>{this.readyState=r.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),qo(r,()=>{this.readyState=r.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),Ho(r,()=>{this.readyState=r.readyState,this.trigger("mediaSourceClose",null)},this._canceller.signal),this._mediaSource.streaming!==void 0&&(this.streaming=this._mediaSource.streaming),this._mediaSource.addEventListener("startstreaming",()=>{this.streaming=!0,this.trigger("streamingChanged",null)}),this._mediaSource.addEventListener("endstreaming",()=>{this.streaming=!1,this.trigger("streamingChanged",null)})}addSourceBuffer(e,t){let r=this._mediaSource.addSourceBuffer(t),i=new Ld(e,t,r);return this.sourceBuffers.push(i),i}setDuration(e,t){this._durationUpdater.updateDuration(e,t)}interruptDurationSetting(){this._durationUpdater.stopUpdating()}maintainEndOfStream(){this._endOfStreamCanceller===null&&(this._endOfStreamCanceller=new U,this._endOfStreamCanceller.linkToSignal(this._canceller.signal),m.debug("mse","end-of-stream order received."),Hf(this._mediaSource,this._endOfStreamCanceller.signal))}stopEndOfStream(){this._endOfStreamCanceller!==null&&(m.debug("mse","resume-stream order received."),this._endOfStreamCanceller.cancel(),this._endOfStreamCanceller=null)}dispose(){this.sourceBuffers.forEach(e=>e.dispose()),this._canceller.cancel(),ry(this._mediaSource)}},Ld=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new U,this._sourceBuffer=r,this._operationQueue=[],this._currentOperations=[];let i=this._onError.bind(this),o=this._onUpdateEnd.bind(this);r.addEventListener("updateend",o),r.addEventListener("error",i),this._canceller.signal.register(()=>{r.removeEventListener("updateend",o),r.removeEventListener("error",i)})}appendBuffer(...e){return m.debug("mse","receiving order to push data to the SourceBuffer",{type:this.type}),this._addToQueue({operationName:0,params:e})}remove(e,t){return m.debug("mse","receiving order to remove data from the SourceBuffer",{type:this.type,start:e,end:t}),this._addToQueue({operationName:1,params:[e,t]})}getBuffered(){try{return Le(this._sourceBuffer.buffered)}catch(e){return m.error("mse","Failed to get buffered time range of SourceBuffer",{type:this.type},e instanceof Error?e:"Unknown Error"),[]}}abort(){try{this._sourceBuffer.abort()}catch(e){m.debug("mse","Failed to abort SourceBuffer:",e instanceof Error?e:"Unknown Error")}this._emptyCurrentQueue()}dispose(){try{this._sourceBuffer.abort()}catch(e){}this._emptyCurrentQueue()}_onError(e){let t;e instanceof Error?t=e:e.error instanceof Error?t=e.error:t=new Error("Unknown SourceBuffer Error");let r=this._currentOperations;if(this._currentOperations=[],r.length===0)m.error("mse","error for an unknown operation",t);else{let i=new lt(t.name,t.message,t.name==="QuotaExceededError");for(let o of r)o.reject(i)}}_onUpdateEnd(){let e=this._currentOperations;this._currentOperations=[];try{for(let t of e)t.resolve(Le(this._sourceBuffer.buffered))}catch(t){for(let r of e)t instanceof Error&&t.name==="InvalidStateError"?r.resolve([]):r.reject(t)}this._performNextOperation()}_emptyCurrentQueue(){let e=new we;this._currentOperations.length>0&&(this._currentOperations.forEach(t=>{t.reject(e)}),this._currentOperations=[]),this._operationQueue.length>0&&(this._operationQueue.forEach(t=>{t.reject(e)}),this._operationQueue=[])}_addToQueue(e){return new Promise((t,r)=>{let i=this._operationQueue.length===0&&this._currentOperations.length===0,o=Y({resolve:t,reject:r},e);this._operationQueue.push(o),i&&this._performNextOperation()})}_performNextOperation(){var t,r,i,o,a;if(this._currentOperations.length!==0||this._sourceBuffer.updating)return;let e=this._operationQueue.shift();if(e!==void 0)if(e.operationName===0){this._currentOperations=[{operationName:0,resolve:e.resolve,reject:e.reject}];let s=e.params[0],d=e.params[1],u=s;if(this._operationQueue.length>0&&this._operationQueue[0].operationName===0){let c;s instanceof ArrayBuffer?c=new Uint8Array(s):s instanceof Uint8Array?c=s:c=new Uint8Array(s.buffer);let l=[c];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let f=this._operationQueue[0],p=(r=d.appendWindow)!=null?r:[void 0,void 0],h=(i=f.params[1].appendWindow)!=null?i:[void 0,void 0],I=(o=d.timestampOffset)!=null?o:0,g=(a=f.params[1].timestampOffset)!=null?a:0;if(p[0]===h[0]&&p[1]===h[1]&&d.codec===f.params[1].codec&&I===g){let b=f.params[0],T;b instanceof ArrayBuffer?T=new Uint8Array(b):b instanceof Uint8Array?T=b:T=new Uint8Array(b.buffer),l.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:f.resolve,reject:f.reject})}else break}l.length>1&&(m.info("mse",`: Merging ${l.length} segments together for perf`,{type:this.type}),u=de(...l).buffer)}try{this._appendBufferNow(u,d)}catch(c){let l=c instanceof Error?new lt(c.name,c.message,c.name==="QuotaExceededError"):new lt("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(f=>{f.reject(l)}),this._currentOperations=[],this._performNextOperation()}}else{this._currentOperations=[e];let[s,d]=e.params;m.debug("mse","removing data from SourceBuffer",{type:this.type,start:s,end:d});try{this._sourceBuffer.remove(s,d)}catch(u){let c=u instanceof Error?new lt(u.name,u.message,!1):new lt("Error","Unknown SourceBuffer Error during remove",!1);e.reject(c),this._currentOperations.forEach(l=>{l.reject(c)}),this._currentOperations=[],this._performNextOperation()}}}_appendBufferNow(e,t){let r=this._sourceBuffer,{codec:i,timestampOffset:o,appendWindow:a=[]}=t;if(i!==void 0&&i!==this.codec&&(m.debug("mse","updating codec",{prevCodec:this.codec,newCodec:i}),Od(r,i)?this.codec=i:m.debug("mse","could not update codec",{prevCodec:this.codec,newCodec:i})),o!==void 0&&r.timestampOffset!==o){let s=o;m.debug("mse","updating timestampOffset",{codec:i,prevTimestampOffset:r.timestampOffset,newTimestampOffset:s}),r.timestampOffset=s}if(a[0]===void 0)r.appendWindowStart>0&&(m.debug("mse","re-setting `appendWindowStart`",{prevWindowStart:r.appendWindowStart}),r.appendWindowStart=0);else if(a[0]!==r.appendWindowStart){if(a[0]>=r.appendWindowEnd){let s=a[0]+1;m.debug("mse","pre-updating `appendWindowEnd`",{prevWindowEnd:r.appendWindowEnd,newWindowEnd:s}),r.appendWindowEnd=s}m.debug("mse","setting `appendWindowStart`",{appendWindowStart:a[0]}),r.appendWindowStart=a[0]}a[1]===void 0?r.appendWindowEnd!==1/0&&(m.debug("mse","re-setting `appendWindowEnd`",{prevWindowStart:r.appendWindowStart}),r.appendWindowEnd=1/0):a[1]!==r.appendWindowEnd&&(m.debug("mse","setting `appendWindowEnd`",{prevWindowEnd:r.appendWindowEnd,newWindowEnd:a[1]}),r.appendWindowEnd=a[1]),m.debug("mse","pushing segment",{type:this.type}),r.appendBuffer(e)}};function ry(n){if(n.readyState!=="closed"){let{readyState:e,sourceBuffers:t}=n;for(let r=t.length-1;r>=0;r--){let i=t[r];try{if(e==="open"){m.info("mse","Aborting SourceBuffer before removing");try{i.abort()}catch(o){}}m.info("mse","Removing SourceBuffer from mediaSource"),n.removeSourceBuffer(i)}catch(o){}}t.length>0&&m.info("mse","Not all SourceBuffers could have been removed.")}}var iy=rt();function Nd(n,e){if(e!==null&&n.src===e&&(m.info("media","Clearing HTMLMediaElement's src"),ir(n)),e!==null)try{m.debug("media","Revoking previous URL"),URL.revokeObjectURL(e)}catch(t){m.warn("media","Error while revoking the media source URL",t instanceof Error?t:"")}}function oy(n,e){if(ic&&"disableRemotePlayback"in n){let t=n.disableRemotePlayback;e.register(()=>{n.disableRemotePlayback=t}),n.disableRemotePlayback=!0}}function ay(n,e){let t=w(n.src)?n.src:null;Nd(n,t);let r=new Ci(iy(),"FORCED_MEDIA_SOURCE"in n?n.FORCED_MEDIA_SOURCE:void 0);return oy(n,e),e.register(()=>{r.dispose()}),r}function Ia(n,e){return ct(e,t=>{let r=ay(n,e);if(r.addEventListener("mediaSourceOpen",()=>{m.info("mse","MediaSource opened"),t(r)},e),m.info("media","Attaching MediaSource URL to the media element",{handleType:r.handle.type}),r.handle.type==="handle")n.srcObject=r.handle.value,e.register(()=>{Nd(n,null)});else{let i=URL.createObjectURL(r.handle.value);n.src=i,e.register(()=>{Nd(n,i)})}})}function Ud(n,e,t){var i;if(!E(t)){let o=bn(n),a=kt(n);if(E(t.position))if(E(t.wallClockTime))if(E(t.fromFirstPosition))if(E(t.fromLastPosition))if(E(t.fromLivePosition)){if(!E(t.percentage)){let{percentage:s}=t;if(m.debug("Init","Initial Position: using startAt.percentage",{percentage:s,min:o,max:a}),s>100)return a;if(s<0)return o;let d=+s/100,u=a-o;return o+u*d}}else{let s=(i=Sn(n))!=null?i:a,{fromLivePosition:d}=t;return m.debug("Init","Initial Position: using startAt.fromLivePosition",{fromLivePosition:d,livePosition:s,min:o}),d>=0?s:Math.max(o,s+d)}else{let{fromLastPosition:s}=t;return m.debug("Init","Initial Position: using startAt.fromLastPosition",{fromLastPosition:s,min:o,max:a}),s>=0?a:Math.max(o,a+s)}else{let{fromFirstPosition:s}=t;return m.debug("Init","Initial Position: using startAt.fromFirstPosition",{fromFirstPosition:s,min:o,max:a}),s<=0?o:Math.min(a,o+s)}else{let s=n.availabilityStartTime===void 0?0:n.availabilityStartTime,d=t.wallClockTime-s;return m.debug("Init","Initial Position: using startAt.wallClockTime",{wallClockTime:t.wallClockTime,wallClockOffset:s,deOffseted:d,min:o,max:a,isDynamic:n.isDynamic}),n.isDynamic?d:Math.max(Math.min(d,a),o)}else return m.debug("Init","Initial Position: using startAt.position",{position:t.position,min:o,max:a,isDynamic:n.isDynamic}),n.isDynamic?t.position:Math.max(Math.min(t.position,a),o)}let r=bn(n);if(n.isLive){let{suggestedPresentationDelay:o,clockOffset:a}=n,s=kt(n),d,{DEFAULT_LIVE_GAP:u}=O.getCurrent();if(a===void 0)m.info("Init","no clock offset found for a live content, starting close to maximum available position",{maximumPosition:s}),d=s;else{let l=n.availabilityStartTime===void 0?0:n.availabilityStartTime,f=(z()+a)/1e3-l;d=Math.min(s,f),m.info("Init","clock offset found for a live content, checking if we can start close to it",{wallClockOffset:l,clockRelativeLiveTime:f,liveTime:d})}let c=o!=null?o:e?u.LOW_LATENCY:u.DEFAULT;return m.debug("Init","Initial Position: Applying gap from live time",{liveTime:d,diffFromLiveTime:c,minimumPosition:r}),Math.max(d-c,r)}return m.info("Init","Initial Position: starting at the minimum available position",{minimumPosition:r}),r}function Ai(){let{FORCE_SHOULD_VALIDATE_METADATA:n}=O.getCurrent();return n||V.isSamsungBrowser}function Bd(n){let{FORCE_DONT_WAIT_FOR_DATA_BEFORE_LOADED:e}=O.getCurrent();return!(e||n&&(V.browser===V.BROWSERS.SafariMobile||V.browser===V.BROWSERS.SafariDesktop))}function Fd(){let{FORCE_WAIT_FOR_HAVE_ENOUGH_DATA:n}=O.getCurrent();return n||V.device===V.DEVICES.PlayStation5}function Mi(n,e,t){let r=new U;r.linkToSignal(t);let i=new j(!1,r.signal);return n.listen(o=>{if(o.rebuffering!==null||o.freezing!==null||o.readyState===0)return;if(!Bd(e)){if(isNaN(o.duration))return;if(o.duration>0){i.setValue(!0),r.cancel();return}}let a=Fd()?4:3;if(o.readyState>=a&&(o.currentRange!==null||o.ended)&&(!Ai()||o.duration>0)){i.setValue(!0),r.cancel();return}},{includeLastObservation:!0,clearSignal:r.signal}),i}var or=class{constructor(e,t){this._last=e,this._wanted=t}serialize(){return[this._last,this._wanted]}getPolled(){return this._last}getWanted(){var e;return(e=this._wanted)!=null?e:this._last}forceWantedPosition(e){this._wanted=e}isAwaitingFuturePosition(){return this._wanted!==null}};function xi({mediaElement:n,playbackObserver:e,startTime:t,mustAutoPlay:r,isDirectfile:i,onWarning:o},a){let s=new j(!1,a);return{autoPlayResult:new Promise((u,c)=>{let l=a.register(b=>{c(b)});if(a.isCancelled())return;let f=!1,p=b=>{let T=e.getPendingSeekInformation();(T===null||T.isInternal)&&e.setCurrentTime(b),f=!0,e.unblockSeeking()};if(!i||typeof t=="number"){let b=typeof t=="number"?t:t();b!==0&&b!==void 0?p(b):e.unblockSeeking(),h()}else e.listen((b,T)=>{let v=typeof t=="number"?t:t();v===void 0&&b.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||b.readyState>=1&&(T(),v!==0&&v!==void 0?p(v):e.unblockSeeking(),h())},{includeLastObservation:!1,clearSignal:a});function h(){let b=!1;e.listen((T,v)=>{if(!b&&(T.seeking!==0||T.event==="seeking"||T.event==="internal-seeking")&&(b=!0),!(f&&!b||T.readyState===0)){if(v(),Ai()&&n.duration===0){let _=new re("MEDIA_ERR_NOT_LOADED_METADATA","Cannot load automatically: your browser falsely announced having loaded the content.");o(_)}a.isCancelled()||I()}},{includeLastObservation:!1,clearSignal:a})}function I(){e.listen((b,T)=>{b.seeking===0&&b.rebuffering===null&&b.readyState>=1&&(T(),g())},{includeLastObservation:!0,clearSignal:a})}function g(){var T;if(m.info("Init","Can begin to play content"),r){if(n.ended)return m.warn("Init","autoplay is enabled but the video is ended. Skipping autoplay to prevent video to start again"),s.setValue(!0),s.finish(),l(),u({type:"skipped"})}else return n.autoplay&&m.warn("Init","autoplay is enabled on HTML media element. Media will play as soon as possible."),s.setValue(!0),s.finish(),l(),u({type:"skipped"});let b;try{b=(T=n.play())!=null?T:Promise.resolve()}catch(v){return l(),c(v)}b.then(()=>{if(!a.isCancelled())return s.setValue(!0),s.finish(),l(),u({type:"autoplay"})}).catch(v=>{if(l(),!a.isCancelled())if(v instanceof Error&&v.name==="NotAllowedError"){m.warn("Init","Media element can't play. It may be due to browser auto-play policies.");let _=new re("MEDIA_ERR_BLOCKED_AUTOPLAY","Cannot trigger auto-play automatically: your browser does not allow it.");return o(_),a.isCancelled()?void 0:u({type:"autoplay-blocked"})}else c(v)})}}),initialPlayPerformed:s}}function wi(n,e,t,r){var l;if(e.length===0)return c("No `keySystems` option given.");if(pe.decrypt===null)return c("EME feature not activated.");let i=new U;i.linkToSignal(r);let o=new j({initializationState:{type:"uninitialized",value:null},drmSystemId:void 0},r),a=pe.decrypt,s=(l=n.FORCED_EME_API)!=null?l:sf("auto");if(s===null)return c("EME API not available on the current page.");m.debug("Init","Creating ContentDecryptor");let d=new a(s,n,e),u=f=>{var p;f>0&&((p=t.onCodecSupportUpdate)==null||p.call(t),d.removeEventListener("stateChange",u))};return d.addEventListener("stateChange",u),d.addEventListener("stateChange",f=>{if(f===1){let p=new j(!1);p.onUpdate((h,I)=>{h&&(I(),f===1&&d.attach())},{clearSignal:i.signal}),o.setValue({initializationState:{type:"awaiting-media-link",value:{isMediaLinked:p}},drmSystemId:d.systemId})}else f===2&&(o.setValue({initializationState:{type:"initialized",value:null},drmSystemId:d.systemId}),d.removeEventListener("stateChange"))}),d.addEventListener("error",f=>{i.cancel(),t.onError(f)}),d.addEventListener("warning",f=>{t.onWarning(f)}),d.addEventListener("blackListProtectionData",f=>{t.onBlackListProtectionData(f)}),d.addEventListener("keyIdsCompatibilityUpdate",f=>{t.onKeyIdsCompatibilityUpdate(f)}),i.signal.register(()=>{d.dispose()}),{statusRef:o,contentDecryptor:{enabled:!0,value:d}};function c(f){let p=new be("MEDIA_IS_ENCRYPTED_ERROR",f,{keyStatuses:void 0,keySystemConfiguration:void 0,keySystem:void 0}),h=new j({initializationState:{type:"initialized",value:null},drmSystemId:void 0});return h.finish(),{statusRef:h,contentDecryptor:{enabled:!1,value:p}}}}var Oi=class{constructor(e){this._displayer=e}pushTextData(e){try{return Promise.resolve(this._displayer.pushTextData(e))}catch(t){return Promise.reject(t)}}remove(e,t){try{return Promise.resolve(this._displayer.removeBuffer(e,t))}catch(r){return Promise.reject(r)}}reset(){this._displayer.reset()}stop(){this._displayer.stop()}};function Cn(){let{FORCE_IS_SEEKING_APPROXIMATE:n}=O.getCurrent();return n||V.device===V.DEVICES.Tizen}var Di=1/60,An=class extends se{constructor(e,t,r){super(),this._playbackObserver=e,this._manifest=t,this._speed=r,this._discontinuitiesStore=[],this._isStarted=!1,this._canceller=new U}start(){if(this._isStarted)return;this._isStarted=!0;let e=new zd(this._playbackObserver,this._speed);this._canceller.signal.register(()=>{e.dispose()}),this._playbackObserver.listen(t=>{let r=this._discontinuitiesStore,{buffered:i,position:o,readyState:a,rebuffering:s,freezing:d}=t,{BUFFER_DISCONTINUITY_THRESHOLD:u,FREEZING_STALLED_DELAY:c}=O.getCurrent();if(d!==null&&z()-d.timestamp>c){s===null?e.stopRebuffering():e.startRebuffering(),this.trigger("stalled","freezing");return}if(s===null){if(e.stopRebuffering(),a===1){let g;t.seeking!==0?g=t.seeking===1?"internal-seek":"seeking":g="not-ready",this.trigger("stalled",g);return}this.trigger("unstalled",null);return}let l=s.reason==="seeking"&&t.seeking===1?"internal-seek":s.reason;if(o.isAwaitingFuturePosition()?(e.stopRebuffering(),m.debug("Init","let rebuffering happen as we're awaiting a future position",{wantedPosition:o.getWanted(),lastPolledPosition:o.getPolled()})):e.startRebuffering(),this._manifest===null||Cn()&&z()-s.timestamp<=1e3){this.trigger("stalled",l);return}let{position:f}=s,p=t.position.isAwaitingFuturePosition()?t.position.getWanted():this._playbackObserver.getCurrentTime();if(f!=null&&this._speed.getValue()>0){let g=sy(r,this._manifest,f);if(g!==null){let b=g+.001;if(b<=p)m.info("Init","position to seek already reached, no seeking",{targetTime:p,realSeekTime:b});else{m.warn("Init","skippable discontinuity found in the stream",{lastPolledPosition:o.getPolled(),realSeekTime:b}),this._playbackObserver.setCurrentTime(b),this.trigger("warning",Vd(f,b));return}}}let h=f!=null?f:o.getPolled(),I=fc(i,h);if((!Cn()||z()-s.timestamp>1e3)&&this._speed.getValue()>0&&I<u){let g=h+I+Di;if(p<g){m.warn("Init","discontinuity encountered inferior to the threshold",{positionBlockedAt:h,seekTo:g,BUFFER_DISCONTINUITY_THRESHOLD:u}),this._playbackObserver.setCurrentTime(g),this.trigger("warning",Vd(h,g));return}}for(let g=this._manifest.periods.length-2;g>=0;g--){let b=this._manifest.periods[g];if(b.end!==void 0&&b.end<=h){if(this._manifest.periods[g+1].start>h&&this._manifest.periods[g+1].start>p){let T=this._manifest.periods[g+1];this._playbackObserver.setCurrentTime(T.start),this.trigger("warning",Vd(h,T.start));return}break}}this.trigger("stalled",l)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}updateDiscontinuityInfo(e){this._isStarted||this.start();let t=this._playbackObserver.getReference().getValue();dy(this._discontinuitiesStore,e,t)}onLockedStream(e,t){var s;this._isStarted||this.start();let r=this._playbackObserver.getReference().getValue();if(r.rebuffering===null||r.paused||this._speed.getValue()<=0||e!=="audio"&&e!=="video")return;let i=r.position.getWanted(),o=(s=r.rebuffering.position)!=null?s:i,a=t.start;i<a&&Math.abs(o-a)<1&&(m.warn("Init",`rebuffering because of a future locked stream.
|
|
4
|
-
Trying to unlock by seeking to the next Period`),this._playbackObserver.setCurrentTime(a+.001))}destroy(){this._canceller.cancel()}};function sy(n,e,t){if(n.length===0)return null;let r=null;for(let i of n){let{period:o}=i;if(o.start>t)return r;let a;if(o.end===void 0||o.end>t){let{discontinuity:s,position:d}=i,{start:u,end:c}=s,l=u!=null?u:d;if(t>=l-Di)if(c===null){let f=Do(e,o);f!==null?a=f.start+Di:m.warn("Init","discontinuity at Period's end but no next Period",{periodId:o.id})}else t<c+Di&&(a=c+Di);a!==void 0&&(m.info("Init","discontinuity found",{stalledPosition:t,discontinuityEnd:a}),r=r!==null&&r>a?r:a)}}return r}function Kd(n){return n.discontinuity!==null}function dy(n,e,t){let r=Math.min(t.position.getPolled(),t.position.getWanted());for(;n.length>0&&n[0].period.end!==void 0&&n[0].period.end+10<r;)n.shift();let{period:i,bufferType:o}=e;if(!(o!=="audio"&&o!=="video")){for(let a=0;a<n.length;a++)if(n[a].period.id===i.id){if(n[a].bufferType===o){Kd(e)?n[a]=e:n.splice(a,1);return}}else if(n[a].period.start>i.start){Kd(e)&&n.splice(a,0,e);return}Kd(e)&&n.push(e)}}function Vd(n,e){return new re("DISCONTINUITY_ENCOUNTERED","A discontinuity has been encountered at position "+String(n)+", seeking at position "+String(e))}var zd=class{constructor(e,t){this._speedUpdateCanceller=new U,this._isRebuffering=!1,this._playbackObserver=e,this._isDisposed=!1,this._speed=t,this._updateSpeed()}startRebuffering(){this._isRebuffering||this._isDisposed||(this._isRebuffering=!0,this._speedUpdateCanceller.cancel(),m.info("Init","Pause playback to build buffer"),this._playbackObserver.setPlaybackRate(0))}stopRebuffering(){!this._isRebuffering||this._isDisposed||(this._isRebuffering=!1,this._speedUpdateCanceller=new U,this._updateSpeed())}dispose(){this._speedUpdateCanceller.cancel(),this._isDisposed=!0}_updateSpeed(){this._speed.onUpdate(e=>{m.info("Init","Resume playback speed",{newSpeed:e}),this._playbackObserver.setPlaybackRate(e)},{clearSignal:this._speedUpdateCanceller.signal,emitCurrentValue:!0})}};function uy(n,e){return n.id===e.id&&n.start===e.start&&n.end===e.end}var jf=uy;function ly(n,e){let t=[],{periods:r}=e;for(let i of r){let{streamEvents:o}=i;o.forEach(({start:a,end:s,id:d,data:u})=>{for(let f of n)if(jf(f,{id:d,start:a,end:s})){t.push(f);return}let c;if(u.value.xmlData!==void 0){let f=u.value.xmlData.namespaces.reduce((h,I)=>h+"xmlns:"+I.key+'="'+I.value+'" ',"<toremove ");f+=">";let p=new DOMParser().parseFromString(f+u.value.xmlData.data+"</toremove>","application/xml").documentElement;c=p.children.length>0?p.children[0]:p.childNodes[0]}else return;let l={type:u.type,value:ue(ae({},u.value),{xmlData:void 0,element:c})};if(s===void 0){let f={start:a,id:d,data:l,publicEvent:{start:a,data:l}};t.push(f)}else{let f={start:a,end:s,id:d,data:l,publicEvent:{start:a,end:s,data:l}};t.push(f)}})}return t}var Wd=ly;var Li=class extends se{constructor(e,t){super(),this._manifest=e,this._playbackObserver=t,this._canceller=null,this._scheduledEventsRef=new j([]),this._eventsBeingPlayed=new WeakMap}start(){if(this._canceller!==null)return;this._canceller=new U;let e=this._canceller.signal,t=this._playbackObserver,r=!1,i=new U;i.linkToSignal(e),this._scheduledEventsRef.setValue(Wd([],this._manifest)),this._scheduledEventsRef.onUpdate(({length:o})=>{if(o===0){r&&(i.cancel(),i=new U,i.linkToSignal(e),r=!1);return}else if(r)return;r=!0;let a=c(),s=()=>{let l=c();this._emitStreamEvents(this._scheduledEventsRef.getValue(),a,l,i.signal),a=l},{STREAM_EVENT_EMITTER_POLL_INTERVAL:d}=O.getCurrent(),u=setInterval(s,d);t.listen(s,{includeLastObservation:!1,clearSignal:i.signal}),i.signal.register(()=>{clearInterval(u)});function c(){var h;let l=t.getReference().getValue(),f=(h=t.getCurrentTime())!=null?h:t.getReference().getValue().position.getPolled(),p=l.seeking!==0;return{currentTime:f,isSeeking:p}}},{emitCurrentValue:!0,clearSignal:e})}onManifestUpdate(e){let t=this._scheduledEventsRef.getValue();this._scheduledEventsRef.setValue(Wd(t,e))}stop(){this._canceller!==null&&(this._canceller.cancel(),this._canceller=null)}_emitStreamEvents(e,t,r,i){let{currentTime:o}=t,{isSeeking:a,currentTime:s}=r,d=[],u=[];for(let c=0;c<e.length;c++){let l=e[c],f=l.start,p=Hd(l)?l.end:void 0;this._eventsBeingPlayed.has(l)?(f>s||p!==void 0&&s>=p)&&(Hd(l)&&u.push(l.publicEvent),this._eventsBeingPlayed.delete(l)):f<=s&&p!==void 0&&s<p?(d.push({type:"stream-event",value:l.publicEvent}),this._eventsBeingPlayed.set(l,!0)):o<f&&s>=(p!=null?p:f)&&(a?d.push({type:"stream-event-skip",value:l.publicEvent}):(d.push({type:"stream-event",value:l.publicEvent}),Hd(l)&&u.push(l.publicEvent)))}if(d.length>0){for(let c of d)if(c.type==="stream-event"?this.trigger("event",c.value):this.trigger("eventSkip",c.value),i.isCancelled())return}if(u.length>0){for(let c of u)if(typeof c.onExit=="function"&&c.onExit(),i.isCancelled())return}}};function Hd(n){return n.end!==void 0}var Yf=Li;function Ni(n,e,t){if(t.isCancelled())return;n.addEventListener("error",r),t.register(()=>{n.removeEventListener("error",r)});function r(){let i=n.error,o,a;switch(E(i)||(o=i.code,a=i.message),o){case 1:return a=a!=null?a:"The fetching of the associated resource was aborted by the user's request.",e(new re("MEDIA_ERR_ABORTED",a));case 2:return a=a!=null?a:"A network error occurred which prevented the media from being successfully fetched",e(new re("MEDIA_ERR_NETWORK",a));case 3:return a=a!=null?a:"An error occurred while trying to decode the media resource",e(new re("MEDIA_ERR_DECODE",a));case 4:return a=a!=null?a:"The media resource has been found to be unsuitable.",e(new re("MEDIA_ERR_SRC_NOT_SUPPORTED",a));default:return a=a!=null?a:"The HTMLMediaElement errored due to an unknown reason.",e(new re("MEDIA_ERR_UNKNOWN",a))}}}var Mn=class extends rr{constructor(e){super(),this._initSettings=e,this._initCanceller=new U,this._manifest=null,this._decryptionCapabilities={status:"uninitialized",value:null};let t=e.url===void 0?void 0:[e.url];this._cmcdDataBuilder=e.cmcd===void 0?null:new Rc(e.cmcd),this._manifestFetcher=new sd(t,e.transport,ue(ae({},e.manifestRequestSettings),{lowLatencyMode:e.lowLatencyMode,cmcdDataBuilder:this._cmcdDataBuilder}))}prepare(){this._manifest===null&&(this._manifest=Wf.createAsync(ct(this._initCanceller.signal,(e,t)=>{this._manifestFetcher.addEventListener("warning",r=>this.trigger("warning",r)),this._manifestFetcher.addEventListener("error",r=>{this.trigger("error",r),t(r)}),this._manifestFetcher.addEventListener("manifestReady",r=>{e(r)})})),this._manifestFetcher.start(),this._initCanceller.signal.register(()=>{this._manifestFetcher.dispose()}))}start(e,t){this.prepare(),Ni(e,r=>this._onFatalError(r),this._initCanceller.signal),this._setupInitialMediaSourceAndDecryption(e).then(r=>this._onInitialMediaSourceReady(e,r.mediaSource,t,r.drmSystemId,r.unlinkMediaSource)).catch(r=>{this._onFatalError(r)})}updateContentUrls(e,t){this._manifestFetcher.updateContentUrls(e,t)}dispose(){this._initCanceller.cancel()}_onFatalError(e){this._initCanceller.isUsed()||(this._initCanceller.cancel(),this.trigger("error",e))}_setupInitialMediaSourceAndDecryption(e){let t=this._initCanceller;return ct(t.signal,r=>{let{keySystems:i}=this._initSettings,{statusRef:o,contentDecryptor:a}=wi(e,i,{onWarning:s=>this.trigger("warning",s),onError:s=>this._onFatalError(s),onBlackListProtectionData:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();my(d,s)})().catch(te)},onKeyIdsCompatibilityUpdate:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();fy(d,s.whitelistedKeyIds,s.blacklistedKeyIds,s.delistedKeyIds)})().catch(te)},onCodecSupportUpdate:()=>{var d,u;let s=(d=this._manifest)==null?void 0:d.syncValue;E(s)?(u=this._manifest)==null||u.getValueAsAsync().then(c=>{this._initCanceller.isUsed()||this._refreshManifestCodecSupport(c,e)},te):this._refreshManifestCodecSupport(s,e)}},t.signal);a.enabled?this._decryptionCapabilities={status:"enabled",value:a.value}:this._decryptionCapabilities={status:"disabled",value:a.value},o.onUpdate((s,d)=>{if(s.initializationState.type==="uninitialized")return;d();let u=new U;u.linkToSignal(t.signal),Ia(e,u.signal).then(c=>{let l=o.getValue();if(l.initializationState.type==="awaiting-media-link")l.initializationState.value.isMediaLinked.setValue(!0),o.onUpdate((f,p)=>{if(f.initializationState.type==="initialized"){p(),r({mediaSource:c,drmSystemId:f.drmSystemId,unlinkMediaSource:u});return}},{emitCurrentValue:!0,clearSignal:t.signal});else if(s.initializationState.type==="initialized"){r({mediaSource:c,drmSystemId:s.drmSystemId,unlinkMediaSource:u});return}}).catch(c=>{u.isUsed()||this._onFatalError(c)})},{emitCurrentValue:!0,clearSignal:t.signal})})}async _onInitialMediaSourceReady(e,t,r,i,o){var k;let{adaptiveOptions:a,autoPlay:s,bufferOptions:d,lowLatencyMode:u,segmentRequestOptions:c,speed:l,startAt:f,textTrackOptions:p,transport:h}=this._initSettings,I=this._initCanceller;ne(this._manifest!==null);let g;try{g=(k=this._manifest.syncValue)!=null?k:await this._manifest.getValueAsAsync()}catch(x){return}g.addEventListener("manifestUpdate",x=>{this.trigger("manifestUpdate",x),this._refreshManifestCodecSupport(g,e)},I.signal),g.addEventListener("decipherabilityUpdate",x=>{this.trigger("decipherabilityUpdate",x)},I.signal),g.addEventListener("supportUpdate",()=>{this.trigger("codecSupportUpdate",null)},I.signal),m.debug("Init","Calculating initial time");let b=Ud(g,u,f);m.debug("Init","Initial time calculated",{initialTime:b});let T=_c(a),v=Y({textTrackOptions:p,drmSystemId:i},d),_=new Wn(I.signal),R=new cd(h,_,this._cmcdDataBuilder,c);this._refreshManifestCodecSupport(g,e),this.trigger("manifestReady",g),!I.isUsed()&&this._setupContentWithNewMediaSource({mediaElement:e,playbackObserver:r,mediaSource:t,initialTime:b,autoPlay:s,manifest:g,representationEstimator:T,cdnPrioritizer:_,segmentQueueCreator:R,speed:l,bufferOptions:v},o)}_setupContentWithNewMediaSource(e,t){this._startLoadingContentOnMediaSource(e,this._createReloadMediaSourceCallback(e,t),t.signal)}_createReloadMediaSourceCallback(e,t){let r=this._initCanceller;return i=>{if(t.cancel(),r.isUsed()||(this.trigger("reloadingMediaSource",i),r.isUsed()))return;let o=new U;o.linkToSignal(r.signal),Ia(e.mediaElement,o.signal).then(a=>{this._setupContentWithNewMediaSource(ue(ae({},e),{mediaSource:a,initialTime:i.position,autoPlay:i.autoPlay}),o)}).catch(a=>{o.isUsed()||this._onFatalError(a)})}}_startLoadingContentOnMediaSource(e,t,r){var B,A;let{autoPlay:i,bufferOptions:o,initialTime:a,manifest:s,mediaElement:d,mediaSource:u,playbackObserver:c,representationEstimator:l,cdnPrioritizer:f,segmentQueueCreator:p,speed:h}=e,{transport:I}=this._initSettings,g=(B=s.getPeriodForTime(a))!=null?B:s.getNextPeriod(a);if(g===void 0){let C=new re("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");return this._onFatalError(C)}let b=null,T=cy(d,this._initSettings.textTrackOptions);if(T!==null){let C=new Oi(T);b=C,r.register(()=>{C.stop(),T==null||T.stop()})}let v=new on(u,d.nodeName==="VIDEO",b);r.register(()=>{v.disposeAll()});let{autoPlayResult:_,initialPlayPerformed:R}=xi({mediaElement:d,playbackObserver:c,startTime:a,mustAutoPlay:i,onWarning:C=>{this.trigger("warning",C)},isDirectfile:!1},r);if(r.isCancelled())return;R.onUpdate((C,N)=>{if(C){N();let K=new Yf(s,c);s.addEventListener("manifestUpdate",()=>{K.onManifestUpdate(s)},r),K.addEventListener("event",q=>{this.trigger("streamEvent",q)},r),K.addEventListener("eventSkip",q=>{this.trigger("streamEventSkip",q)},r),K.start(),r.register(()=>{K.stop()})}},{clearSignal:r,emitCurrentValue:!0});let k=wd(c,{autoPlay:i,manifest:s,mediaSource:u,textDisplayer:T,initialPlayPerformed:R,speed:h},r);(A=this._cmcdDataBuilder)==null||A.startMonitoringPlayback(k),r.register(()=>{var C;(C=this._cmcdDataBuilder)==null||C.stopMonitoringPlayback()});let x=this._createRebufferingController(c,s,h,r),P=new hi(v);os()&&s.addEventListener("decipherabilityUpdate",C=>{C.some(N=>N.representation.decipherable!==!0)&&D(0,void 0,void 0)},r),k.listen(C=>{Id(C,v);let N=P.onNewObservation(C);if(N===null)return;let K=()=>{var H;let q=c.getReference().getValue(),X=q.position.isAwaitingFuturePosition()?q.position.getWanted():(H=k.getCurrentTime())!=null?H:q.position.getPolled(),W=R.getValue()?!c.getIsPaused():i;t({position:X,autoPlay:W})};py(N,{enableRepresentationAvoidance:this._initSettings.enableRepresentationAvoidance,manifest:s,triggerReload:K,playbackObserver:c})},{clearSignal:r});let M=gd(s,u,k,v,{onWarning:C=>this.trigger("warning",C),onPeriodChanged:C=>this.trigger("activePeriodChanged",{period:C})},r);_.then(()=>{Mi(c,!1,r).onUpdate((C,N)=>{if(C){let K=md(I.thumbnails,f);N(),this.trigger("loaded",{getSegmentSinkMetrics:async()=>new Promise(q=>q(v.getSegmentSinksMetrics())),getThumbnailData:async(q,X,W)=>yd(K,s,q,X,W)})}},{emitCurrentValue:!0,clearSignal:r})}).catch(C=>{r.isCancelled()||this._onFatalError(C)});let L=this;zf({manifest:s,initialPeriod:g},k,l,v,p,o,F(),r);function F(){return{needsBufferFlush:C=>{var H;let N,K=c.getReference().getValue(),q=K.position.isAwaitingFuturePosition()?K.position.getWanted():d.currentTime,X=(H=C==null?void 0:C.relativeResumingPosition)!=null?H:0,W=!!(C!=null&&C.relativePosHasBeenDefaulted);X===0&&W?N=q+.001:N=q+X,c.setCurrentTime(N),c.listen((G,ie)=>{(G.currentRange!==null||G.position.getPolled()>N+.1)&&(ie(),c.setCurrentTime(G.position.getWanted()+.001))},{includeLastObservation:!1,clearSignal:r})},streamStatusUpdate(C){let{period:N,bufferType:K,imminentDiscontinuity:q,position:X}=C;x.updateDiscontinuityInfo({period:N,bufferType:K,discontinuity:q,position:X}),!r.isCancelled()&&s.isLastPeriodKnown&&C.period.id===s.periods[s.periods.length-1].id&&(C.hasFinishedLoading||C.isEmptyStream?M.onLastSegmentFinishedLoading(C.bufferType):M.onLastSegmentLoadingResume(C.bufferType))},needsManifestRefresh:()=>L._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0}),manifestMightBeOufOfSync:()=>{let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:C}=O.getCurrent();L._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:C})},lockedStream:C=>x.onLockedStream(C.bufferType,C.period),adaptationChange:C=>{L.trigger("adaptationChange",C),!r.isCancelled()&&M.onAdaptationChange(C.type,C.period,C.adaptation)},representationChange:C=>{L.trigger("representationChange",C),!r.isCancelled()&&M.onRepresentationChange(C.type,C.period)},inbandEvent:C=>L.trigger("inbandEvents",C),warning:C=>L.trigger("warning",C),periodStreamReady:C=>L.trigger("periodStreamReady",C),periodStreamCleared:C=>{M.onPeriodCleared(C.type,C.period),!r.isCancelled()&&L.trigger("periodStreamCleared",{type:C.type,periodId:C.period.id})},bitrateEstimateChange:C=>{var N;(N=L._cmcdDataBuilder)==null||N.updateThroughput(C.type,C.bitrate),L.trigger("bitrateEstimateChange",C)},needsMediaSourceReload:C=>{D(C.timeOffset,C.minimumPosition,C.maximumPosition)},needsDecipherabilityFlush(){var N,K,q,X;let C=Zn(d);if(as(C==null?void 0:C[0])){let W=k.getReference().getValue(),H=W.position.isAwaitingFuturePosition()?W.position.getWanted():(N=k.getCurrentTime())!=null?N:W.position.getPolled(),G=(q=(K=W.paused.pending)!=null?K:k.getIsPaused())!=null?q:W.paused.last;t({position:H,autoPlay:!G})}else{let W=k.getReference().getValue(),H=W.position.isAwaitingFuturePosition()?W.position.getWanted():(X=k.getCurrentTime())!=null?X:W.position.getPolled();H+.001<W.duration?c.setCurrentTime(d.currentTime+.001):c.setCurrentTime(H)}},encryptionDataEncountered:C=>{if(L._decryptionCapabilities.status==="disabled"){L._onFatalError(L._decryptionCapabilities.value);return}else if(L._decryptionCapabilities.status==="uninitialized"){m.error("Init","received encryption data without known decryption capabilities");return}for(let N of C)if(L._decryptionCapabilities.value.onInitializationData(N),r.isCancelled())return},error:C=>L._onFatalError(C)}}function D(C,N,K){var G,ie,oe;let q=k.getReference().getValue(),X=q.position.isAwaitingFuturePosition()?q.position.getWanted():(G=k.getCurrentTime())!=null?G:q.position.getPolled(),W=(oe=(ie=q.paused.pending)!=null?ie:k.getIsPaused())!=null?oe:q.paused.last,H=X+C;N!==void 0&&(H=Math.max(N,H)),K!==void 0&&(H=Math.min(K,H)),t({position:H,autoPlay:!W})}}_createRebufferingController(e,t,r,i){let o=new An(e,t,r);return o.addEventListener("stalled",a=>this.trigger("stalled",a)),o.addEventListener("unstalled",()=>this.trigger("unstalled",null)),o.addEventListener("warning",a=>this.trigger("warning",a)),i.register(()=>o.destroy()),o.start(),o}getCodecsSupportInfo(e,t){return e.map(i=>{var d;let o=`${i.mimeType};codecs="${i.codec}"`,a=ns(t,o);if(!a)return{mimeType:i.mimeType,codec:i.codec,supported:!1,supportedIfEncrypted:!1};let s;if(this._decryptionCapabilities.status==="uninitialized")s=void 0;else if(this._decryptionCapabilities.status==="disabled")s=!0;else{let u=this._decryptionCapabilities.value;u.getState()!==0&&(s=(d=u.isCodecSupported(i.mimeType,i.codec))!=null?d:!0)}return{mimeType:i.mimeType,codec:i.codec,supported:a,supportedIfEncrypted:s}})}_refreshManifestCodecSupport(e,t){let r=e.getCodecsWithUnknownSupport(),i=this.getCodecsSupportInfo(r,t);if(i.length>0)try{e.updateCodecSupport(i)}catch(o){this._onFatalError(o)}}};function cy(n,e){return e.textTrackMode==="html"&&pe.htmlTextDisplayer!==null?new pe.htmlTextDisplayer(n,e.textTrackElement):pe.nativeTextDisplayer!==null?new pe.nativeTextDisplayer(n):null}function fy(n,e,t,r){n.updateRepresentationsDeciperability(i=>{let{representation:o}=i;if(o.contentProtections===void 0)return o.decipherable;let a=o.contentProtections.keyIds;if(a!==void 0)for(let s of a){for(let d of t)if(Se(d,s))return!1;for(let d of e)if(Se(d,s))return!0;for(let d of r)if(Se(d,s))return}return o.decipherable})}function my(n,e){n.updateRepresentationsDeciperability(t=>{var o,a;let r=t.representation;if(r.decipherable===!1)return!1;let i=(a=(o=r.contentProtections)==null?void 0:o.initData)!=null?a:[];for(let s of i)if((e.type===void 0||s.type===e.type)&&e.values.getFormattedValues().every(u=>s.values.some(c=>(u.systemId===void 0||c.systemId===u.systemId)&&Se(c.data,u.data))))return!1;return r.decipherable})}function py(n,{playbackObserver:e,enableRepresentationAvoidance:t,manifest:r,triggerReload:i}){switch(n.type){case"reload":{m.info("Init","Planning reload due to freeze"),i();break}case"flush":{m.info("Init","Flushing buffer due to freeze");let o=e.getReference().getValue(),a=o.position.isAwaitingFuturePosition()?o.position.getWanted():e.getCurrentTime(),s=n.value.relativeSeek,d=a+s;e.setCurrentTime(d);break}case"avoid-representations":{let o=n.value;t&&r.addRepresentationsToAvoid(o),i();break}default:ze(n)}}var gy="<",hy=60,Qf=">",ba=62,qd=45,$f=47,yy=33,Xf=39,Zf=34,Gd=91,Iy=93,by=`\r
|
|
5
|
-
>/= `;function
|
|
1
|
+
"use strict";(()=>{var bg=Object.defineProperty,Sg=Object.defineProperties;var Tg=Object.getOwnPropertyDescriptors;var Cc=Object.getOwnPropertySymbols;var _g=Object.prototype.hasOwnProperty,Eg=Object.prototype.propertyIsEnumerable;var Pc=(n,e,t)=>e in n?bg(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,oe=(n,e)=>{for(var t in e||(e={}))_g.call(e,t)&&Pc(n,t,e[t]);if(Cc)for(var t of Cc(e))Eg.call(e,t)&&Pc(n,t,e[t]);return n},me=(n,e)=>Sg(n,Tg(e));var b={PRODUCTION:0,DEV:1,CURRENT_ENV:0};var S={CURRENT_LEVEL:"NONE"};function _(n){return n==null}var se=class{constructor(){this._listeners={}}addEventListener(e,t,r){let i=this._listeners[e];Array.isArray(i)?i.push(t):this._listeners[e]=[t],r!==void 0&&r.register(()=>{this.removeEventListener(e,t)})}removeEventListener(e,t){if(_(e)){this._listeners={};return}let r=this._listeners[e];if(!Array.isArray(r))return;if(_(t)){delete this._listeners[e];return}let i=r.indexOf(t);i!==-1&&r.splice(i,1),r.length===0&&delete this._listeners[e]}trigger(e,t){let r=this._listeners[e];Array.isArray(r)&&r.slice().forEach(i=>{try{i(t)}catch(o){if(b.CURRENT_ENV===b.DEV)throw o instanceof Error?o:new Error("EventEmitter: listener error");console.error("RxPlayer: EventEmitter error",o instanceof Error?o:null)}})}};var Zn=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope;var kg=typeof window=="undefined"&&!Zn,rn=kg;var zo;Zn?zo=self:rn?zo=global:zo=window;var Z=zo;var Rt=typeof queueMicrotask=="function"?queueMicrotask:function(e){Promise.resolve().then(e,()=>e())};function vs(){if(!rn&&!_(Z.WebKitSourceBuffer)&&Z.WebKitSourceBuffer.prototype.addEventListener===void 0){let e=Z.WebKitSourceBuffer.prototype;for(let t in se.prototype)Object.prototype.hasOwnProperty.call(se.prototype,t)&&(e[t]=se.prototype[t]);e._listeners=[],e._emitUpdate=function(t,r){Rt(()=>{this.trigger(t,r),this.updating=!1,this.trigger("updateend",new Event("updateend"))})},e.appendBuffer=function(t){var r,i;if(this.updating)throw new Error("updating");this.trigger("updatestart",new Event("updatestart")),this.updating=!0;try{this.append(t)}catch(o){(r=this._emitUpdate)==null||r.call(this,"error",o);return}(i=this._emitUpdate)==null||i.call(this,"update",new Event("update"))}}}var Mc={DEFAULT_REQUEST_TIMEOUT:3e4,DEFAULT_CONNECTION_TIMEOUT:15e3,DEFAULT_TEXT_TRACK_MODE:"native",DEFAULT_ENABLE_FAST_SWITCHING:!0,DELTA_POSITION_AFTER_RELOAD:{bitrateSwitch:-.1,trackSwitch:{audio:0,video:0,other:0}},DEFAULT_CODEC_SWITCHING_BEHAVIOR:"continue",DEFAULT_AUDIO_TRACKS_NOT_PLAYABLE_BEHAVIOR:"error",DEFAULT_VIDEO_TRACKS_NOT_PLAYABLE_BEHAVIOR:"error",DEFAULT_AUTO_PLAY:!1,DEFAULT_WANTED_BUFFER_AHEAD:30,DEFAULT_MAX_BUFFER_AHEAD:1/0,DEFAULT_MAX_BUFFER_BEHIND:1/0,DEFAULT_MAX_VIDEO_BUFFER_SIZE:1/0,MAXIMUM_MAX_BUFFER_AHEAD:{text:18e3},MINIMUM_MAX_BUFFER_AHEAD:{text:120},MAXIMUM_MAX_BUFFER_BEHIND:{text:18e3},DEFAULT_BASE_BANDWIDTH:0,INACTIVITY_DELAY:6e4,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:!1,DEFAULT_VIDEO_RESOLUTION_LIMIT:"none",DEFAULT_LIVE_GAP:{DEFAULT:10,LOW_LATENCY:3.5},BUFFER_DISCONTINUITY_THRESHOLD:.2,BITRATE_REBUFFERING_RATIO:1.5,DEFAULT_MAX_MANIFEST_REQUEST_RETRY:4,DEFAULT_CDN_DOWNGRADE_TIME:60,DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:4,INITIAL_BACKOFF_DELAY_BASE:{REGULAR:200,LOW_LATENCY:50},MAX_BACKOFF_DELAY_BASE:{REGULAR:3e3,LOW_LATENCY:1e3},SAMPLING_INTERVAL_MEDIASOURCE:1e3,SAMPLING_INTERVAL_LOW_LATENCY:500,SAMPLING_INTERVAL_NO_MEDIASOURCE:500,ABR_ENTER_BUFFER_BASED_ALGO:10,ABR_EXIT_BUFFER_BASED_ALGO:5,ABR_MINIMUM_TOTAL_BYTES:15e4,ABR_MINIMUM_CHUNK_SIZE:16e3,ABR_STARVATION_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_REGULAR_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_STARVATION_GAP:{DEFAULT:5,LOW_LATENCY:5},OUT_OF_STARVATION_GAP:{DEFAULT:7,LOW_LATENCY:7},ABR_STARVATION_DURATION_DELTA:.1,ABR_FAST_EMA:2,ABR_SLOW_EMA:10,RESUME_GAP_AFTER_SEEKING:{DEFAULT:1.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_NOT_ENOUGH_DATA:{DEFAULT:.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_BUFFERING:{DEFAULT:5,LOW_LATENCY:.5},REBUFFERING_GAP:{DEFAULT:.5,LOW_LATENCY:.2},MINIMUM_BUFFER_AMOUNT_BEFORE_FREEZING:2,UNFREEZING_SEEK_DELAY:6e3,FREEZING_STALLED_DELAY:600,UNFREEZING_DELTA_POSITION:.001,FREEZING_FLUSH_FAILURE_DELAY:{MAXIMUM:2e4,MINIMUM:4e3,POSITION_DELTA:1},SEGMENT_SYNCHRONIZATION_DELAY:1500,MISSING_DATA_TRIGGER_SYNC_DELAY:.1,MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:.15,MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:.4,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:.3,MINIMUM_SEGMENT_SIZE:.001,APPEND_WINDOW_SECURITIES:{START:.2,END:.1},MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:50,TEXT_TRACK_SIZE_CHECKS_INTERVAL:250,BUFFER_PADDING:{audio:1,video:3,other:1},SEGMENT_PRIORITIES_STEPS:[2,4,8,12,18,25],MAX_HIGH_PRIORITY_LEVEL:1,MIN_CANCELABLE_PRIORITY:3,EME_DEFAULT_VIDEO_CODECS:['video/mp4;codecs="avc1.4d401e"','video/mp4;codecs="avc1.42e01e"','video/mp4;codecs="hvc1.1.6.L93.B0"','video/webm;codecs="vp8"'],EME_DEFAULT_AUDIO_CODECS:['audio/mp4;codecs="mp4a.40.2"','audio/webm;codecs="opus"','audio/mp4;codecs="ec-3"'],EME_DEFAULT_WIDEVINE_ROBUSTNESSES:["HW_SECURE_ALL","HW_SECURE_DECODE","HW_SECURE_CRYPTO","SW_SECURE_DECODE","SW_SECURE_CRYPTO"],EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:["3000","2000"],EME_KEY_SYSTEMS:{clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.microsoft.playready.recommendation","com.microsoft.playready","com.chromecast.playready","com.youtube.playready"],fairplay:["com.apple.fps.1_0"]},MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:10,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:200,MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:300,OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:3e3,FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:3e3,DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:3,EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:15,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:1e3,EME_WAITING_DELAY_LOADED_SESSION_EMPTY_KEYSTATUSES:100,FORCED_ENDED_THRESHOLD:8e-4,ADAP_REP_SWITCH_BUFFER_PADDINGS:{video:{before:5,after:5},audio:{before:2,after:2.5},text:{before:0,after:0}},SOURCE_BUFFER_FLUSHING_INTERVAL:500,CONTENT_REPLACEMENT_PADDING:1.2,CACHE_LOAD_DURATION_THRESHOLDS:{video:50,audio:10},STREAM_EVENT_EMITTER_POLL_INTERVAL:250,DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR:.001,BUFFERED_HISTORY_RETENTION_TIME:6e4,BUFFERED_HISTORY_MAXIMUM_ENTRIES:200,MIN_BUFFER_AHEAD:5,UPTO_CURRENT_POSITION_CLEANUP:5,DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_VIDEO_TRACK_SWITCHING_MODE:"reload",DEFAULT_AUDIO_TRACK_SWITCHING_MODE:"seamless",DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:1,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:1e4,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:7e3,FORCE_CANNOT_RELY_ON_REQUEST_MEDIA_KEY_SYSTEM_ACCESS:!1,FORCE_CANNOT_REUSE_MEDIA_KEYS:!1,FORCE_HAS_ISSUES_WITH_HIGH_MEDIA_SOURCE_DURATION:!1,FORCE_IS_SEEKING_APPROXIMATE:!1,FORCE_MEDIA_ELEMENT_FAIL_ON_UNDECIPHERABLE_DATA:!1,FORCE_SHOULD_AWAIT_SET_MEDIA_KEYS:!1,FORCE_SHOULD_FAVOUR_CUSTOM_SAFARI_EME:!1,FORCE_SHOULD_RELOAD_MEDIA_SOURCE_ON_DECIPHERABILITY_UPDATE:!1,FORCE_SHOULD_RENEW_MEDIA_KEY_SYSTEM_ACCESS:!1,FORCE_SHOULD_UNSET_MEDIA_KEYS:!1,FORCE_SHOULD_VALIDATE_METADATA:!1,FORCE_DONT_WAIT_FOR_DATA_BEFORE_LOADED:!1,FORCE_WAIT_FOR_HAVE_ENOUGH_DATA:!1},Ac=Mc;function Cg(n,...e){if(n==null)throw new TypeError("Cannot convert undefined or null to object");let t=Object(n);for(let r of e)for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i]);return t}var G=typeof Object.assign=="function"?Object.assign:Cg;function Rs(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function Nr(n,...e){if(e.length===0)return n;let t=e.shift();if(Rs(n)&&Rs(t))for(let r in t)if(Rs(t[r])){let i=n[r];i===void 0&&(i={},n[r]=i),Nr(i,t[r])}else G(n,{[r]:t[r]});return Nr(n,...e)}var ks=class extends se{constructor(){super(...arguments);this.updated=!1;this._config=Ac}update(t){let r=Nr(this._config,t);this._config=r,this.updated=!0,this.trigger("update",t)}getCurrent(){return this._config}},Pg=new ks,O=Pg;var gt=class n extends Error{constructor(e,t,r){super(e),Object.setPrototypeOf(this,n.prototype),this.name="CustomLoaderError",this.canRetry=t,this.xhr=r}};function Te(n,e,t){if(typeof Array.prototype.findIndex=="function")return n.findIndex(e,t);let r=n.length>>>0;for(let i=0;i<r;i++)if(e.call(t,n[i],i,n))return i;return-1}function ae(){}var Wo=class{constructor(e,t){this._value=e,this._listeners=[],this._isFinished=!1,this._onFinishCbs=[],t!==void 0&&(this._deregisterCancellation=t.register(()=>this.finish()))}getValue(){return this._value}setValue(e){if(this._isFinished){b.CURRENT_ENV===b.DEV&&console.error("Finished shared references cannot be updated");return}if(this._value=e,this._listeners.length===0)return;let t=this._listeners.slice();for(let r of t)try{r.hasBeenCleared||r.trigger(e,r.complete)}catch(i){}}setValueIfChanged(e){e!==this._value&&this.setValue(e)}onUpdate(e,t){let r=()=>{if(t.clearSignal!==void 0&&t.clearSignal.deregister(r),i.hasBeenCleared)return;i.hasBeenCleared=!0;let o=this._listeners.indexOf(i);o>=0&&this._listeners.splice(o,1)},i={trigger:e,complete:r,hasBeenCleared:!1};if(this._listeners.push(i),t.emitCurrentValue===!0&&e(this._value,r),this._isFinished||i.hasBeenCleared){r();return}t.clearSignal.register(r)}waitUntilDefined(e,t){this.onUpdate((r,i)=>{r!==void 0&&(i(),e(this._value))},{clearSignal:t.clearSignal,emitCurrentValue:!0})}_onFinished(e,t){if(t.isCancelled())return ae;let r=()=>{let a=Te(this._onFinishCbs,s=>s.trigger===i);a>=0&&(this._onFinishCbs[a].hasBeenCleared=!0,this._onFinishCbs.splice(a,1))},i=()=>{r(),e()},o=t.register(r);return this._onFinishCbs.push({trigger:i,hasBeenCleared:!1}),o}finish(){this._deregisterCancellation!==void 0&&this._deregisterCancellation(),this._isFinished=!0;let e=this._listeners.slice();for(let t of e)try{t.hasBeenCleared||(t.complete(),t.hasBeenCleared=!0)}catch(r){}if(this._listeners.length=0,this._onFinishCbs.length>0){let t=this._onFinishCbs.slice();for(let r of t)try{r.hasBeenCleared||(r.trigger(),r.hasBeenCleared=!0)}catch(i){}this._onFinishCbs.length=0}}};function vn(n,e,t){let r=new Wo(e(n.getValue()),t);return n.onUpdate(function(o){r.setValue(e(o))},{clearSignal:t}),n._onFinished(()=>{r.finish()},t),r}var W=Wo;var Cs=new W(0);function xc({date:n,timestamp:e}){let t=n-e,r=typeof performance!="undefined"?Date.now()-performance.now():0;Cs.setValueIfChanged(r-t)}var Mg=typeof performance!="undefined"?()=>performance.now()+Cs.getValue():()=>Date.now()+Cs.getValue(),z=Mg;var Ag="NONE",Br=class extends se{constructor(){super(),this.error=ae,this.warn=ae,this.info=ae,this.debug=ae,this._levels={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},this._currentFormat="standard",this._currentLevel=Ag}setLevel(e,t,r){let i,o=this._levels[e];typeof o=="number"?(i=o,this._currentLevel=e):(i=0,this._currentLevel="NONE");let a;if(t==="standard"||t==="full"?a=t:a="standard",a==="full"&&a!==this._currentFormat){let d=z();console.log(String(d.toFixed(2)),"[Init]",`Local-Date: ${Date.now()}`)}this._currentFormat=a;let s=this._currentFormat==="full"?(d,u)=>(c,...l)=>{let f=z();return u(String(f.toFixed(2)),`[${d}]`,c+":",...l.map(m=>typeof m=="object"&&m!==null&&!(m instanceof Error)?wc(m):m))}:(d,u)=>(c,...l)=>u(c+":",...l.map(f=>typeof f=="object"&&f!==null&&!(f instanceof Error)?wc(f):f));if(r===void 0)this.error=i>=this._levels.ERROR?s("error",console.error.bind(console)):ae,this.warn=i>=this._levels.WARNING?s("warn",console.warn.bind(console)):ae,this.info=i>=this._levels.INFO?s("info",console.info.bind(console)):ae,this.debug=i>=this._levels.DEBUG?s("log",console.log.bind(console)):ae;else{let d=u=>i>=this._levels[u]?(c,...l)=>r(u,c,l):ae;this.error=d("ERROR"),this.warn=d("WARNING"),this.info=d("INFO"),this.debug=d("DEBUG")}this.trigger("onLogLevelChange",{level:this._currentLevel,format:this._currentFormat})}getLevel(){return this._currentLevel}getFormat(){return this._currentFormat}hasLevel(e){return this._levels[e]>=this._levels[this._currentLevel]}};function wc(n){let e="";for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){e.length>0&&(e+=" ");let r=n[t];r instanceof Error?e+=`${t}="${JSON.stringify(r==null?void 0:r.toString())}"`:e+=`${t}=${typeof r=="string"?`${JSON.stringify(r)}`:String(r)}`}return e}var xg=new Br,p=xg;var Me=class n extends Error{constructor(e,t,r){let i;switch(r){case"TIMEOUT":i="The request timed out";break;case"ERROR_EVENT":i="An error prevented the request to be performed successfully";break;case"PARSE_ERROR":i="An error happened while formatting the response data";break;case"ERROR_HTTP_CODE":i="An HTTP status code indicating failure was received: "+String(t);break}super(i),Object.setPrototypeOf(this,n.prototype),this.name="RequestError",this.url=e,this.status=t,this.type=r}serialize(){return{url:this.url,status:this.status,type:this.type}}},Qe={TIMEOUT:"TIMEOUT",ERROR_EVENT:"ERROR_EVENT",ERROR_HTTP_CODE:"ERROR_HTTP_CODE",PARSE_ERROR:"PARSE_ERROR"};var Ps=typeof Headers=="function"?Headers:null,Ho=typeof AbortController=="function"?AbortController:null;function qo(n){var f,m;let e;if(!_(n.headers))if(_(Ps))e=n.headers;else{e=new Ps;let g=Object.keys(n.headers);for(let I=0;I<g.length;I++){let h=g[I];e.append(h,n.headers[h])}}p.debug("utils","Fetch",{url:n.url});let t=null,r=!1,i=!1,o=z(),a=_(Ho)?null:new Ho;function s(){if(_(a)){p.warn("utils","Fetch: AbortController API not available.");return}a.abort()}let d;n.timeout!==void 0&&(d=setTimeout(()=>{r=!0,u!==void 0&&clearTimeout(u),s()},n.timeout));let u;n.connectionTimeout!==void 0&&(u=setTimeout(()=>{i=!0,d!==void 0&&clearTimeout(d),s()},n.connectionTimeout));let c=n.cancelSignal.register(function(I){t=I,s()}),l={method:"GET"};if(e!==void 0&&(l.headers=e),l.signal=_(a)?null:a.signal,p.hasLevel("DEBUG")){let g="fetch GET "+n.url;n.timeout!==void 0&&(g+=" to="+String(n.timeout/1e3)),n.connectionTimeout!==void 0&&(g+=" cto="+String(n.connectionTimeout/1e3)),((f=n.headers)==null?void 0:f.Range)!==void 0&&(g+=" Range="+((m=n.headers)==null?void 0:m.Range)),p.debug("utils",g)}return fetch(n.url,l).then(g=>{if(u!==void 0&&clearTimeout(u),g.status>=300)throw p.warn("utils","Fetch: Request HTTP Error",{status:g.status,responseUrl:g.url}),new Me(g.url,g.status,Qe.ERROR_HTTP_CODE);if(_(g.body))throw new Me(g.url,g.status,Qe.PARSE_ERROR);let I=g.headers.get("Content-Length"),h=!_(I)&&!isNaN(+I)?+I:void 0,y=g.body.getReader(),T=0;return v();async function v(){let E=await y.read();if(!E.done&&!_(E.value)){T+=E.value.byteLength;let R=z(),k={url:g.url,currentTime:R,duration:R-o,sendingTime:o,chunkSize:E.value.byteLength,chunk:E.value.buffer,size:T,totalSize:h};return n.onData(k),v()}else if(E.done){d!==void 0&&clearTimeout(d),c();let R=z();return{requestDuration:R-o,receivedTime:R,sendingTime:o,size:T,status:g.status,url:g.url}}return v()}}).catch(g=>{throw t!==null?t:(c(),r?(p.warn("utils","Fetch: Request timed out.",{url:n.url,timeout:n.timeout}),new Me(n.url,0,Qe.TIMEOUT)):i?(p.warn("utils","Fetch: Request connection timed out.",{url:n.url,connectionTimeout:n.connectionTimeout}),new Me(n.url,0,Qe.TIMEOUT)):g instanceof Me?g:(p.warn("utils","Fetch: Request Error",{error:g instanceof Error?g.toString():"Unkwown Error"}),new Me(n.url,0,Qe.ERROR_EVENT)))})}function Ur(){let n=/\[\s*native\s+code\s*\]/;return typeof Z.fetch=="function"&&!_(Ho)&&n.test(Ho.toString())&&!_(Ps)}function x(n){return typeof n=="string"&&n.length>0}var wg="json";function Fr(n){let e={url:n.url,headers:n.headers,responseType:_(n.responseType)?wg:n.responseType,timeout:n.timeout,connectionTimeout:n.connectionTimeout};return new Promise((t,r)=>{let{onProgress:i,cancelSignal:o}=n,{url:a,headers:s,responseType:d,timeout:u,connectionTimeout:c}=e,l=new XMLHttpRequest;l.open("GET",a,!0);let f;u!==void 0&&(l.timeout=u,f=setTimeout(()=>{h(),r(new Me(a,l.status,Qe.TIMEOUT))},u+3e3));let m;if(c!==void 0&&(m=setTimeout(()=>{h(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(new Me(a,l.status,Qe.TIMEOUT))},c)),l.responseType=d,l.responseType==="document"&&l.overrideMimeType("text/xml"),!_(s)){let y=s;for(let T in y)Object.prototype.hasOwnProperty.call(y,T)&&l.setRequestHeader(T,y[T])}let g=z(),I=null;if(o!==void 0&&(I=o.register(function(T){h(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(T)}),o.isCancelled()))return;if(l.onerror=function(){h(),r(new Me(a,l.status,Qe.ERROR_EVENT))},l.ontimeout=function(){h(),r(new Me(a,l.status,Qe.TIMEOUT))},c!==void 0&&(l.onreadystatechange=function(){l.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&clearTimeout(m)}),i!==void 0&&(l.onprogress=function(T){let v=z();i({url:a,duration:v-g,sendingTime:g,currentTime:v,size:T.loaded,totalSize:T.total})}),l.onload=function(T){if(l.readyState===XMLHttpRequest.DONE)if(h(),l.status>=200&&l.status<300){let v=z(),E=l.response instanceof ArrayBuffer?l.response.byteLength:T.total,R=l.status,k=l.responseType,A=x(l.responseURL)?l.responseURL:a,P;if(k==="json"?P=typeof l.response=="object"?l.response:Og(l.responseText):P=l.response,_(P)){r(new Me(a,l.status,Qe.PARSE_ERROR));return}t({status:R,url:A,responseType:k,sendingTime:g,receivedTime:v,requestDuration:v-g,size:E,responseData:P})}else r(new Me(a,l.status,Qe.ERROR_HTTP_CODE))},p.hasLevel("DEBUG")){let y="XHR GET "+a;n.responseType!==void 0&&(y+=" type="+n.responseType),u!==void 0&&(y+=" to="+String(u/1e3)),c!==void 0&&(y+=" cto="+String(c/1e3)),(s==null?void 0:s.Range)!==void 0&&(y+=" Range="+(s==null?void 0:s.Range)),p.debug("utils",y)}l.send();function h(){f!==void 0&&clearTimeout(f),m!==void 0&&clearTimeout(m),I!==null&&I()}})}function Og(n){try{return JSON.parse(n)}catch(e){return null}}var xe=Fr;var Rn=Qe,ft={NETWORK_ERROR:"NETWORK_ERROR",MEDIA_ERROR:"MEDIA_ERROR",ENCRYPTED_MEDIA_ERROR:"ENCRYPTED_MEDIA_ERROR",OTHER_ERROR:"OTHER_ERROR"},Ms={PIPELINE_LOAD_ERROR:"PIPELINE_LOAD_ERROR",PIPELINE_PARSE_ERROR:"PIPELINE_PARSE_ERROR",INTEGRITY_ERROR:"INTEGRITY_ERROR",MANIFEST_PARSE_ERROR:"MANIFEST_PARSE_ERROR",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"MANIFEST_INCOMPATIBLE_CODECS_ERROR",MANIFEST_UPDATE_ERROR:"MANIFEST_UPDATE_ERROR",MANIFEST_UNSUPPORTED_ADAPTATION_TYPE:"MANIFEST_UNSUPPORTED_ADAPTATION_TYPE",MEDIA_STARTING_TIME_NOT_FOUND:"MEDIA_STARTING_TIME_NOT_FOUND",MEDIA_TIME_BEFORE_MANIFEST:"MEDIA_TIME_BEFORE_MANIFEST",MEDIA_TIME_AFTER_MANIFEST:"MEDIA_TIME_AFTER_MANIFEST",MEDIA_TIME_NOT_FOUND:"MEDIA_TIME_NOT_FOUND",NO_PLAYABLE_REPRESENTATION:"NO_PLAYABLE_REPRESENTATION",MEDIA_IS_ENCRYPTED_ERROR:"MEDIA_IS_ENCRYPTED_ERROR",CREATE_MEDIA_KEYS_ERROR:"CREATE_MEDIA_KEYS_ERROR",MEDIA_KEYS_ATTACHMENT_ERROR:"MEDIA_KEYS_ATTACHMENT_ERROR",KEY_ERROR:"KEY_ERROR",KEY_STATUS_CHANGE_ERROR:"KEY_STATUS_CHANGE_ERROR",KEY_UPDATE_ERROR:"KEY_UPDATE_ERROR",KEY_LOAD_ERROR:"KEY_LOAD_ERROR",KEY_LOAD_TIMEOUT:"KEY_LOAD_TIMEOUT",KEY_GENERATE_REQUEST_ERROR:"KEY_GENERATE_REQUEST_ERROR",INCOMPATIBLE_KEYSYSTEMS:"INCOMPATIBLE_KEYSYSTEMS",INVALID_ENCRYPTED_EVENT:"INVALID_ENCRYPTED_EVENT",INVALID_KEY_SYSTEM:"INVALID_KEY_SYSTEM",LICENSE_SERVER_CERTIFICATE_ERROR:"LICENSE_SERVER_CERTIFICATE_ERROR",MULTIPLE_SESSIONS_SAME_INIT_DATA:"MULTIPLE_SESSIONS_SAME_INIT_DATA",BUFFER_APPEND_ERROR:"BUFFER_APPEND_ERROR",BUFFER_FULL_ERROR:"BUFFER_FULL_ERROR",BUFFER_TYPE_UNKNOWN:"BUFFER_TYPE_UNKNOWN",MEDIA_ERR_BLOCKED_AUTOPLAY:"MEDIA_ERR_BLOCKED_AUTOPLAY",MEDIA_ERR_PLAY_NOT_ALLOWED:"MEDIA_ERR_PLAY_NOT_ALLOWED",MEDIA_ERR_NOT_LOADED_METADATA:"MEDIA_ERR_NOT_LOADED_METADATA",MEDIA_ERR_ABORTED:"MEDIA_ERR_ABORTED",MEDIA_ERR_NETWORK:"MEDIA_ERR_NETWORK",MEDIA_ERR_DECODE:"MEDIA_ERR_DECODE",MEDIA_ERR_SRC_NOT_SUPPORTED:"MEDIA_ERR_SRC_NOT_SUPPORTED",MEDIA_ERR_UNKNOWN:"MEDIA_ERR_UNKNOWN",MEDIA_SOURCE_NOT_SUPPORTED:"MEDIA_SOURCE_NOT_SUPPORTED",MEDIA_KEYS_NOT_SUPPORTED:"MEDIA_KEYS_NOT_SUPPORTED",DISCONTINUITY_ENCOUNTERED:"DISCONTINUITY_ENCOUNTERED",NONE:"NONE",NO_AUDIO_VIDEO_TRACKS:"NO_AUDIO_VIDEO_TRACKS"};function mt(n,e){return`${n}: ${e}`}var be=class n extends Error{constructor(e,t,r){super(mt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="EncryptedMediaError",this.type=ft.ENCRYPTED_MEDIA_ERROR,this.code=e,this._originalMessage=t,this.fatal=!1,this.keyStatuses=r.keyStatuses,this.keySystemConfiguration=r.keySystemConfiguration,this.keySystem=r.keySystem}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage,keyStatuses:this.keyStatuses,keySystemConfiguration:this.keySystemConfiguration,keySystem:this.keySystem}}};var re=class n extends Error{constructor(e,t,r){super(mt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="MediaError",this.type=ft.MEDIA_ERROR,this._originalMessage=t,this.code=e,this.fatal=!1,(r==null?void 0:r.tracks)!==void 0&&(r==null?void 0:r.tracks.length)>0&&(this.tracksInfo=r.tracks)}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage,tracks:this.tracksInfo}}};var at=class n extends Error{constructor(e,t){super(mt(e,t.message)),Object.setPrototypeOf(this,n.prototype),this.name="NetworkError",this.type=ft.NETWORK_ERROR,this.url=t.url,this.status=t.status,this.errorType=t.type,this._baseError=t,this.code=e,this.fatal=!1}isHttpError(e){return this.errorType===Rn.ERROR_HTTP_CODE&&this.status===e}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,baseError:this._baseError.serialize()}}};var De=class n extends Error{constructor(e,t){super(mt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="OtherError",this.type=ft.OTHER_ERROR,this.code=e,this.fatal=!1,this._originalMessage=t}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage}}};function on(n){return(n instanceof be||n instanceof re||n instanceof De||n instanceof at)&&Object.keys(ft).indexOf(n.type)>=0}function Ae(n,{defaultCode:e,defaultReason:t}){if(on(n))return n;let r=n instanceof Error?n.toString():t;return new De(e,r)}var He=class n extends Error{constructor(e,t,r){super(t),Object.setPrototypeOf(this,n.prototype),this.name="SourceBufferError",this.errorName=e,this.isBufferFull=r}serialize(){return{errorName:this.name,message:this.message,isBufferFull:this.isBufferFull}}toString(){return`${this.errorName}: ${this.message}`}};var Dg={dashParsers:{wasm:null,js:null},createDebugElement:null,directfile:null,decrypt:null,htmlTextDisplayer:null,htmlTextTracksParsers:{},monothread:null,multithread:null,nativeTextDisplayer:null,nativeTextTracksParsers:{},transports:{}},Kr=Dg;function Go(n){for(let e of n)if(typeof e=="function")e(Kr);else if(!_(e)&&typeof e._addFeature=="function")e._addFeature(Kr);else throw new Error("Unrecognized feature")}var pe=Kr;function q(n,e,t){if(typeof Array.prototype.find=="function")return n.find(e,t);let r=n.length>>>0;for(let i=0;i<r;i++){let o=n[i];if(e.call(t,o,i,n))return o}}var Lg={aa:"aar",ab:"abk",ae:"ave",af:"afr",ak:"aka",am:"amh",an:"arg",ar:"ara",as:"asm",av:"ava",ay:"aym",az:"aze",ba:"bak",be:"bel",bg:"bul",bi:"bis",bm:"bam",bn:"ben",bo:"bod",br:"bre",bs:"bos",ca:"cat",ce:"che",ch:"cha",co:"cos",cr:"cre",cs:"ces",cu:"chu",cv:"chv",cy:"cym",da:"dan",de:"deu",dv:"div",dz:"dzo",ee:"ewe",el:"ell",en:"eng",eo:"epo",es:"spa",et:"est",eu:"eus",fa:"fas",ff:"ful",fi:"fin",fj:"fij",fo:"fao",fr:"fra",fy:"fry",ga:"gle",gd:"gla",gl:"glg",gn:"grn",gu:"guj",gv:"glv",ha:"hau",he:"heb",hi:"hin",ho:"hmo",hr:"hrv",ht:"hat",hu:"hun",hy:"hye",hz:"her",ia:"ina",id:"ind",ie:"ile",ig:"ibo",ii:"iii",ik:"ipk",io:"ido",is:"isl",it:"ita",iu:"iku",ja:"jpn",jv:"jav",ka:"kat",kg:"kon",ki:"kik",kj:"kua",kk:"kaz",kl:"kal",km:"khm",kn:"kan",ko:"kor",kr:"kau",ks:"kas",ku:"kur",kv:"kom",kw:"cor",ky:"kir",la:"lat",lb:"ltz",lg:"lug",li:"lim",ln:"lin",lo:"lao",lt:"lit",lu:"lub",lv:"lav",mg:"mlg",mh:"mah",mi:"mri",mk:"mkd",ml:"mal",mn:"mon",mr:"mar",ms:"msa",mt:"mlt",my:"mya",na:"nau",nb:"nob",nd:"nde",ne:"nep",ng:"ndo",nl:"nld",nn:"nno",no:"nor",nr:"nbl",nv:"nav",ny:"nya",oc:"oci",oj:"oji",om:"orm",or:"ori",os:"oss",pa:"pan",pi:"pli",pl:"pol",ps:"pus",pt:"por",qu:"que",rm:"roh",rn:"run",ro:"ron",ru:"rus",rw:"kin",sa:"san",sc:"srd",sd:"snd",se:"sme",sg:"sag",si:"sin",sk:"slk",sl:"slv",sm:"smo",sn:"sna",so:"som",sq:"sqi",sr:"srp",ss:"ssw",st:"sot",su:"sun",sv:"swe",sw:"swa",ta:"tam",te:"tel",tg:"tgk",th:"tha",ti:"tir",tk:"tuk",tl:"tgl",tn:"tsn",to:"ton",tr:"tur",ts:"tso",tt:"tat",tw:"twi",ty:"tah",ug:"uig",uk:"ukr",ur:"urd",uz:"uzb",ve:"ven",vi:"vie",vo:"vol",wa:"wln",wo:"wol",xh:"xho",yi:"yid",yo:"yor",za:"zha",zh:"zho",zu:"zul"},Oc=Lg;var Ng={alb:"sqi",arm:"hye",baq:"eus",bur:"mya",chi:"zho",cze:"ces",dut:"nld",fre:"fra",geo:"kat",ger:"deu",gre:"ell",ice:"isl",mac:"mkd",mao:"mri",may:"msa",per:"fas",slo:"slk",rum:"ron",tib:"bod",wel:"cym"},Dc=Ng;function Bg(n){if(_(n)||n==="")return"und";let t=(""+n).toLowerCase().split("-")[0],r=Ug(t);return x(r)?r:n}function Ug(n){let e;switch(n.length){case 2:e=Oc[n];break;case 3:e=Dc[n];break}return e}var Lc=Bg;var Vr=Lc;function _e(n,e){if(n.length!==e.length)return!1;if(n===e)return!0;for(let t=n.length-1;t>=0;t--)if(n[t]!==e[t])return!1;return!0}function Jn(n){return Object.keys(n).map(e=>n[e])}var er=typeof Object.values=="function"?Object.values:Jn;var an=["audio","video","text"];function Cn(n){var o,a;let e=n.timeBounds;if(e.timeshiftDepth===null)return(o=e.minimumSafePosition)!=null?o:0;let{maximumTimeData:t}=e,r;if(!e.maximumTimeData.isLinear)r=t.maximumSafePosition;else{let s=z()-t.time;r=t.maximumSafePosition+s/1e3}let i=r-e.timeshiftDepth;return Math.max((a=e.minimumSafePosition)!=null?a:0,i)}function Pn(n){let{maximumTimeData:e}=n.timeBounds;if(!n.isLive||e.livePosition===void 0)return;if(!e.isLinear)return e.livePosition;let t=z()-e.time;return e.livePosition+t/1e3}function Ot(n){let{maximumTimeData:e}=n.timeBounds;if(!e.isLinear)return e.maximumSafePosition;let t=z()-e.time;return e.maximumSafePosition+t/1e3}function Vt(n,e){if(e===void 0)return xs(n).filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1);let t=n.adaptations[e];return t===void 0?[]:t.filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1)}function tr(n,e){let t=null;for(let r=n.periods.length-1;r>=0;r--){let i=n.periods[r];if(As(i,e,t))return i;t=i}}function jo(n,e){let t=e.end;if(t===void 0)return null;let r=q(n.periods,i=>i.end===void 0||t<i.end);return r===void 0?null:r}function As(n,e,t){return e>=n.start&&(n.end===void 0||e<n.end)?!0:e===n.end&&(t===null||t.start>n.end)}function xs(n){let e=n.adaptations;return Jn(e).reduce((t,r)=>_(r)?t:t.concat(r),[])}function Yo(n,e){var r,i;let t={language:(r=n.language)!=null?r:"",normalized:(i=n.normalizedLanguage)!=null?i:"",audioDescription:n.isAudioDescription===!0,id:n.id,representations:(e?n.representations.filter(o=>wt(o)===!0):n.representations).map(Xo),label:n.label};return n.isDub===!0&&(t.dub=!0),t}function Qo(n){var e,t;return{language:(e=n.language)!=null?e:"",normalized:(t=n.normalizedLanguage)!=null?t:"",closedCaption:n.isClosedCaption===!0,id:n.id,label:n.label,forced:n.isForcedSubtitles}}function $o(n,e){let t=n.trickModeTracks!==void 0?n.trickModeTracks.map(i=>{let o=(e?i.representations.filter(s=>wt(s)===!0):i.representations).map(kn),a={id:i.id,representations:o,isTrickModeTrack:!0};return i.isSignInterpreted===!0&&(a.signInterpreted=!0),a}):void 0,r={id:n.id,representations:(e?n.representations.filter(i=>wt(i)===!0):n.representations).map(kn),label:n.label};return n.isSignInterpreted===!0&&(r.signInterpreted=!0),n.isTrickModeTrack===!0&&(r.isTrickModeTrack=!0),t!==void 0&&(r.trickModeTracks=t),r}function Xo(n){let{id:e,bitrate:t,codecs:r,isSpatialAudio:i,isSupported:o,decipherable:a}=n;return{id:e,bitrate:t,codec:r==null?void 0:r[0],isSpatialAudio:i,isCodecSupported:o,decipherable:a}}function kn(n){let{id:e,bitrate:t,frameRate:r,width:i,height:o,codecs:a,hdrInfo:s,isSupported:d,decipherable:u,contentProtections:c}=n;return{id:e,bitrate:t,frameRate:r,width:i,height:o,codec:a==null?void 0:a[0],hdrInfo:s,isCodecSupported:d,decipherable:u,contentProtections:c!==void 0?{keyIds:c.keyIds}:void 0}}function Mn(n){switch(n.type){case"audio":return{type:"audio",track:Yo(n,!1)};case"video":return{type:"video",track:$o(n,!1)};case"text":return{type:"text",track:Qo(n)}}}function wt(n){return n.decipherable===!1?!1:n.isSupported}function Nc(n,e){let{whitelistedKeyIds:t,blacklistedKeyIds:r,delistedKeyIds:i}=e,o=a=>{if(a.contentProtections===void 0)return a.decipherable;let s=a.contentProtections.keyIds;if(s!==void 0)for(let d of s){for(let u of r)if(_e(u,d))return!1;for(let u of t)if(_e(u,d))return!0;for(let u of i)if(_e(u,d))return}return a.decipherable};return n.manifestFormat===0&&n.updateRepresentationsDeciperability(({representation:a})=>o(a)),Uc(n,o)}function Bc(n,e){let t=r=>{var o,a;if(r.decipherable===!1)return!1;let i=(a=(o=r.contentProtections)==null?void 0:o.initData)!=null?a:[];for(let s of i)if((e.type===void 0||s.type===e.type)&&e.values.getFormattedValues().every(u=>s.values.some(c=>(u.systemId===void 0||c.systemId===u.systemId)&&_e(c.data,u.data))))return!1;return r.decipherable};return n.manifestFormat===0&&n.updateRepresentationsDeciperability(({representation:r})=>t(r)),Uc(n,t)}function Uc(n,e){let t=[];for(let r of n.periods){let i=r.adaptations,o=Jn(i).reduce((a,s)=>_(s)?a:a.concat(s),[]);for(let a of o){let s=!0;for(let d of a.representations){let u=e(d);u!==!1&&(s=!1),u!==d.decipherable&&(u===!0?a.supportStatus.isDecipherable=!0:u===void 0&&a.supportStatus.isDecipherable===!1&&(a.supportStatus.isDecipherable=void 0),t.push({manifest:n,period:r,adaptation:a,representation:d}),d.decipherable=u)}s&&(a.supportStatus.isDecipherable=!1)}}return t}function Fc(n,e,t){var r,i;for(let o of Object.keys(e))o!=="periods"&&(n[o]=e[o]);for(let o of t.removedPeriods)for(let a=0;a<n.periods.length;a++)if(n.periods[a].id===o.id){n.periods.splice(a,1);break}for(let o of t.updatedPeriods)for(let a=0;a<n.periods.length;a++){let s=o.period;if(n.periods[a].id===o.period.id){let d=n.periods[a];for(let u of Object.keys(s))u!=="adaptations"&&(d[u]=s[u]);for(let u of o.result.removedThumbnailTracks)for(let c=0;c<d.thumbnailTracks.length;c++)if(d.thumbnailTracks[c].id===u.id){d.thumbnailTracks.splice(c,1);break}for(let u of o.result.updatedThumbnailTracks){let c=u;for(let l=0;l<d.thumbnailTracks.length;l++)if(d.thumbnailTracks[l].id===c.id){let f=d.thumbnailTracks[l];for(let m of Object.keys(c))f[m]=c[m];break}}for(let u of o.result.addedThumbnailTracks)d.thumbnailTracks.push(u);for(let u of o.result.removedAdaptations){let c=u.trackType,l=(r=d.adaptations[c])!=null?r:[];for(let f=0;f<l.length;f++)if(l[f].id===u.id){l.splice(f,1);break}}for(let u of o.result.updatedAdaptations){let c=u.adaptation,l=u.trackType,f=(i=d.adaptations[l])!=null?i:[];for(let m=0;m<f.length;m++)if(f[m].id===c){let g=f[m];for(let I of u.removedRepresentations)for(let h=0;h<g.representations.length;h++)if(g.representations[h].id===I){g.representations.splice(h,1);break}for(let I of u.updatedRepresentations)for(let h=0;h<g.representations.length;h++)if(g.representations[h].id===I.id){let y=g.representations[h];for(let T of Object.keys(I))T!=="decipherable"&&(y[T]=I[T]);break}for(let I of u.addedRepresentations)g.representations.push(I);break}}for(let u of o.result.addedAdaptations){let c=u.type,l=d.adaptations[c];l===void 0?d.adaptations[c]=[u]:l.push(u)}break}}for(let o of t.addedPeriods){for(let a=0;a<n.periods.length;a++)if(n.periods[a].start>o.start){n.periods.splice(a,0,o);break}n.periods.push(o)}}function Kc(n){return new Function(`return (${n}(arguments[0], arguments[1]))`)}function Fe(){let n="",e=-1;return function(){return e++,e>=Number.MAX_SAFE_INTEGER&&(n+="0",e=0),n+String(e)}}var Zo=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="AssertionError"}};function ee(n,e){if(b.DEV===b.CURRENT_ENV&&!n)throw new Zo(e===void 0?"invalid assertion":e)}function Vc(n,e,t="object"){ee(!_(n),`${t} should be an object`);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&ee(typeof n[r]===e[r],`${t} should have property ${r} as a ${e[r]}`)}function we(n){throw new Zo("Unreachable path taken")}var Wc=typeof Z=="object"&&typeof Z.TextDecoder=="function",Fg=typeof Z=="object"&&typeof Z.TextEncoder=="function";function Jo(n){let e=new ArrayBuffer(n.length*2),t=new Uint8Array(e);for(let r=0;r<t.length;r+=2){let i=n.charCodeAt(r/2);t[r]=i&255,t[r+1]=i>>8&255}return t}function ea(n){if(Wc)try{return new TextDecoder("utf-16le").decode(n)}catch(t){let r=t instanceof Error?t:"Unknown Error";p.warn("utils","could not use TextDecoder to parse UTF-16LE, fallbacking to another implementation",r)}let e="";for(let t=0;t<n.length;t+=2)e+=String.fromCharCode((n[t+1]<<8)+n[t]);return e}function Re(n){if(Fg)try{return new TextEncoder().encode(n)}catch(i){let o=i instanceof Error?i:"Unknown Error";p.warn("utils","Could not use TextEncoder to encode string into UTF-8, fallbacking to another implementation",o)}let e,t=encodeURIComponent(n);if(typeof unescape=="function")e=unescape(t);else{let i=/[0-9a-fA-F]/,o=t.length;e="";for(let a=0;a<t.length;a++){let s=!1;if(t[a]==="%"){if(a<=o-6&&t[a+1]==="u"&&i.test(t[a+2])&&i.test(t[a+3])&&i.test(t[a+4])&&i.test(t[a+5])){let d=parseInt(t.substring(a+1,a+6),16);e+=String.fromCharCode(d),s=!0,a+=5}else if(a<=o-3&&i.test(t[a+1])&&i.test(t[a+2])){let d=parseInt(t.substring(a+1,a+3),16);e+=String.fromCharCode(d),s=!0,a+=2}}s||(e+=t[a])}}let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i)&255;return r}function Kg(n){let t="";for(let r=0;r<n.length;r+=16e3){let i=n.subarray(r,r+16e3);t+=String.fromCharCode.apply(null,i)}return t}function zc(n,e){let t=n.toString(16);return t.length>=e?t:new Array(e-t.length+1).join("0")+t}function he(n){if(Wc)try{return new TextDecoder().decode(n)}catch(i){let o=i instanceof Error?i:"Unknown Error";p.warn("utils","could not use TextDecoder to parse UTF-8, fallbacking to another implementation",o)}let e=n;e[0]===239&&e[1]===187&&e[2]===191&&(e=e.subarray(3));let t=Kg(e),r;if(typeof escape=="function")r=escape(t);else{let i=/[A-Za-z0-9*_+-./]/;r="";for(let o=0;o<t.length;o++)if(i.test(t[o]))r+=t[o];else{let a=t.charCodeAt(o);r+=a>=256?"%u"+zc(a,4):"%"+zc(a,2)}}return decodeURIComponent(r)}function st(n){let e=n.length,t=new Uint8Array(e/2);for(let r=0,i=0;r<e;r+=2,i++)t[i]=parseInt(n.substring(r,r+2),16)&255;return t}function Ve(n,e=""){let t="";for(let r=0;r<n.byteLength;r++)t+=(n[r]>>>4).toString(16),t+=(n[r]&15).toString(16),e.length>0&&r<n.byteLength-1&&(t+=e);return t}function ta(n){ee(n.length===16,"GUID length should be 16");let e=n[0],t=n[1],r=n[2],i=n[3],o=n[4],a=n[5],s=n[6],d=n[7],u=new Uint8Array(16);return u[0]=i,u[1]=r,u[2]=t,u[3]=e,u[4]=a,u[5]=o,u[6]=d,u[7]=s,u.set(n.subarray(8,16),8),u}function ws(n,e){let t=e;for(;t<n.length&&n[t]!==0;)t+=1;let r=n.subarray(e,t);return{end:t+1,string:he(r)}}var Vg=Fe(),Os=class{constructor(e,t,r){var o,a,s,d,u;this.id=e.id,this.uniqueId=Vg(),this.shouldBeAvoided=!1,this.bitrate=e.bitrate,this.codecs=[],this.trackType=t,e.isSpatialAudio!==void 0&&(this.isSpatialAudio=e.isSpatialAudio),e.height!==void 0&&(this.height=e.height),e.width!==void 0&&(this.width=e.width),e.mimeType!==void 0&&(this.mimeType=e.mimeType),e.contentProtections!==void 0&&(this.contentProtections=e.contentProtections),e.frameRate!==void 0&&(this.frameRate=e.frameRate),e.hdrInfo!==void 0&&(this.hdrInfo=e.hdrInfo),this.cdnMetadata=e.cdnMetadata,this.index=e.index;let i=this.contentProtections!==void 0;if(t==="audio"||t==="video"){if(e.supplementalCodecs!==void 0){let c=r.isSupported((o=this.mimeType)!=null?o:"",(a=e.supplementalCodecs)!=null?a:"",i);c!==!1&&(this.codecs=[e.supplementalCodecs],this.isSupported=c)}this.isSupported!==!0&&(this.codecs.length>0?this.codecs.push((s=e.codecs)!=null?s:""):(this.codecs=e.codecs===void 0?[]:[e.codecs],this.isSupported=r.isSupported((d=this.mimeType)!=null?d:"",(u=e.codecs)!=null?u:"",i)))}else e.codecs!==void 0&&this.codecs.push(e.codecs),this.isSupported=!0}refreshCodecSupport(e){var s,d;if(this.isSupported!==void 0)return;let t=this.contentProtections!==void 0,r=!1,i=(s=this.mimeType)!=null?s:"",o=(d=this.codecs)!=null?d:[];o.length===0&&(o=[""]);let a=!1;for(let u of o){if(r=e.isSupported(i,u,t),r===!0){this.codecs=[u];break}r===void 0&&(a=!0)}r===!0?this.isSupported=!0:a?this.isSupported=void 0:this.isSupported=!1}getMimeTypeString(){var e,t,r;return`${(e=this.mimeType)!=null?e:""};codecs="${(r=(t=this.codecs)==null?void 0:t[0])!=null?r:""}"`}getEncryptionData(e){var i;let t=this.getAllEncryptionData(),r=[];for(let o=0;o<t.length;o++){let a=!1,s=t[o];for(let d=0;d<s.values.length;d++)if(s.values[d].systemId.toLowerCase()===e.toLowerCase())if(a)r[r.length-1].values.push(s.values[d]);else{let u=(i=this.contentProtections)==null?void 0:i.keyIds;r.push({type:s.type,keyIds:u,values:[s.values[d]]}),a=!0}}return r}getAllEncryptionData(){var t;if(this.contentProtections===void 0||this.contentProtections.initData.length===0)return[];let e=(t=this.contentProtections)==null?void 0:t.keyIds;return this.contentProtections.initData.map(r=>({type:r.type,keyIds:e,values:r.values}))}addProtectionData(e,t,r){let i=!1;if(this.contentProtections===void 0)return this.contentProtections={keyIds:t!==void 0?[t]:[],initData:[{type:e,values:r}]},!0;if(t!==void 0){let a=this.contentProtections.keyIds;if(a===void 0)this.contentProtections.keyIds=[t];else{let s=!1;for(let d of a)_e(d,t)&&(s=!0);s||(p.warn("manifest","found unanounced key id.",{keyId:Ve(t)}),a.push(t))}}let o=this.contentProtections.initData;for(let a=0;a<o.length;a++)if(o[a].type===e){let s=o[a].values;for(let d=0;d<r.length;d++){let u=r[d],c;for(c=0;c<s.length;c++)if(u.systemId===s[c].systemId){if(_e(u.data,s[c].data))break;p.warn("manifest","different init data for the same system ID",{systemId:u.systemId})}c===s.length&&(s.push(u),i=!0)}return i}return this.contentProtections.initData.push({type:e,values:r}),!0}isPlayable(){return wt(this)}getMetadataSnapshot(){return{id:this.id,uniqueId:this.uniqueId,bitrate:this.bitrate,codecs:this.codecs,mimeType:this.mimeType,width:this.width,height:this.height,frameRate:this.frameRate,isSupported:this.isSupported,hdrInfo:this.hdrInfo,contentProtections:this.contentProtections,decipherable:this.decipherable,isCodecSupportedInWebWorker:this.isCodecSupportedInWebWorker}}},zr=Os;var sn=class n{constructor(e,t,r={}){let{trickModeTracks:i}=e,{representationFilter:o,isManuallyAdded:a}=r;this.id=e.id,this.type=e.type,e.isTrickModeTrack!==void 0&&(this.isTrickModeTrack=e.isTrickModeTrack),e.language!==void 0&&(this.language=e.language,this.normalizedLanguage=Vr(e.language)),e.closedCaption!==void 0&&(this.isClosedCaption=e.closedCaption),e.audioDescription!==void 0&&(this.isAudioDescription=e.audioDescription),e.isDub!==void 0&&(this.isDub=e.isDub),e.forcedSubtitles!==void 0&&(this.isForcedSubtitles=e.forcedSubtitles),e.isSignInterpreted!==void 0&&(this.isSignInterpreted=e.isSignInterpreted),e.label!==void 0&&(this.label=e.label),i!==void 0&&i.length>0&&(this.trickModeTracks=i.map(u=>new n(u,t)));let s=e.representations,d=[];this.supportStatus={hasSupportedCodec:!1,hasCodecWithUndefinedSupport:!1,isDecipherable:!1};for(let u=0;u<s.length;u++){let c=new zr(s[u],this.type,t),l=!0;if(!_(o)){let f={id:c.id,bitrate:c.bitrate,codecs:c.codecs,height:c.height,width:c.width,frameRate:c.frameRate,hdrInfo:c.hdrInfo};if(c.contentProtections!==void 0&&(f.contentProtections={},c.contentProtections.keyIds!==void 0)){let m=c.contentProtections.keyIds;f.contentProtections.keyIds=m}l=o(f,{trackType:this.type,language:this.language,normalizedLanguage:this.normalizedLanguage,isClosedCaption:this.isClosedCaption,isDub:this.isDub,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted})}l?(d.push(c),c.isSupported===void 0?(this.supportStatus.hasCodecWithUndefinedSupport=!0,this.supportStatus.hasSupportedCodec===!1&&(this.supportStatus.hasSupportedCodec=void 0)):c.isSupported&&(this.supportStatus.hasSupportedCodec=!0),c.decipherable===void 0?this.supportStatus.isDecipherable===!1&&(this.supportStatus.isDecipherable=void 0):c.decipherable&&(this.supportStatus.isDecipherable=!0)):p.debug("manifest","Filtering Representation due to representationFilter",this.type,`Adaptation: ${this.id}`,`Representation: ${c.id}`,`(${c.bitrate})`)}d.sort((u,c)=>u.bitrate-c.bitrate),this.representations=d,this.manuallyAdded=a===!0}refreshCodecSupport(e){let t=!1,r=!1;for(let i of this.representations)i.refreshCodecSupport(e),i.isSupported===void 0?t=!0:i.isSupported&&(r=!0);r?this.supportStatus.hasSupportedCodec=!0:t?this.supportStatus.hasSupportedCodec=void 0:this.supportStatus.hasSupportedCodec=!1,this.supportStatus.hasCodecWithUndefinedSupport=t}getRepresentation(e){return q(this.representations,({id:t})=>e===t)}getMetadataSnapshot(){let e=[],t=this.representations;for(let r of t)e.push(r.getMetadataSnapshot());return{id:this.id,type:this.type,supportStatus:this.supportStatus,language:this.language,isForcedSubtitles:this.isForcedSubtitles,isClosedCaption:this.isClosedCaption,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted,normalizedLanguage:this.normalizedLanguage,representations:e,label:this.label,isDub:this.isDub}}};var qe=Z,Hc,qc,Gc,jc,Yc,ht=(Yc=(jc=(Gc=(qc=(Hc=qe==null?void 0:qe.MediaSource)!=null?Hc:qe==null?void 0:qe.MozMediaSource)!=null?qc:qe==null?void 0:qe.WebKitMediaSource)!=null?Gc:qe==null?void 0:qe.MSMediaSource)!=null?jc:qe==null?void 0:qe.ManagedMediaSource)!=null?Yc:void 0,Qc=ht!==void 0&&ht===(qe==null?void 0:qe.ManagedMediaSource);var zg=200,na=new Map;function Ds(n,e){if(n.isDummy)return n.FORCED_MEDIA_SOURCE.isTypeSupported(e);if(_(ht))return Zn&&p.error("mse","Cannot request codec support in a worker without MSE."),!1;if(typeof ht.isTypeSupported=="function"){let t=na.get(e);if(t!==void 0)return t;{let r=ht.isTypeSupported(e);return na.size>=zg&&na.clear(),na.set(e,r),r}}return!0}var dn={EdgeChromium:0,Firefox:1,Ie11:2,OtherIeOrEdgePreEdgeChromium:3,SafariDesktop:4,SafariMobile:5,Other:6},It={A1KStb40xx:100,Panasonic:101,PhilipsNetTv:102,PlayStation4:103,PlayStation5:104,Tizen:105,WebOs2021:106,WebOs2022:107,WebOsOther:108,Xbox:109,Other:110},Ge={DEVICES:It,BROWSERS:dn,browser:dn.Other,device:It.Other,isSamsungBrowser:!1};Wg();function Wg(){var n,e,t;rn||(typeof Z.MSInputMethodContext!="undefined"&&typeof document.documentMode!="undefined"?Ge.browser=dn.Ie11:navigator.appName==="Microsoft Internet Explorer"||navigator.appName==="Netscape"&&/(Trident|Edge)\//.test(navigator.userAgent)?Ge.browser=dn.OtherIeOrEdgePreEdgeChromium:navigator.userAgent.toLowerCase().indexOf("edg/")!==-1?Ge.browser=dn.EdgeChromium:navigator.userAgent.toLowerCase().indexOf("firefox")!==-1?Ge.browser=dn.Firefox:typeof navigator.platform=="string"&&/iPad|iPhone|iPod/.test(navigator.platform)?Ge.browser=dn.SafariMobile:(Object.prototype.toString.call(Z.HTMLElement).indexOf("Constructor")>=0||((e=(n=Z.safari)==null?void 0:n.pushNotification)==null?void 0:e.toString())==="[object SafariRemoteNotification]"||/Safari\/(\d+)/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&((t=navigator.vendor)==null?void 0:t.indexOf("Apple"))!==-1&&!/Chrome\/(\d+)/.test(navigator.userAgent)&&!/Chromium\/(\d+)/.test(navigator.userAgent))&&(Ge.browser=dn.SafariDesktop),/SamsungBrowser/.test(navigator.userAgent)&&(Ge.isSamsungBrowser=!0),navigator.userAgent.indexOf("PlayStation 4")!==-1?Ge.device=It.PlayStation4:navigator.userAgent.indexOf("PlayStation 5")!==-1?Ge.device=It.PlayStation5:/Tizen/.test(navigator.userAgent)?Ge.device=It.Tizen:/[Ww]eb[O0]S/.test(navigator.userAgent)?/[Ww]eb[O0]S.TV-2022/.test(navigator.userAgent)||/[Cc]hr[o0]me\/87/.test(navigator.userAgent)?Ge.device=It.WebOs2022:/[Ww]eb[O0]S.TV-2021/.test(navigator.userAgent)||/[Cc]hr[o0]me\/79/.test(navigator.userAgent)?Ge.device=It.WebOs2021:Ge.device=It.WebOsOther:navigator.userAgent.indexOf("NETTV")!==-1&&navigator.userAgent.indexOf("Philips")!==-1?Ge.device=It.PhilipsNetTv:/[Pp]anasonic/.test(navigator.userAgent)?Ge.device=It.Panasonic:navigator.userAgent.indexOf("Xbox")!==-1?Ge.device=It.Xbox:navigator.userAgent.indexOf("Model/a1-kstb40xx")!==-1&&(Ge.device=It.A1KStb40xx))}var V=Ge;function Ls(){let{FORCE_SHOULD_UNSET_MEDIA_KEYS:n}=O.getCurrent();return n||V.browser===V.BROWSERS.Ie11}function An(n){return new Promise(e=>{setTimeout(e,n)})}function Ns(){let{FORCE_SHOULD_AWAIT_SET_MEDIA_KEYS:n}=O.getCurrent();return n||V.device===V.DEVICES.WebOs2021||V.device===V.DEVICES.WebOs2022||V.device===V.DEVICES.WebOsOther}function Bs(n,e,t){let r=n.setMediaKeys(e,t).then(()=>{p.info("DRM","MediaKeys updated with success")}).catch(i=>{if(t===null){p.error("DRM","Could not reset MediaKeys",i instanceof Error?i:"Unknown Error");return}throw p.error("DRM","Could not update MediaKeys",i instanceof Error?i:"Unknown Error"),i});return Ns()?r:Promise.race([r,An(1e3)])}var Dt=new WeakMap,dt={async attach(n,e){let t=Dt.get(n),r=Hg(n,t,e).then(()=>{Dt.set(n,{pendingTask:null,mediaKeysState:e})},()=>{Dt.set(n,{pendingTask:null,mediaKeysState:null})});return Dt.set(n,{pendingTask:r,mediaKeysState:e}),r},getAwaitedState(n){var t;let e=Dt.get(n);return(t=e==null?void 0:e.mediaKeysState)!=null?t:null},async getAttachedMediaKeysState(n){let e=Dt.get(n);return e===void 0?null:e.pendingTask!==null?(await e.pendingTask,this.getAttachedMediaKeysState(n)):e.mediaKeysState},clearMediaKeys(n){let e=Dt.get(n),t=qg(n,e).then(()=>{Dt.set(n,{pendingTask:null,mediaKeysState:null})},()=>{Dt.set(n,{pendingTask:null,mediaKeysState:null})});return Dt.set(n,{pendingTask:t,mediaKeysState:null}),t}};async function $c(n){let e=n.pendingTask;if(!_(e)){p.info("DRM","Awaiting previous MediaKeys attachment operation");try{await n.pendingTask}catch(t){p.info("DRM","previous MediaKeys attachment operation failed",t instanceof Error?t:"Unknown error")}}}async function Hg(n,e,t){if(e!==void 0&&(e.pendingTask!==null&&await $c(e),await(!_(e.mediaKeysState)&&e.mediaKeysState.loadedSessionsStore!==t.loadedSessionsStore?e.mediaKeysState.loadedSessionsStore.closeAllSessions():Promise.resolve()),n.mediaKeys===t.mediaKeys)){p.debug("DRM","Right MediaKeys already set");return}p.info("DRM","Attaching MediaKeys to the media element");try{await Bs(t.emeImplementation,n,t.mediaKeys),p.info("DRM","MediaKeys attached with success")}catch(r){let i=r instanceof Error?r.toString():"Unknown Error";throw new be("MEDIA_KEYS_ATTACHMENT_ERROR","Could not attach the MediaKeys to the media element: "+i,{keyStatuses:void 0,keySystemConfiguration:t.mediaKeySystemAccess.getConfiguration(),keySystem:t.mediaKeySystemAccess.keySystem})}}async function qg(n,e){if(e===void 0||(e.pendingTask!==null&&await $c(e),e.mediaKeysState===null))return;p.info("DRM","Disposing of the current MediaKeys");let{loadedSessionsStore:t}=e.mediaKeysState;return await t.closeAllSessions(),Bs(e.mediaKeysState.emeImplementation,n,null)}async function nr(n){return dt.clearMediaKeys(n)}async function ra(n){if(p.info("DRM","Clearing-up DRM session."),Ls())return p.info("DRM","disposing current MediaKeys."),nr(n);let e=await dt.getAttachedMediaKeysState(n);return e!==null&&e.keySystemOptions.closeSessionsOnStop===!0?(p.info("DRM","closing all current sessions."),e.loadedSessionsStore.closeAllSessions()):(p.info("DRM","Nothing to clear. Returning right away.",{noState:e===null}),Promise.resolve())}function xn(n,e){let t;return new Promise((r,i)=>{if(n.cancellationError!==null)return i(n.cancellationError);let o=!1;t=e(function(d){n.deregister(a),o=!0,r(d)},function(d){n.deregister(a),o=!0,i(d)}),o||n.register(a);function a(s){t!==void 0&&t(),i(s)}})}function un(n,e){return xn(e,t=>{let r=setTimeout(()=>t(),n);return()=>clearTimeout(r)})}var D=class{constructor(){let[e,t]=Gg();this._isUsed=!1,this._trigger=e,this.signal=new Wr(t)}isUsed(){return this._isUsed}linkToSignal(e){let t=e.register(()=>{this.cancel()});return this.signal.register(t),t}cancel(e){if(this._isUsed)return;this._isUsed=!0;let t=e!=null?e:new Ee;this._trigger(t)}static isCancellationError(e){return e instanceof Ee}},Wr=class{constructor(e){this._isCancelled=!1,this.cancellationError=null,this._listeners=[],e(t=>{for(this.cancellationError=t,this._isCancelled=!0;this._listeners.length>0;)try{let r=this._listeners.pop();r==null||r(t)}catch(r){p.error("utils","Error while calling clean up listener",r instanceof Error?r:"Unknown Error")}})}isCancelled(){return this._isCancelled}register(e){return this._isCancelled?(ee(this.cancellationError!==null),e(this.cancellationError),ae):(this._listeners.push(e),()=>this.deregister(e))}deregister(e){for(let t=this._listeners.length-1;t>=0;t--)this._listeners[t]===e&&this._listeners.splice(t,1)}},Ee=class n extends Error{constructor(){super("This task was cancelled."),Object.setPrototypeOf(this,n.prototype),this.name="CancellationError"}};function Gg(){let n=ae;return[function(t){n(t)},function(t){n=t}]}function ia(n){let e=new D;return Promise.race([n.close().then(()=>{e.cancel()}),n.closed.then(()=>{e.cancel()}),t()]);async function t(){try{await un(1e3,e.signal),await r()}catch(i){if(i instanceof Ee)return;let o=i instanceof Error?i.message:"Unknown error made it impossible to close the session";p.error("DRM","Error made it impossible to close the session",`${o}`)}}async function r(){try{await n.update(new Uint8Array(1))}catch(i){if(e.isUsed()||i instanceof Error&&i.message==="The session is already closed.")return;await un(1e3,e.signal)}if(!e.isUsed())throw new Error("Compat: Couldn't know if session is closed")}}var jg=["","webkit","moz","ms"];function Yg(n,e){let t=document.createElement(n.tagName),r="on"+e;return r in t?!0:(t.setAttribute(r,"return;"),typeof t[r]=="function")}function Qg(n,e){return e.filter(t=>Yg(n,t))[0]}function $g(n,e){return n.reduce((t,r)=>t.concat((e===void 0?jg:e).map(i=>i+r)),[])}function Oe(n,e){let t,r=$g(n,e);return(i,o,a)=>{if(!a.isCancelled()){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement)if(typeof t=="undefined"&&(t=Qg(i,r)),x(t))i.addEventListener(t,o),a.register(()=>{t!==void 0&&i.removeEventListener(t,o)});else{p.warn("utils",`element ${i.tagName} does not support any of these events: `+r.join(", "));return}r.forEach(s=>{let d=!1;typeof i.addEventListener=="function"?i.addEventListener(s,o):(d=!0,i["on"+s]=o),a.register(()=>{typeof i.removeEventListener=="function"&&i.removeEventListener(s,o),d&&delete i["on"+s]})})}}}function Xg(n){let e,t=document;_(t.hidden)?_(t.mozHidden)?_(t.msHidden)?_(t.webkitHidden)||(e="webkit"):e="ms":e="moz":e="";let r=x(e)?e+"Hidden":"hidden",i=x(e)?e+"visibilitychange":"visibilitychange",o=document[r],a=new W(!o,n);return wn(document,i,()=>{let s=!document[r];a.setValueIfChanged(s)},n),a}function Xc(n,e){if(n.webkitSupportsPresentationMode===!0&&typeof n.webkitSetPresentationMode=="function"){let i=n.webkitPresentationMode==="picture-in-picture",o=new W({isEnabled:i,pipWindow:null},e);return wn(n,"webkitpresentationmodechanged",()=>{let a=n.webkitPresentationMode==="picture-in-picture";o.setValue({isEnabled:a,pipWindow:null})},e),o}let t=document.pictureInPictureElement===n,r=new W({isEnabled:t,pipWindow:null},e);return wn(n,"enterpictureinpicture",i=>{var o;r.setValue({isEnabled:!0,pipWindow:(o=i.pictureInPictureWindow)!=null?o:null})},e),wn(n,"leavepictureinpicture",()=>{r.setValue({isEnabled:!1,pipWindow:null})},e),r}function Zc(n,e){let t=Xg(e),r,i=new W(!0,e);return e.register(()=>{clearTimeout(r),r=void 0}),t.onUpdate(o,{clearSignal:e}),n.onUpdate(o,{clearSignal:e}),o(),i;function o(){if(clearTimeout(r),r=void 0,n.getValue().isEnabled||t.getValue())i.setValueIfChanged(!0);else{let{INACTIVITY_DELAY:a}=O.getCurrent();r=setTimeout(()=>{i.setValueIfChanged(!1)},a)}}}function Jc(n){var o,a;let e=_(Z.devicePixelRatio)||Z.devicePixelRatio===0?1:Z.devicePixelRatio,t=new W({width:(o=Z.screen)==null?void 0:o.width,height:(a=Z.screen)==null?void 0:a.height,pixelRatio:e},n),r=setInterval(i,2e4);return n.register(function(){clearInterval(r)}),t;function i(){let s=t.getValue();(s.width!==screen.width||s.height!==screen.height||s.pixelRatio!==e)&&t.setValue({width:screen.width,height:screen.height,pixelRatio:e})}}function ef(n,e,t){let r=_(Z.devicePixelRatio)||Z.devicePixelRatio===0?1:Z.devicePixelRatio,i=new W({width:n.clientWidth,height:n.clientHeight,pixelRatio:r},t),o=ae;e.onUpdate(s,{clearSignal:t}),wn(Z,"resize",s,t),wn(n,"enterpictureinpicture",s,t),wn(n,"leavepictureinpicture",s,t);let a=setInterval(s,2e4);return s(),t.register(function(){o(),clearInterval(a)}),i;function s(){o();let d=e.getValue(),{pipWindow:u}=d;if(d.isEnabled)if(_(u)){let l=i.getValue();(l.width!==void 0||l.height!==void 0||l.pixelRatio!==r)&&i.setValue({width:void 0,height:void 0,pixelRatio:r})}else{let l=()=>{c()};u.addEventListener("resize",l),o=()=>{u.removeEventListener("resize",l),o=ae},c()}else{let l=i.getValue();(l.width!==n.clientWidth||l.height!==n.clientHeight||l.pixelRatio!==r)&&i.setValue({width:n.clientWidth,height:n.clientHeight,pixelRatio:r})}function c(){let l=i.getValue();(l.width!==(u==null?void 0:u.width)||l.height!==(u==null?void 0:u.height)||l.pixelRatio!==r)&&i.setValue({width:u==null?void 0:u.width,height:u==null?void 0:u.height,pixelRatio:r})}}}var Kk=Oe(["loadedmetadata"]),Vk=Oe(["timeupdate"]),zk=Oe(["addtrack"]),Wk=Oe(["removetrack"]),rr=Oe(["sourceopen","webkitsourceopen"]),oa=Oe(["sourceclose","webkitsourceclose"]),aa=Oe(["sourceended","webkitsourceended"]),tf=Oe(["update"]),nf=Oe(["removesourcebuffer"]),sa=Oe(["keymessage","message"]),rf=Oe(["keyadded","ready"]),da=Oe(["keyerror","error"]),of=Oe(["keystatuseschange"]),af=Oe(["seeking"]),sf=Oe(["seeked"]),df=Oe(["ended"]);function wn(n,e,t,r){n.addEventListener(e,t),r.register(()=>{n.removeEventListener(e,t)})}function Wt(n){try{let e=n();return typeof e=="object"&&e!==null&&typeof e.then=="function"?e:Promise.resolve(e)}catch(e){return Promise.reject(e)}}var Ht,{MSMediaKeys:Hr}=Z;Hr!==void 0&&Hr.prototype!==void 0&&typeof Hr.isTypeSupported=="function"&&typeof Hr.prototype.createSession=="function"&&(Ht=Hr);var Us=class extends se{constructor(e){super(),this.expiration=NaN,this.keyStatuses=new Map,this._mk=e,this._sessionClosingCanceller=new D,this.closed=new Promise(t=>{this._sessionClosingCanceller.signal.register(()=>t("closed-by-application"))}),this.update=t=>new Promise((r,i)=>{if(this._ss===void 0)return i("MediaKeySession not set.");try{r(this._ss.update(t,""))}catch(o){i(o)}})}generateRequest(e,t){return new Promise(r=>{let i;t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t.buffer),this._ss=this._mk.createSession("video/mp4",i),sa(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"message",o)},this._sessionClosingCanceller.signal),rf(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyadded",o)},this._sessionClosingCanceller.signal),da(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyerror",o)},this._sessionClosingCanceller.signal),r()})}close(){return new Promise(e=>{_(this._ss)||(this._ss.close(),this._ss=void 0),this._sessionClosingCanceller.cancel(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._ss)==null?void 0:e.sessionId)!=null?t:""}},ua=class{constructor(e){if(Ht===void 0)throw new Error("No MSMediaKeys API.");this._mediaKeys=new Ht(e)}_setVideo(e){return Wt(()=>{this._videoElement=e,this._videoElement.msSetMediaKeys!==void 0&&this._videoElement.msSetMediaKeys(this._mediaKeys)})}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new Us(this._mediaKeys)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function Fs(){return{isTypeSupported:(r,i)=>{if(Ht===void 0)throw new Error("No MSMediaKeys API.");return i!==void 0?Ht.isTypeSupported(r,i):Ht.isTypeSupported(r)},createCustomMediaKeys:r=>new ua(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof ua))throw new Error("Custom setMediaKeys is supposed to be called with IE11 custom MediaKeys.");return i._setVideo(r)}}}var ln,{MozMediaKeys:qr}=Z;qr!==void 0&&qr.prototype!==void 0&&typeof qr.isTypeSupported=="function"&&typeof qr.prototype.createSession=="function"&&(ln=qr);function Ks(){return{isTypeSupported:(r,i)=>{if(ln===void 0)throw new Error("No MozMediaKeys API.");return i!==void 0?ln.isTypeSupported(r,i):ln.isTypeSupported(r)},createCustomMediaKeys:r=>{if(ln===void 0)throw new Error("No MozMediaKeys API.");return new ln(r)},setMediaKeys:(r,i)=>Wt(()=>{if(r.mozSetMediaKeys===void 0||typeof r.mozSetMediaKeys!="function")throw new Error("Can't set video on MozMediaKeys.");return r.mozSetMediaKeys(i)})}}var qt=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"],uf=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];function la(n){if(n>=uf.length)throw new Error("Unable to parse base64 string.");let e=uf[n];if(e===255)throw new Error("Unable to parse base64 string.");return e}function ca(n){let e="",t,r=n.length;for(t=2;t<r;t+=3)e+=qt[n[t-2]>>2],e+=qt[(n[t-2]&3)<<4|n[t-1]>>4],e+=qt[(n[t-1]&15)<<2|n[t]>>6],e+=qt[n[t]&63];return t===r+1&&(e+=qt[n[t-2]>>2],e+=qt[(n[t-2]&3)<<4],e+="=="),t===r&&(e+=qt[n[t-2]>>2],e+=qt[(n[t-2]&3)<<4|n[t-1]>>4],e+=qt[(n[t-1]&15)<<2],e+="="),e}function Ct(n){let e=n.length%4,t=n;e!==0&&(p.warn("utils","base64ToBytes: base64 given miss padding",{padding:e}),t+=e===3?"=":e===2?"==":"===");let r=t.indexOf("=");if(r!==-1&&r<t.length-2)throw new Error("Unable to parse base64 string.");let i=t.endsWith("==")?2:t.endsWith("=")?1:0,o=t.length,a=new Uint8Array(o/4*3),s;for(let d=0,u=0;d<o;d+=4,u+=3)s=la(t.charCodeAt(d))<<18|la(t.charCodeAt(d+1))<<12|la(t.charCodeAt(d+2))<<6|la(t.charCodeAt(d+3)),a[u]=s>>16,a[u+1]=s>>8&255,a[u+2]=s&255;return a.subarray(0,a.length-i)}function le(...n){let e=n.length,t=-1,r=0,i;for(;++t<e;)i=n[t],r+=typeof i=="number"?i:i.length;let o=new Uint8Array(r),a=0;for(t=-1;++t<e;)i=n[t],typeof i=="number"?a+=i:i.length>0&&(o.set(i,a),a+=i.length);return o}function fa(n,e){return(n[e+0]<<8)+(n[e+1]<<0)}function ma(n,e){return n[e+0]*65536+n[e+1]*256+n[e+2]}function te(n,e){return n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function lf(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]|0}function $e(n,e){return(n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3])*4294967296+n[e+4]*16777216+n[e+5]*65536+n[e+6]*256+n[e+7]}function Se(n){return new Uint8Array([n>>>8&255,n&255])}function Ce(n){return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function cn(n){let e=n%4294967296,t=(n-e)/4294967296;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function cf(n,e){return(n[e+0]<<0)+(n[e+1]<<8)}function ff(n,e){return n[e+0]+n[e+1]*256+n[e+2]*65536+n[e+3]*16777216}function mf(n){return new Uint8Array([n&255,n>>>8&255])}function Gr(n){return new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255])}function Gt(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer)}function zs(n){return typeof(n==null?void 0:n.webkitGenerateKeyRequest)=="function"}var Vs=class extends se{constructor(e,t){super(),this._vid=e,this._key=t,this.sessionId="",this._closeSession=ae,this.keyStatuses=new Map,this.expiration=NaN;let r=i=>{this.trigger(i.type,i)};this.closed=new Promise(i=>{this._closeSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(o=>{e.removeEventListener(o,r),e.removeEventListener(`webkit${o}`,r)}),i("closed-by-application")}}),["keymessage","message","keyadded","ready","keyerror","error"].forEach(i=>{e.addEventListener(i,r),e.addEventListener(`webkit${i}`,r)})}update(e){return new Promise((t,r)=>{try{if(this._key.indexOf("clearkey")>=0){let i=Gt(e),o=JSON.parse(he(i)),a=Ct(o.keys[0].k),s=Ct(o.keys[0].kid);t(this._vid.webkitAddKey(this._key,a,s,""))}else t(this._vid.webkitAddKey(this._key,e,null,""))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{this._vid.webkitGenerateKeyRequest(this._key,t),r()})}close(){return new Promise(e=>{this._closeSession(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}},pa=class{constructor(e){this._keySystem=e}_setVideo(e){return Wt(()=>{if(!zs(e))throw new Error("Video not attached to the MediaKeys");this._videoElement=e})}createSession(){if(_(this._videoElement))throw new Error("Video not attached to the MediaKeys");return new Vs(this._videoElement,this._keySystem)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function Ws(){return{isTypeSupported:function(r){let i=document.querySelector("video");return _(i)&&(i=document.createElement("video")),!_(i)&&typeof i.canPlayType=="function"?!!i.canPlayType("video/mp4",r):!1},createCustomMediaKeys:r=>new pa(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof pa))throw new Error("Custom setMediaKeys is supposed to be called with old webkit custom MediaKeys.");return i._setVideo(r)}}}function Le(n,e,t){if(typeof String.prototype.startsWith=="function")return n.startsWith(e,t);let r=typeof t=="number"?Math.max(t,0):0;return n.substring(r,r+e.length)===e}function Hs(n,e){let t=Gt(n),r=Gt(e);if(ff(t,0)+4!==t.length)throw new Error("Unsupported WebKit initData.");let o=ea(t),a=o.indexOf("skd://"),s=a>-1?o.substring(a+6):o,d=Jo(s),u=0,c=new Uint8Array(t.byteLength+4+d.byteLength+4+r.byteLength);return c.set(t),u+=t.length,c.set(Gr(d.byteLength),u),u+=4,c.set(d,u),u+=d.byteLength,c.set(Gr(r.byteLength),u),u+=4,c.set(r,u),c}function Lt(){let{WebKitMediaKeys:n}=Z;if(n!==void 0&&typeof n.isTypeSupported=="function"&&typeof n.prototype.createSession=="function"&&typeof HTMLMediaElement.prototype.webkitSetMediaKeys=="function")return n}function Jg(n){return Le(n,"com.apple.fps")}function pf(n,e){return Wt(()=>{if(n.webkitSetMediaKeys===void 0)throw new Error("No webKitMediaKeys API.");n.webkitSetMediaKeys(e)})}var qs=class extends se{constructor(e,t,r){super(),this._serverCertificate=r,this._videoElement=e,this._keyType=t,this._unbindSession=ae,this._closeSession=ae,this.closed=new Promise(i=>{this._closeSession=i}),this.keyStatuses=new Map,this.expiration=NaN}update(e){return new Promise((t,r)=>{if(this._nativeSession===void 0||this._nativeSession.update===void 0||typeof this._nativeSession.update!="function")return r("Unavailable WebKit key session.");try{let i=Gt(e);t(this._nativeSession.update(i))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{var s;let i=this._videoElement;if(((s=i.webkitKeys)==null?void 0:s.createSession)===void 0)throw new Error("No WebKitMediaKeys API.");let o;if(Jg(this._keyType)){if(this._serverCertificate===void 0)throw new Error("A server certificate is needed for creating fairplay session.");o=Hs(t,this._serverCertificate)}else o=t;let a=i.webkitKeys.createSession("video/mp4",o);if(a==null)throw new Error("Impossible to get the key sessions");this._listenEvent(a),this._nativeSession=a,r()})}close(){return new Promise((e,t)=>{if(this._unbindSession(),this._closeSession("closed-by-application"),this._nativeSession===void 0){t("No session to close.");return}this._nativeSession.close(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._nativeSession)==null?void 0:e.sessionId)!=null?t:""}_listenEvent(e){this._unbindSession();let t=r=>{this.trigger(r.type,r)};["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.addEventListener(r,t),e.addEventListener(`webkit${r}`,t)}),this._unbindSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.removeEventListener(r,t),e.removeEventListener(`webkit${r}`,t)})}}},ga=class{constructor(e){let t=Lt();if(t===void 0)throw new Error("No WebKitMediaKeys API.");this._keyType=e,this._mediaKeys=new t(e)}_setVideo(e){if(this._videoElement=e,this._videoElement===void 0)throw new Error("Video not attached to the MediaKeys");return pf(this._videoElement,this._mediaKeys)}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new qs(this._videoElement,this._keyType,this._serverCertificate)}setServerCertificate(e){return this._serverCertificate=e,Promise.resolve(!0)}};function ha(){let n=Lt();if(n===void 0)throw new Error("No WebKitMediaKeys API.");return{isTypeSupported:n.isTypeSupported,createCustomMediaKeys:i=>new ga(i),setMediaKeys:(i,o)=>{if(o===null)return pf(i,o);if(!(o instanceof ga))throw new Error("Custom setMediaKeys is supposed to be called with webkit custom MediaKeys.");return o._setVideo(i)}}}function Gs(){let{FORCE_SHOULD_FAVOUR_CUSTOM_SAFARI_EME:n}=O.getCurrent();return n?!0:(V.browser===V.BROWSERS.SafariDesktop||V.browser===V.BROWSERS.SafariMobile)&&Lt()!==void 0}var jr=class{constructor(e,t,r){this._keyType=e;this._mediaKeys=t;this._configuration=r}get keySystem(){return this._keyType}createMediaKeys(){return new Promise(e=>e(this._mediaKeys))}getConfiguration(){return this._configuration}};function js(n){var o;let e,t,r=eh,i;if(n==="standard"||n==="auto"&&!Gs()){if(rn||_(navigator.requestMediaKeySystemAccess))return null;e=(...a)=>navigator.requestMediaKeySystemAccess(...a),t=Oe(["encrypted"]),i="standard"}else{let a,s;if(n==="webkit"&&Lt()!==void 0){let d=ha();t=gf(),a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(zs((o=Z.HTMLVideoElement)==null?void 0:o.prototype)){t=Oe(["needkey"]);let d=Ws();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="older-webkit"}else if(Lt()!==void 0){t=gf();let d=ha();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(V.browser===V.BROWSERS.Ie11&&Ht!==void 0){t=Oe(["encrypted","needkey"]);let d=Fs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="ms"}else if(ln!==void 0){t=Oe(["encrypted","needkey"]);let d=Ks();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="moz"}else{t=Oe(["encrypted","needkey"]);let d=Z.MediaKeys,u=()=>{if(d===void 0)throw new re("MEDIA_KEYS_NOT_SUPPORTED","No `MediaKeys` implementation found in the current browser.");if(typeof d.isTypeSupported=="undefined"){let c="This browser seems to be unable to play encrypted contents currently.Note: Some browsers do not allow decryption in some situations, like when not using HTTPS.";throw new Error(c)}};a=c=>(u(),ee(typeof d.isTypeSupported=="function"),d.isTypeSupported(c)),s=c=>(u(),new d(c)),i="unknown"}e=function(d,u){if(!a(d))return Promise.reject(new Error("Unsupported key type"));for(let c=0;c<u.length;c++){let l=u[c],{videoCapabilities:f,audioCapabilities:m,initDataTypes:g,distinctiveIdentifier:I}=l,h=!0;if(h=h&&(_(g)||g.some(y=>y==="cenc")),h=h&&I!=="required",h){let y={initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]};f!==void 0&&(y.videoCapabilities=f),m!==void 0&&(y.audioCapabilities=m);let T=s(d);return Promise.resolve(new jr(d,T,y))}}return Promise.reject(new Error("Unsupported configuration"))}}return{requestMediaKeySystemAccess:e,onEncrypted:t,setMediaKeys:r,implementation:i}}function gf(){let n=Oe(["needkey"],void 0);return(t,r,i)=>{n(t,o=>{let a=G(o,{forceSessionRecreation:!0});r(a)},i)}}function eh(n,e){try{let t;return typeof n.setMediaKeys=="function"?t=n.setMediaKeys(e):typeof n.webkitSetMediaKeys=="function"?t=n.webkitSetMediaKeys(e):typeof n.mozSetMediaKeys=="function"?t=n.mozSetMediaKeys(e):typeof n.msSetMediaKeys=="function"&&e!==null&&(t=n.msSetMediaKeys(e)),typeof t=="object"&&t!==null&&typeof t.then=="function"?t:Promise.resolve(t)}catch(t){return Promise.reject(t)}}function Nt(n,e){let t=n.length,r=0;for(;r+8<=t;){let i=te(n,r);if(i===0)i=t-r;else if(i===1){if(r+16>t)return-1;i=$e(n,r+8)}if(isNaN(i)||i<=0)return-1;if(te(n,r+4)===e)return r+i<=t?r:-1;r+=i}return-1}function Ia(n){let e=0,t=[],r=null;for(;e<=n.length;){if(e===n.length){r=null;break}r=n.subarray(e,1/0);let i=Nt(r,1836019558);if(i<0)break;let o=te(n,i+e),a=e+i+o;if(a>n.length)break;let s=Nt(r,1835295092);if(s<0)break;let d=te(n,s+e),u=e+s+d;if(u>n.length)break;let c=Math.max(a,u),l=n.subarray(e,c);t.push(l),e=c}return t.length===0?[null,r]:[t,r]}function th(n,e,t){return new Uint8Array(Array.prototype.slice.call(n,e,t))}function nh(n,e,t){return n.slice(e,t)}var Ys=typeof Uint8Array.prototype.slice=="function"?nh:th;function Qs(n,e){let t=n;for(let r of e){let i=ke(t,r);if(i===null)return null;t=i}return t}function ke(n,e){let t=Xe(n,e);return t!==null?n.subarray(t[1],t[2]):null}function hf(n,e){let t=[],r=n;for(;;){let i=Xe(r,e);if(i===null)return t;ee(i[2]!==0&&r.length!==0),t.push(r.subarray(i[1],i[2])),r=r.subarray(i[2])}}function $s(n,e){let t=Xe(n,e);return t!==null?n.subarray(t[0],t[2]):null}function Xe(n,e){let t=n.length,r=0,i,o=0,a;for(;r+8<=t;){if(a=r,o=te(n,a),a+=4,i=te(n,a),a+=4,o===0)o=t-r;else if(o===1){if(a+8>t)return null;o=$e(n,a),a+=8}if(o<0)throw new Error("ISOBMFF: Size out of range");if(i===e)return e===1970628964&&(a+=16),[r,a,r+o];r+=o}return null}function On(n,e,t,r,i){let o=n.length,a;for(let s=0;s<o;s+=a){let d=s;a=te(n,d),d+=4;let u=te(n,d);if(d+=4,a===0)a=o-s;else if(a===1){if(d+8>o)return;a=$e(n,d),d+=8}if(u===1970628964&&d+16<=o&&te(n,d)===e&&te(n,d+4)===t&&te(n,d+8)===r&&te(n,d+12)===i)return d+=16,n.subarray(d,s+a)}}function Xs(n){let e=n.length;if(e<8)return p.warn("isobmff","box inferior to 8 bytes, cannot find offsets"),null;let t=0,r=te(n,t);t+=4;let i=te(n,t);if(t+=4,r===0)r=e;else if(r===1){if(t+8>e)return p.warn("isobmff","box too short, cannot find offsets"),null;r=$e(n,t),t+=8}if(r<0)throw new Error("ISOBMFF: Size out of range");return i===1970628964&&(t+=16),[0,t,r]}function ya(n){let e=0,t=ke(n,1836019574);if(t===null)return[];let r=[];for(;e<t.length;){let i;try{i=Xe(t,1886614376)}catch(s){let d=s instanceof Error?s:"";return p.warn("isobmff","Error while removing PSSH from ISOBMFF",d),r}if(i===null)return r;let o=Ys(t,i[0],i[2]),a=ba(o,i[1]-i[0]);a!==void 0&&r.push({systemId:a,data:o}),t[i[0]+4]=102,t[i[0]+5]=114,t[i[0]+6]=101,t[i[0]+7]=101,e=i[2]}return r}function ba(n,e){if(n[e]>1){p.warn("isobmff","un-handled PSSH version");return}let t=e+4;if(t+16>n.length)return;let r=Ys(n,t,t+16);return Ve(r)}var Yr=Math.pow(2,32)-1;var Zs={};function If(n){if(Zs[n]!==void 0)return Zs[n];let e=Re(n);return Zs[n]=e,e}function Ie(n,e){let t=e.length+8;return t<=Yr?le(Ce(t),If(n),e):le(Ce(1),If(n),cn(t+8),e)}function ze(n,e){return Ie(n,le(...e))}function Qr(n){let e=ke(n,1836019558);return e===null?null:ke(e,1953653094)}function Js(n){return hf(n,1836019558).reduce((t,r)=>{let i=ke(r,1953653094);return i!==null&&t.push(i),t},[])}function Dn(n){return ke(n,1835295092)}function ed(n){let e=ke(n,1836019574);if(e===null)return null;let t=ke(e,1953653099);return t===null?null:ke(t,1835297121)}function yf(n,e=0){return ke(n.subarray(e),1701671783)}function $r(n){let e=cf(n,8),t=ea(n.subarray(10,e+10)),i=new DOMParser().parseFromString(t,"application/xml").querySelector("KID");if(i===null)throw new Error("Cannot parse PlayReady private data: invalid XML");let o=i.textContent===null?"":i.textContent,a=ta(Ct(o));return Ve(a).toLowerCase()}function Xr(n,e){let t=Xe(n,1936286840);if(t===null)return null;let r=e,i=t[2]-t[0],o=t[1],a=n[o];o+=8;let s=te(n,o);o+=4;let d;if(a===0)d=te(n,o),o+=4,r+=te(n,o)+i,o+=4;else if(a===1)d=$e(n,o),o+=8,r+=$e(n,o)+i,o+=8;else return null;let u=[];o+=2;let c=fa(n,o);for(o+=2;--c>=0;){let l=te(n,o);o+=4;let f=(l&2147483648)>>>31,m=l&2147483647;if(f===1)throw new Error("sidx with reference_type `1` not yet implemented");let g=te(n,o);o+=4,o+=4,u.push({time:d,duration:g,timescale:s,range:[r,r+m-1]}),d+=g,r+=m}return u}function Zr(n){let e=Qr(n);if(e===null)return;let t=ke(e,1952867444);if(t===null)return;let r=t[0];if(r===1)return $e(t,4);if(r===0)return te(t,4)}function bf(n){let e=ke(n,1952868452);if(e===null)return;let t=1,r=ma(e,t);t+=3;let i=(r&1)>0,o=(r&2)>0;return(r&8)>0?(t+=4,i&&(t+=8),o&&(t+=4),te(e,t)):void 0}function Sf(n){let e=Js(n),t=[];for(let r of e){let i=ke(r,1953658222);if(i===null)continue;let o=0,a=i[o];if(o+=1,a>1)return[];let s=ma(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=bf(r),u===void 0))return[];let c=(s&1)>0,l=(s&4)>0,f=(s&512)>0,m=(s&1024)>0,g=(s&2048)>0,I=te(i,o);o+=4,c&&(o+=4),l&&(o+=4);let h=I;for(;h-- >0;){let y,T,v,E;d?(y=te(i,o),o+=4):y=u,f&&(T=te(i,o),o+=4),m&&(v=te(i,o),o+=4),g&&(E=a===0?te(i,o):lf(i,o),o+=4),t.push({duration:y,compositionTimeOffset:E,size:T,flags:v})}}return t}function Jr(n){let e=Js(n);if(e.length===0)return;let t=0;for(let r of e){let i=ke(r,1953658222);if(i===null)return;let o=0,a=i[o];if(o+=1,a>1)return;let s=ma(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=bf(r),u===void 0))return;let c=(s&1)>0,l=(s&4)>0,f=(s&512)>0,m=(s&1024)>0,g=(s&2048)>0,I=te(i,o);o+=4,c&&(o+=4),l&&(o+=4);let h=I,y=0;for(;h-- >0;)d?(y+=te(i,o),o+=4):y+=u,f&&(o+=4),m&&(o+=4),g&&(o+=4);t+=y}return t}function ei(n){let e=ed(n);if(e===null)return;let t=ke(e,1835296868);if(t===null)return;let r=0,i=t[r];if(r+=4,i===1)return te(t,r+16);if(i===0)return te(t,r+8)}function td(n){let e=n.length;if(e<4)throw new Error("Cannot update box length: box too short");let t=te(n,0);if(t===0)if(e>Yr){let r=new Uint8Array(e+8);return r.set(Ce(1),0),r.set(n.subarray(4,8),4),r.set(cn(e+8),8),r.set(n.subarray(8,e),16),r}else return n.set(Ce(e),0),n;else if(t===1){if(e<16)throw new Error("Cannot update box length: box too short");return n.set(cn(e),8),n}else{if(e<=Yr)return n.set(Ce(e),0),n;{let r=new Uint8Array(e+8);return r.set(Ce(1),0),r.set(n.subarray(4,8),4),r.set(cn(e+8),8),r.set(n.subarray(8,e),16),r}}}function Tf(n){let e=[],t=0;for(;t<n.length;){let r=yf(n,t);if(r===null)break;let i=r.length;t+=i;let o=r[0];if(o!==0)p.warn("isobmff","EMSG version "+o.toString()+" not supported.");else{let a=4,{end:s,string:d}=ws(r,a);a=s;let{end:u,string:c}=ws(r,a);a=u;let l=te(r,a);a+=4;let f=te(r,a);a+=4;let m=te(r,a);a+=4;let g=te(r,a);a+=4;let I=r.subarray(a,i),h={schemeIdUri:d,value:c,timescale:l,presentationTimeDelta:f,eventDuration:m,id:g,messageData:I};e.push(h)}}if(e.length!==0)return e}function _f(n){let e=Qs(n,[1836019574,1953653099,1835297121,1835626086,1937007212,1937011556]);if(e===null)return null;let t=e.subarray(8),r=ke(t,1701733238),i=0;if(r===null?(i=28,r=ke(t,1701733217)):i=78,r===null)return null;let o=Qs(r.subarray(i),[1936289382,1935894633,1952804451]);if(o===null||o.byteLength<24)return null;let a=o.subarray(8,24);return a.every(s=>s===0)?null:a}var Sa=te(Re("pssh"),0);function rh(n){p.info("DRM","Trying to move CENC PSSH from init data at the end of it.");let e=!1,t=new Uint8Array,r=new Uint8Array,i=0;for(;i<n.length;){if(n.length<i+8||te(n,i+4)!==Sa)throw p.warn("DRM","unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let o=te(new Uint8Array(n),i);if(i+o>n.length)throw p.warn("DRM","unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let a=n.subarray(i,i+o);if(n[i+12]===16&&n[i+13]===119&&n[i+14]===239&&n[i+15]===236&&n[i+16]===192&&n[i+17]===178&&n[i+18]===77&&n[i+19]===2&&n[i+20]===172&&n[i+21]===227&&n[i+22]===60&&n[i+23]===30&&n[i+24]===82&&n[i+25]===226&&n[i+26]===251&&n[i+27]===75){let s=Xs(a),d=s===null?void 0:a[s[1]];p.info("DRM","CENC PSSH found with version",d),d===void 0?p.warn("DRM","could not read version of CENC PSSH"):e===(d===1)?t=le(t,a):d===1?(p.warn("DRM","cenc version 1 encountered, removing every other cenc pssh box."),t=a,e=!0):p.warn("DRM","filtering out cenc pssh box with wrong version",d)}else r=le(r,a);i+=o}if(i!==n.length)throw p.warn("DRM","unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");return le(r,t)}function ti(n,e,t){p.debug("DRM","Calling generateRequest on the MediaKeySession");let r;try{r=rh(t)}catch(o){r=t}let i=e!=null?e:"";return n.generateRequest(i,r).catch(o=>{if(i!==""||!(o instanceof TypeError))throw o;return p.warn("DRM",'error while calling `generateRequest` with an empty initialization data type. Retrying with a default "cenc" value.',o),n.generateRequest("cenc",r)})}function ih(n){let e=[],t=0;for(;t<n.length;){if(n.length<t+8||te(n,t+4)!==Sa)return p.warn("DRM","Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let r=te(new Uint8Array(n),t);if(t+r>n.length)return p.warn("DRM","Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let i=n.subarray(t,t+r),a={systemId:ba(i,8),data:i};oh(e,a)?p.warn("DRM","Duplicated PSSH found in initialization data, removing it."):e.push(a),t+=r}return t!==n.length?(p.warn("DRM","Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}]):e}function oh(n,e){for(let t=0;t<n.length;t++){let r=n[t];if((e.systemId===void 0||r.systemId===void 0||e.systemId===r.systemId)&&_e(e.data,r.data))return!0}return!1}function Ta(n){let{initData:e,initDataType:t,forceSessionRecreation:r}=n;if(_(e))return p.warn("DRM","No init data found on media encrypted event."),null;let i=new Uint8Array(e),o=ih(i);return{type:t,values:o,forceSessionRecreation:r}}var ah=100;async function ni(n,e){p.info("DRM","Load persisted session",{sessionId:e});let t=await n.load(e);return!t||n.keyStatuses.size>0?t:new Promise(r=>{n.addEventListener("keystatuseschange",o);let i=setTimeout(o,ah);function o(){a(),r(t)}function a(){clearTimeout(i),n.removeEventListener("keystatuseschange",o)}})}var _a=js;function J(n,e,t){if(typeof Array.prototype.includes=="function")return n.includes(e,t);let r=n.length>>>0;if(r===0)return!1;let i=t|0,o=i>=0?Math.min(i,r-1):Math.max(r+i,0),a=(s,d)=>s===d||typeof s=="number"&&typeof d=="number"&&isNaN(s)&&isNaN(d);for(;o<r;){if(a(n[o],e))return!0;o++}return!1}function ri(n){if(n.sessionId==="")return!1;let e=n.keyStatuses,t=[];return e.forEach(r=>{t.push(r)}),t.length<=0?(p.debug("DRM","isSessionUsable: MediaKeySession given has an empty keyStatuses",{sessionId:n.sessionId}),!1):J(t,"expired")?(p.debug("DRM","isSessionUsable: MediaKeySession given has an expired key",{sessionId:n.sessionId}),!1):J(t,"internal-error")?(p.debug("DRM","isSessionUsable: MediaKeySession given has a key with an internal-error",{sessionId:n.sessionId}),!1):(p.debug("DRM","isSessionUsable: MediaKeySession is usable",{sessionId:n.sessionId}),!0)}function nd(n,e,t,r){let{loadedSessionsStore:i,persistentSessionsStore:o}=n;return t==="temporary"?Ef(i,e):o===null?(p.warn("DRM","Cannot create persistent MediaKeySession, PersistentSessionsStore not created."),Ef(i,e)):sh(i,o,e,r)}function Ef(n,e){p.info("DRM","Creating a new temporary session");let t=n.createSession(e,"temporary");return Promise.resolve({type:"created-session",value:t})}async function sh(n,e,t,r){if(r.cancellationError!==null)throw r.cancellationError;p.info("DRM","Creating persistent MediaKeySession");let i=n.createSession(t,"persistent-license"),o=e.getAndReuse(t);if(o===null)return{type:"created-session",value:i};try{let s=await n.loadPersistentSession(i.mediaKeySession,o.sessionId);if(!s){p.warn("DRM","No data stored for the loaded session",{sessionId:o.sessionId}),e.delete(o.sessionId),n.removeSessionWithoutClosingIt(i.mediaKeySession);let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}return s&&ri(i.mediaKeySession)?(e.add(t,t.keyIds,i.mediaKeySession),p.info("DRM","Succeeded to load persistent session."),{type:"loaded-persistent-session",value:i}):(p.warn("DRM","Previous persistent session not usable anymore."),a())}catch(s){return p.warn("DRM","Unable to load persistent session: "+(s instanceof Error?s.toString():"Unknown Error")),a()}async function a(){if(r.cancellationError!==null)throw r.cancellationError;p.info("DRM","Removing previous persistent session.");let s=e.get(t);s!==null&&e.delete(s.sessionId);try{await n.closeSession(i.mediaKeySession)}catch(u){if(i.mediaKeySession.sessionId!=="")throw u;n.removeSessionWithoutClosingIt(i.mediaKeySession)}if(r.cancellationError!==null)throw r.cancellationError;let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}}async function rd(n,e){if(e<0||e>=n.getLength())return;p.info("DRM","LSS cache limit exceeded",{limit:e,length:n.getLength()});let t=[],r=n.getAll().slice(),i=r.length-e;for(let o=0;o<i;o++){let a=r[o];t.push(n.closeSession(a.mediaKeySession))}await Promise.all(t)}async function id(n,e,t,r,i){let o=null,{loadedSessionsStore:a,persistentSessionsStore:s}=e,d=a.reuse(n);if(d!==null){if(o=d.mediaKeySession,ri(o))return p.info("DRM","Reuse loaded session",{sessionId:o.sessionId}),{type:"loaded-open-session",value:{mediaKeySession:o,sessionType:d.sessionType,keySessionRecord:d.keySessionRecord}};s!==null&&d.mediaKeySession.sessionId!==""&&s.delete(d.mediaKeySession.sessionId)}if(o!==null&&(await a.closeSession(o),i.cancellationError!==null)||(await rd(a,r<=0?r:r-1),i.cancellationError!==null))throw i.cancellationError;let u=await nd(e,n,t,i);return{type:u.type,value:{mediaKeySession:u.value.mediaKeySession,sessionType:u.value.sessionType,keySessionRecord:u.value.keySessionRecord}}}function od(){let{FORCE_CANNOT_REUSE_MEDIA_KEYS:n}=O.getCurrent();return!n&&V.device!==V.DEVICES.WebOs2021&&V.device!==V.DEVICES.WebOs2022&&V.device!==V.DEVICES.WebOsOther&&V.device!==V.DEVICES.PhilipsNetTv&&V.device!==V.DEVICES.Panasonic&&V.device!==V.DEVICES.A1KStb40xx}function vf(n){let{FORCE_CANNOT_RELY_ON_REQUEST_MEDIA_KEY_SYSTEM_ACCESS:e}=O.getCurrent();return!(e||(V.browser===V.BROWSERS.EdgeChromium||V.browser===V.BROWSERS.Firefox)&&n.indexOf("playready")!==-1)}var Rf='<WRMHEADER xmlns="http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader" version="4.0.0.0"><DATA><PROTECTINFO><KEYLEN>16</KEYLEN><ALGID>AESCTR</ALGID></PROTECTINFO><KID>ckB07BNLskeUq0qd83fTbA==</KID><DS_ID>yYIPDBca1kmMfL60IsfgAQ==</DS_ID><CUSTOMATTRIBUTES xmlns=""><encryptionref>312_4024_2018127108</encryptionref></CUSTOMATTRIBUTES><CHECKSUM>U/tsUYRgMzw=</CHECKSUM></DATA></WRMHEADER>';function kf(n){let e=Jo(n),t=mf(e.length),r=new Uint8Array([1,0]),i=new Uint8Array([1,0]),o=Gr(e.length+6),a=le(o,i,r,t,e),s=st("9a04f07998404286ab92e65be0885f95");return dh(a,s)}function dh(n,e){let t=Re("pssh"),r=new Uint8Array([0,0,0,0]),i=Ce(n.length),o=Ce(32+n.length);return le(o,t,r,e,i,n)}function ad(n){let{FORCE_SHOULD_RENEW_MEDIA_KEY_SYSTEM_ACCESS:e}=O.getCurrent();return e?!0:n.indexOf("playready")!==-1&&(V.browser===V.BROWSERS.Ie11||V.browser===V.BROWSERS.EdgeChromium||V.browser===V.BROWSERS.Firefox)}function uh(n,e){let{mimeType:t,codecs:r}=Ea(n),{mimeType:i,codecs:o}=Ea(e);if(t!==i||r===""||o==="")return!1;let a=r.split(".")[0];a=a==="hev1"?"hvc1":a;let s=o.split(".")[0];return s=s==="hev1"?"hvc1":s,a===s}var lh=7;function Ea(n){var i;let[e,...t]=n.split(";"),r=(i=q(t,o=>Le(o,"codecs=")))!=null?i:"";return r=r.substring(lh),r[0]==='"'&&(r=r.substring(1,r.length-1)),{mimeType:e,codecs:r}}var va=uh;function ir(n,e){return typeof Array.prototype.flatMap=="function"?n.flatMap(e):n.reduce((t,r)=>{let i=e(r);return Array.isArray(i)?(t.push(...i),t):(t.push(i),t)},[])}function ch(n,e){var c,l,f,m,g,I,h,y,T,v;if(n.label!==e.label)return!1;let t=(c=e.distinctiveIdentifier)!=null?c:"optional",r=(l=n.distinctiveIdentifier)!=null?l:"optional";if(t!==r)return!1;let i=(f=e.persistentState)!=null?f:"optional",o=(m=n.persistentState)!=null?m:"optional";if(i!==o)return!1;let a=(g=e.initDataTypes)!=null?g:[],s=(I=n.initDataTypes)!=null?I:[];if(!Pf(s,a))return!1;let d=(h=e.sessionTypes)!=null?h:[],u=(y=n.sessionTypes)!=null?y:[];if(!Pf(u,d))return!1;for(let E of["audioCapabilities","videoCapabilities"]){let R=(T=n[E])!=null?T:[],k=(v=e[E])!=null?v:[];if(!R.every(P=>{var M,N,U,L,B,C;for(let w=0;w<k.length;w++){let F=k[w];if(((M=F.robustness)!=null?M:"")===((N=P.robustness)!=null?N:"")||((U=F.encryptionScheme)!=null?U:null)===((L=P.encryptionScheme)!=null?L:null)||((B=F.robustness)!=null?B:"")===((C=P.robustness)!=null?C:""))return!0}return!1}))return!1}return!0}function fh(n){let{EME_KEY_SYSTEMS:e}=O.getCurrent();for(let t of Object.keys(e))if(J(e[t],n))return t}function mh(n){let{keyName:e,keyType:t,keySystemOptions:r}=n,i,o="optional",a="optional";Array.isArray(r.wantedSessionTypes)?(i=r.wantedSessionTypes,J(r.wantedSessionTypes,"persistent-license")&&!_(r.persistentLicenseConfig)&&(o="required")):_(r.persistentLicenseConfig)?i=["temporary"]:(o="required",i=["persistent-license"]),_(r.persistentState)||(o=r.persistentState),_(r.distinctiveIdentifier)||(a=r.distinctiveIdentifier);let{EME_DEFAULT_AUDIO_CODECS:s,EME_DEFAULT_VIDEO_CODECS:d,EME_DEFAULT_WIDEVINE_ROBUSTNESSES:u,EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:c}=O.getCurrent(),l,f,{audioCapabilitiesConfig:m,videoCapabilitiesConfig:g}=r;if((m==null?void 0:m.type)==="full")l=m.value;else{let h;(m==null?void 0:m.type)==="robustness"?h=m.value:e==="widevine"?h=u:t==="com.microsoft.playready.recommendation"?h=c:h=[],h.length===0&&h.push(void 0);let y=(m==null?void 0:m.type)==="contentType"?m.value:s;l=ir(h,T=>y.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}if((g==null?void 0:g.type)==="full")f=g.value;else{let h;(g==null?void 0:g.type)==="robustness"?h=g.value:e==="widevine"?h=u:t==="com.microsoft.playready.recommendation"?h=c:h=[],h.length===0&&h.push(void 0);let y=(g==null?void 0:g.type)==="contentType"?g.value:d;f=ir(h,T=>y.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}let I={initDataTypes:["cenc"],videoCapabilities:f,audioCapabilities:l,distinctiveIdentifier:a,persistentState:o,sessionTypes:i};return m!==void 0?g!==void 0?[I]:[I,me(oe({},I),{videoCapabilities:void 0})]:g!==void 0?[I,me(oe({},I),{audioCapabilities:void 0})]:[I,me(oe({},I),{audioCapabilities:void 0,videoCapabilities:void 0})]}function Cf(n,e){var u,c,l,f,m,g;let t=(c=(u=n.audioCapabilities)==null?void 0:u.map(I=>I.contentType))!=null?c:[],r=(f=(l=n.videoCapabilities)==null?void 0:l.map(I=>I.contentType))!=null?f:[],i=t.concat(r).filter(I=>I!==void 0),o=(m=e.videoCapabilities)==null?void 0:m.map(I=>I.contentType),a=(g=e.audioCapabilities)==null?void 0:g.map(I=>I.contentType),s=[...o!=null?o:[],...a!=null?a:[]].filter(I=>I!==void 0);return s.length===0?[]:i.map(I=>{let{codecs:h,mimeType:y}=Ea(I),T=J(s,I);return{codec:h,mimeType:y,result:T}})}function sd(n,e,t,r){p.info("DRM","Searching for compatible MediaKeySystemAccess");let i=t.reduce((a,s)=>{let{EME_KEY_SYSTEMS:d}=O.getCurrent(),u=d[s.type],c;if(!_(u))c=u.map(l=>({keyName:s.type,keyType:l,keySystemOptions:s}));else{let l=fh(s.type),f=s.type;c=[{keyName:l,keyType:f,keySystemOptions:s}]}return a.concat(c)},[]);return o(0);async function o(a){if(a>=i.length)throw new be("INCOMPATIBLE_KEYSYSTEMS","No key system compatible with your wanted configuration has been found in the current browser.",{keyStatuses:void 0,keySystemConfiguration:void 0,keySystem:void 0});if(_(n.requestMediaKeySystemAccess))throw new Error("requestMediaKeySystemAccess is not implemented in your browser.");let s=i[a],{keyType:d,keySystemOptions:u}=s,c=mh(s);p.debug("DRM","Request keysystem access",{keyType:d,index:a,length:i.length});let l,f=await dt.getAttachedMediaKeysState(e);for(let m=0;m<c.length;m++){let g=c[m];if(f!==null&&!ad(f.mediaKeySystemAccess.keySystem)&&d===f.mediaKeySystemAccess.keySystem&&n.implementation===f.emeImplementation.implementation&&ch(g,f.askedConfiguration))return p.info("DRM","Found cached compatible keySystem"),Promise.resolve({type:"reuse-media-key-system-access",value:{mediaKeySystemAccess:f.mediaKeySystemAccess,askedConfiguration:f.askedConfiguration,options:u,codecSupport:Cf(f.askedConfiguration,f.mediaKeySystemAccess.getConfiguration())}});try{return l=await ph(n,d,[g]),p.info("DRM","Found compatible keysystem",{keyType:d,index:a,configIndex:m}),{type:"create-media-key-system-access",value:{options:u,mediaKeySystemAccess:l,askedConfiguration:g,codecSupport:Cf(g,l.getConfiguration())}}}catch(I){if(p.debug("DRM","Rejected access to keysystem",{keyType:d,index:a,configIndex:m}),r.cancellationError!==null)throw r.cancellationError}}return o(a+1)}}async function ph(n,e,t){let r=await n.requestMediaKeySystemAccess(e,t);if(!vf(e))try{let o=(await r.createMediaKeys()).createSession(),a=kf(Rf);await o.generateRequest("cenc",a),o.close().catch(()=>{p.warn("DRM","Failed to close the dummy session")})}catch(i){throw p.debug("DRM","KeySystemAccess was granted but it is not usable"),i}return r}function Pf(n,e){for(let t=0;t<n.length;t++)if(!J(e,n[t]))return!1;return!0}function or(n,e){for(let t of n)if(!e.some(i=>_e(i,t)))return!1;return!0}function Mf(n,e){for(let t of n)if(e.some(i=>_e(i,t)))return!0;return!1}var ii=class{constructor(e){this._initializationData=e,this._keyIds=null}associateKeyIds(e){this._keyIds===null&&(this._keyIds=[]);let t=Array.from(e);for(let r of t)this.isAssociatedWithKeyId(r)||this._keyIds.push(r)}isAssociatedWithKeyId(e){if(this._keyIds===null)return!1;for(let t of this._keyIds)if(_e(t,e))return!0;return!1}getAssociatedKeyIds(){return this._keyIds===null?[]:this._keyIds}isCompatibleWith(e){let{keyIds:t}=e;if(t!==void 0&&t.length>0){if(this._keyIds!==null&&or(t,this._keyIds))return!0;if(this._initializationData.keyIds!==void 0)return or(t,this._initializationData.keyIds)}return this._checkInitializationDataCompatibility(e)}_checkInitializationDataCompatibility(e){return e.keyIds!==void 0&&e.keyIds.length>0&&this._initializationData.keyIds!==void 0?or(e.keyIds,this._initializationData.keyIds):this._initializationData.type!==e.type?!1:this._initializationData.values.isCompatibleWith(e.values)}};var oi=class{constructor(e){this._mediaKeys=e,this._storage=[]}createSession(e,t){let r=new ii(e);p.debug("DRM","calling `createSession`",{sessionType:t});let i=this._mediaKeys.createSession(t),o={mediaKeySession:i,sessionType:t,keySessionRecord:r,isGeneratingRequest:!1,isLoadingPersistentSession:!1,closingStatus:{type:"none"}};return _(i.closed)||i.closed.then(()=>{p.info("DRM","session was closed, removing it.",{sessionId:i.sessionId});let a=this.getIndex(r);a>=0&&this._storage[a].mediaKeySession===i&&this._storage.splice(a,1)}).catch(a=>{p.warn("DRM",`MediaKeySession.closed rejected: ${a}`)}),this._storage.push(oe({},o)),p.debug("DRM","MediaKeySession added",{sessionType:o.sessionType,currentlyLoaded:this._storage.length}),o}reuse(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.keySessionRecord.isCompatibleWith(e))return this._storage.splice(t,1),this._storage.push(r),p.debug("DRM","Reusing session:",{sessionId:r.mediaKeySession.sessionId,sessionType:r.sessionType}),oe({},r)}return null}getEntryForSession(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.mediaKeySession===e)return oe({},r)}return null}async generateLicenseRequest(e,t,r){let i;for(let o of this._storage)if(o.mediaKeySession===e){i=o;break}if(i===void 0)return p.error("DRM","generateRequest error. No MediaKeySession found with the given initData and initDataType"),ti(e,t,r);if(i.isGeneratingRequest=!0,i.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");try{await ti(e,t,r)}catch(o){throw i===void 0||(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start()),o}i!==void 0&&(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start())}async loadPersistentSession(e,t){let r;for(let o of this._storage)if(o.mediaKeySession===e){r=o;break}if(r===void 0)return p.error("DRM","loadPersistentSession error. No MediaKeySession found with the given initData and initDataType"),ni(e,t);if(r.isLoadingPersistentSession=!0,r.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");let i;try{i=await ni(e,t)}catch(o){throw r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),o}return r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),i}async closeSession(e){let t;for(let r of this._storage)if(r.mediaKeySession===e){t=r;break}return t===void 0?(p.warn("DRM","No MediaKeySession found with the given initData and initDataType"),Promise.resolve(!1)):this._closeEntry(t)}getLength(){return this._storage.length}getAll(){return this._storage}async closeAllSessions(){let e=this._storage;p.debug("DRM","Closing all current MediaKeySessions",{numberOfEntries:e.length}),this._storage=[];let t=e.map(r=>this._closeEntry(r));await Promise.all(t)}removeSessionWithoutClosingIt(e){ee(e.sessionId==="","Initialized `MediaKeySession`s should always be properly closed");for(let t=this._storage.length-1;t>=0;t--)if(this._storage[t].mediaKeySession===e)return p.debug("DRM","Removing session without closing it",{sessionId:e.sessionId}),this._storage.splice(t,1),!0;return!1}getIndex(e){for(let t=0;t<this._storage.length;t++)if(this._storage[t].keySessionRecord===e)return t;return-1}async _closeEntry(e){let{mediaKeySession:t}=e;return new Promise((r,i)=>{e!==void 0&&(e.isLoadingPersistentSession||e.isGeneratingRequest)?e.closingStatus={type:"awaiting",start:o}:o();function o(){e!==void 0&&(e.closingStatus={type:"pending"}),gh(t).then(()=>{e!==void 0&&(e.closingStatus={type:"done"}),r(!0)}).catch(a=>{e!==void 0&&(e.closingStatus={type:"failed"}),i(a)})}})}};async function gh(n){let e=n.sessionId;p.debug("DRM","Trying to close a MediaKeySession",{sessionId:e});try{await ia(n),p.debug("DRM","Succeeded to close MediaKeySession",{sessionId:e});return}catch(t){p.error("DRM","Could not close MediaKeySession: "+(t instanceof Error?t.toString():"Unknown error"),{sessionId:e});return}}function fn(n){let e=0,t;for(let r=0;r<n.length;r++)t=n[r],e=(e<<5)-e+t,e=e&e;return e}var yt=class{constructor(e){this.initData=e}toJSON(){return ca(this.initData)}static decode(e){return Ct(e)}};function ar(n,e){var t,r;return(r=(t=Af(n,e))!=null?t:Af(e,n))!=null?r:!1}function Af(n,e){if(n.length===0)return!1;if(e.length<n.length)return null;let t=n[0],r=0,i=0;for(;i<e.length;i++){let o=e[i];if(o.systemId!==t.systemId)continue;if(o.hash!==t.hash)return!1;let a;t.data instanceof Uint8Array?a=t.data:typeof t.data=="string"?a=yt.decode(t.data):a=t.data.initData;let s;if(o.data instanceof Uint8Array?s=o.data:typeof o.data=="string"?s=yt.decode(o.data):s=o.data.initData,!_e(a,s))return!1;if(e.length-i<n.length)return null;for(r=1;r<n.length;r++){let d=n[r];for(i+=1;i<e.length;i++){let u=e[i];if(d.systemId!==u.systemId)continue;if(d.hash!==u.hash)return!1;let c;d.data instanceof Uint8Array?c=d.data:typeof d.data=="string"?c=yt.decode(d.data):c=d.data.initData;let l;if(u.data instanceof Uint8Array?l=u.data:typeof u.data=="string"?l=yt.decode(u.data):l=u.data.initData,!_e(c,l))return!1;break}if(r===e.length)return null}return!0}return null}function hh(n){Vc(n,{save:"function",load:"function"},"persistentLicenseConfig")}var ai=class{constructor(e){hh(e),this._entries=[],this._storage=e;try{let t=this._storage.load();Array.isArray(t)||(t=[]),this._entries=t}catch(t){p.warn("DRM","Persistent store: Could not get entries from license storage",t instanceof Error?t:""),this.dispose()}}getLength(){return this._entries.length}getAll(){return this._entries}get(e){let t=this._getIndex(e);return t===-1?null:this._entries[t]}getAndReuse(e){let t=this._getIndex(e);if(t===-1)return null;let r=this._entries.splice(t,1)[0];return this._entries.push(r),r}add(e,t,r){var s;if(_(r)||!x(r.sessionId)){p.warn("DRM","Persistent Store: Invalid Persisten Session given.");return}let{sessionId:i}=r,o=this._getIndex(e);if(o>=0){let d=t===void 0?3:4,u=this._entries[o];if(((s=u.version)!=null?s:-1)>=d&&i===u.sessionId)return;p.info("DRM","Persistent Store: Updating session info.",{sessionId:i}),this._entries.splice(o,1)}else p.info("DRM","Persistent Store: Add new session",{sessionId:i});let a=Ih(e.values.getFormattedValues());t===void 0?this._entries.push({version:3,sessionId:i,values:a,initDataType:e.type}):this._entries.push({version:4,sessionId:i,keyIds:t.map(d=>new yt(d)),values:a,initDataType:e.type}),this._save()}delete(e){let t=-1;for(let i=0;i<this._entries.length;i++)if(this._entries[i].sessionId===e){t=i;break}if(t===-1){p.warn("DRM","Persistent Store: initData to delete not found in persistent store.");return}let r=this._entries[t];p.warn("DRM","Persistent Store: Delete session from persistent store",{sessionId:r.sessionId}),this._entries.splice(t,1),this._save()}deleteOldSessions(e){p.info("DRM","Persistent Store: Deleting last sessions.",{sessionsToDelete:e}),!(e<=0)&&(e<=this._entries.length?this._entries.splice(0,e):(p.warn("DRM","Persistent Store: Asked to remove more information that it contains",e,this._entries.length),this._entries=[]),this._save())}dispose(){this._entries=[],this._save()}_getIndex(e){let t=null;function r(){if(t===null){let i=e.values.constructRequestData();t={initData:i,initDataHash:fn(i)}}return t}for(let i=0;i<this._entries.length;i++){let o=this._entries[i];if(o.initDataType===e.type)switch(o.version){case 4:if(Array.isArray(e.keyIds)&&e.keyIds.length>0){if(e.keyIds.every(s=>{let d=ca(s);for(let u of o.keyIds)if(typeof u=="string"){if(d===u)return p.debug("DRM","Persistent Store: Found wanted kid stored on entry",{index:i,keyId:d,sessionId:o.sessionId}),!0}else if(_e(u.initData,s))return p.hasLevel("DEBUG")&&p.debug("DRM","Persistent Store: Found wanted kid stored on entry",{index:i,keyId:d,sessionId:o.sessionId}),!0;return!1}))return p.debug("DRM","Persistent Store: Found compatible entry of v4",{index:i,sessionId:o.sessionId}),i}else{let a=e.values.getFormattedValues();if(ar(a,o.values))return p.debug("DRM","Persistent Store: Found compatible entry of v4 without init data",{index:i,sessionId:o.sessionId}),i}break;case 3:{let a=e.values.getFormattedValues();if(ar(a,o.values))return p.debug("DRM","Persistent Store: Found compatible entry of v3 - same values",{index:i,sessionId:o.sessionId}),i;break}case 2:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s)try{let d=typeof o.initData=="string"?yt.decode(o.initData):o.initData.initData;if(_e(d,a))return p.debug("DRM","Persistent Store: Found compatible entry of v2 - same concatenated init data",{index:i,sessionId:o.sessionId}),i}catch(d){p.warn("DRM","Persistent Store: Could not decode initialization data.",d instanceof Error?d:"")}break}case 1:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s){if(typeof o.initData.length=="undefined")return p.debug("DRM","Persistent Store: Found compatible entry of v1 - same hash only",{index:i,sessionId:o.sessionId,hash:s}),i;if(_e(o.initData,a))return p.debug("DRM","Persistent Store: Found compatible entry of v1 - same hash and initData",{index:i,sessionId:o.sessionId,hash:s}),i}break}default:{let{initDataHash:a}=r();if(o.initData===a)return p.debug("DRM","Persistent Store: Found compatible entry - same hash only",{index:i,sessionId:o.sessionId,hash:a}),i}}}return-1}_save(){try{this._storage.save(this._entries)}catch(e){let t=e instanceof Error?e:void 0;p.warn("DRM","Persistent Store: Could not save MediaKeySession information",t)}}};function Ih(n){return n.map(({systemId:e,data:t,hash:r})=>({systemId:e,hash:r,data:new yt(t)}))}var Ra=new WeakMap,Ln={prepare(n){Ra.set(n,null)},set(n,e){let t=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),r=fn(t);Ra.set(n,{hash:r,serverCertificate:t})},hasOne(n){let e=Ra.get(n);if(e===void 0)return!1;if(e!==null)return!0},has(n,e){let t=Ra.get(n);if(t==null)return!1;let{hash:r,serverCertificate:i}=t,o=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer);if(fn(o)!==r||i.length!==o.length)return!1;for(let s=0;s<i.length;s++)if(i[s]!==o[s])return!1;return!0}};function yh(n){let{persistentLicenseConfig:e}=n;return _(e)?null:(p.debug("DRM","Set the given license storage"),new ai(e))}async function dd(n,e,t,r){let i=await sd(n,e,t,r);if(r.cancellationError!==null)throw r.cancellationError;let{options:o,mediaKeySystemAccess:a,askedConfiguration:s,codecSupport:d}=i.value,u=await dt.getAttachedMediaKeysState(e),c=yh(o);if(i.value.options.reuseMediaKeys!==!1&&od()&&u!==null&&i.type==="reuse-media-key-system-access"){p.debug("DRM","Reusing already created MediaKeys");let{mediaKeys:m,loadedSessionsStore:g}=u;if(Ln.hasOne(m)===!1||!_(o.serverCertificate)&&Ln.has(m,o.serverCertificate))return{mediaKeys:m,mediaKeySystemAccess:a,askedConfiguration:s,stores:{loadedSessionsStore:g,persistentSessionsStore:c},options:o,codecSupport:d}}let l=await bh(a);p.info("DRM","MediaKeys created with success");let f=new oi(l);return{mediaKeys:l,mediaKeySystemAccess:a,askedConfiguration:s,stores:{loadedSessionsStore:f,persistentSessionsStore:c},options:o,codecSupport:d}}async function bh(n){p.info("DRM","Calling createMediaKeys on the MediaKeySystemAccess");try{return await n.createMediaKeys()}catch(e){let t=e instanceof Error?e.message:"Unknown error when creating MediaKeys.";throw new be("CREATE_MEDIA_KEYS_ERROR",t,{keyStatuses:void 0,keySystemConfiguration:n.getConfiguration(),keySystem:n.keySystem})}}async function ud(n,e,t,r){let i=await dd(n,e,t,r),{mediaKeys:o}=i;return e.mediaKeys!==null&&e.mediaKeys!==void 0&&o!==e.mediaKeys&&(p.debug("DRM","Disabling old MediaKeys"),await dt.clearMediaKeys(e)),i}function si(n){let e=(Math.random()*2-1)*.3;return n*(e+1)}function ld(n,e,t){let{baseDelay:r,maxDelay:i,totalRetry:o,shouldRetry:a,onRetry:s}=e,d=0;return u();async function u(){if(t.cancellationError!==null)throw t.cancellationError;try{return await n()}catch(c){if(t.cancellationError!==null)throw t.cancellationError;if(!_(a)&&!a(c)||d++>=o)throw c;typeof s=="function"&&s(c,d);let l=Sh(r,d,i);return await An(l),u()}}}function Sh(n,e,t){let r=n*Math.pow(2,e-1),i=si(r);return Math.min(i,t)}function cd(n,e){return n.indexOf("playready")!==-1&&(V.browser===V.BROWSERS.EdgeChromium||V.browser===V.BROWSERS.Ie11||V.browser===V.BROWSERS.OtherIeOrEdgePreEdgeChromium)?ta(e):e}var sr=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.reason=e}},fd={EXPIRED:"expired",INTERNAL_ERROR:"internal-error",OUTPUT_RESTRICTED:"output-restricted"};function md(n,e,t){let{onKeyInternalError:r,onKeyOutputRestricted:i,onKeyExpiration:o}=e,a=[],s=[],d=[];n.keyStatuses.forEach((c,l)=>{let[f,m]=typeof c=="string"?[c,l]:[l,c],g=cd(t.keySystem,new Uint8Array(m)),I={keyId:g.buffer,keyStatus:f};switch(p.hasLevel("DEBUG")&&p.debug("DRM","key status update",{keyId:Ve(g),keyStatus:f}),f){case fd.EXPIRED:{let h=new be("KEY_STATUS_CHANGE_ERROR",`A decryption key expired (${Ve(g)})`,{keyStatuses:[I,...d],keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()});if(o==="error"||o===void 0)throw h;switch(o){case"close-session":throw new sr(h);case"fallback":a.push(g);break;default:o==="continue"||o===void 0?s.push(g):we(o);break}d.push(I);break}case fd.INTERNAL_ERROR:{let h=new be("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ve(g)})`,{keyStatuses:[I,...d],keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()});switch(r){case void 0:case"error":throw h;case"close-session":throw new sr(h);case"fallback":a.push(g);break;case"continue":s.push(g);break;default:if(r!==void 0)we(r);else throw h}d.push(I);break}case fd.OUTPUT_RESTRICTED:{let h=new be("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ve(g)})`,{keyStatuses:[I,...d],keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()});switch(i){case void 0:case"error":throw h;case"fallback":a.push(g);break;case"continue":s.push(g);break;default:if(i!==void 0)we(i);else throw h}d.push(I);break}default:s.push(g);break}});let u;return d.length>0&&(u=new be("KEY_STATUS_CHANGE_ERROR","One or several problematic key statuses have been encountered",{keyStatuses:d,keySystem:t.keySystem,keySystemConfiguration:t.getConfiguration()})),{warning:u,blacklistedKeyIds:a,whitelistedKeyIds:s}}function pd(n,e,t,r,i){p.info("DRM","Binding session events",{sessionId:n.sessionId});let{getLicenseConfig:o={}}=e,a=new D;a.linkToSignal(i),_(n.closed)||n.closed.then(()=>a.cancel()).catch(c=>{i.isCancelled()||(a.cancel(),r.onError(c))}),da(n,c=>{a.cancel(),r.onError(new be("KEY_ERROR",c.type,{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem}))},a.signal),of(n,()=>{p.info("DRM","keystatuseschange event received",{sessionId:n.sessionId});try{s()}catch(c){if(i.isCancelled()||a.isUsed()&&c instanceof Wr)return;a.cancel(),r.onError(c)}},a.signal),sa(n,c=>{let l=c,f=new Uint8Array(l.message),m=x(l.messageType)?l.messageType:"license-request";p.info("DRM","Received message event",{messageType:m,sessionId:n.sessionId});let g=u(o.retry);ld(()=>d(f,m),g,a.signal).then(async I=>{if(!a.isUsed())if(_(I))p.info("DRM","No license given, skipping session.update");else try{await Th(n,I,t)}catch(h){a.cancel(),r.onError(h)}},I=>{if(a.isUsed())return;a.cancel();let h=xf(I,t);if(!_(I)){let{fallbackOnLastTry:y}=I;if(y===!0){p.warn("DRM","Last `getLicense` attempt failed. Blacklisting the current session."),r.onError(new dr(h));return}}r.onError(h)})},a.signal),p.info("DRM","transmitting current keystatuses",{sessionId:n.sessionId}),s();return;function s(){if(a.isUsed()||n.keyStatuses.size===0)return;let{warning:c,blacklistedKeyIds:l,whitelistedKeyIds:f}=md(n,e,t);c!==void 0&&(r.onWarning(c),a.isUsed())||r.onKeyUpdate({whitelistedKeyIds:f,blacklistedKeyIds:l})}function d(c,l){let f;return new Promise((m,g)=>{try{p.debug("DRM","Calling `getLicense`",{messageType:l});let y=e.getLicense(c,l),T=_(o.timeout)?10*1e3:o.timeout;T>=0&&(f=setTimeout(()=>{g(new di(`"getLicense" timeout exceeded (${T} ms)`))},T)),Promise.resolve(y).then(I,h)}catch(y){h(y)}function I(y){f!==void 0&&clearTimeout(f),m(y)}function h(y){f!==void 0&&clearTimeout(f),g(y)}})}function u(c){return{totalRetry:c!=null?c:2,baseDelay:200,maxDelay:3e3,shouldRetry:l=>l instanceof di||_(l)||l.noRetry!==!0,onRetry:l=>r.onWarning(xf(l,t))}}}function xf(n,e){if(n instanceof di)return new be("KEY_LOAD_TIMEOUT","The license server took too much time to respond.",{keyStatuses:void 0,keySystemConfiguration:e.getConfiguration(),keySystem:e.keySystem});let t=new be("KEY_LOAD_ERROR","An error occured when calling `getLicense`.",{keyStatuses:void 0,keySystemConfiguration:e.getConfiguration(),keySystem:e.keySystem});return!_(n)&&x(n.message)&&(t.message=n.message),t}async function Th(n,e,t){p.info("DRM","Updating MediaKeySession with message");try{await n.update(e)}catch(r){let i=r instanceof Error?r.toString():"`session.update` failed";throw new be("KEY_UPDATE_ERROR",i,{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem})}p.info("DRM","MediaKeySession update succeeded.")}var dr=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.sessionError=e}},di=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,dr.prototype),this.message=e}};async function _h(n,e,t){try{return await n.setServerCertificate(e)}catch(r){p.warn("DRM","mediaKeys.setServerCertificate returned an error",r instanceof Error?r:"");let i=r instanceof Error?r.toString():"`setServerCertificate` error";throw new be("LICENSE_SERVER_CERTIFICATE_ERROR",i,{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem})}}async function gd(n,e,t){if(Ln.hasOne(n)===!0)return p.info("DRM","The MediaKeys already has a server certificate, skipping..."),{type:"already-has-one"};if(typeof n.setServerCertificate!="function")return p.warn("DRM","Could not set the server certificate. mediaKeys.setServerCertificate is not a function"),{type:"method-not-implemented"};p.info("DRM","Setting server certificate on the MediaKeys"),Ln.prepare(n);try{let r=await _h(n,e,t);return Ln.set(n,e),{type:"success",value:r}}catch(r){return{type:"error",value:on(r)?r:new be("LICENSE_SERVER_CERTIFICATE_ERROR","Unknown error when setting the server certificate.",{keyStatuses:void 0,keySystemConfiguration:t.getConfiguration(),keySystem:t.keySystem})}}}function hd(n,e){if(isNaN(e)||e<0||e>=n.getLength())return;let t=n.getLength(),r=t-e;p.info("DRM","Too many stored persistent sessions, removing some.",{numberOfPersistentSessions:t,toDelete:r}),n.deleteOldSessions(r)}function Id(n){if(Le(n,"com.microsoft.playready")||n==="com.chromecast.playready"||n==="com.youtube.playready")return"9a04f07998404286ab92e65be0885f95";if(n==="com.widevine.alpha")return"edef8ba979d64acea3c827dcd51d21ed";if(Le(n,"com.apple.fps"))return"94ce86fb07ff4f43adb893d2fa968ca2";if(Le(n,"com.nagra."))return"adb41c242dbf4a6d958b4457c0d27b95"}var ui=class n{constructor(e){this._innerValues=e,this._lazyFormattedValues=null}constructRequestData(){return le(...this._innerValues.map(e=>e.data))}isCompatibleWith(e){let t=e instanceof n?e.getFormattedValues():e;return ar(this.getFormattedValues(),t)}getFormattedValues(){return this._lazyFormattedValues===null&&(this._lazyFormattedValues=Eh(this._innerValues)),this._lazyFormattedValues}};function Eh(n){return n.slice().sort((e,t)=>e.systemId===t.systemId?0:e.systemId===void 0?1:t.systemId===void 0||e.systemId<t.systemId?-1:1).map(({systemId:e,data:t})=>({systemId:e,data:t,hash:fn(t)}))}function yd(n,e,t){let r=`${n};codecs="${e}"`,i=t.filter(o=>o.mimeType===n);if(i.length!==0)for(let{codec:o,mimeType:a,result:s}of i){let d=`${a};codecs="${o}"`;if(va(r,d))return s}}var li=class extends se{constructor(e,t,r){super(),p.debug("DRM","Starting ContentDecryptor logic.");let i=new D;this._currentSessions=[],this._canceller=i,this._initDataQueue=[],this._stateData={state:0,isMediaKeysAttached:0,isInitDataQueueLocked:!0,data:null},this._supportedCodecWhenEncrypted=[],this.error=null,this._eme=e,this._eme.onEncrypted(t,o=>{p.debug("DRM","Encrypted event received from media element.");let a=Ta(o);a!==null&&this.onInitializationData(a)},i.signal),ud(this._eme,t,r,i.signal).then(o=>{let{options:a,mediaKeySystemAccess:s}=o;this._supportedCodecWhenEncrypted=o.codecSupport;let d;(_(a.persistentLicenseConfig)||a.persistentLicenseConfig.disableRetroCompatibility===!0)&&(d=Id(s.keySystem)),this.systemId=d,this._stateData.state===0&&(p.debug("DRM","Waiting for attachment."),this._stateData={state:1,isInitDataQueueLocked:!0,isMediaKeysAttached:0,data:{mediaKeysInfo:o,mediaElement:t}},this.trigger("stateChange",this._stateData.state))}).catch(o=>{this._onFatalError(o)})}getState(){return this._stateData.state}attach(){if(this._stateData.state!==1)throw new Error("`attach` should only be called when in the WaitingForAttachment state");if(this._stateData.isMediaKeysAttached!==0){p.warn("DRM","ContentDecryptor's `attach` method called more than once.");return}let{mediaElement:e,mediaKeysInfo:t}=this._stateData.data,{options:r,mediaKeys:i,mediaKeySystemAccess:o,stores:a,askedConfiguration:s}=t;if(r.disableMediaKeysAttachmentLock===!0&&(p.debug("DRM","disabling MediaKeys attachment lock. Ready for content"),this._stateData={state:2,isInitDataQueueLocked:!0,isMediaKeysAttached:1,data:{mediaKeysInfo:t,mediaElement:e}},this.trigger("stateChange",this._stateData.state),this._isStopped()))return;this._stateData.isMediaKeysAttached=1;let u={emeImplementation:this._eme,loadedSessionsStore:a.loadedSessionsStore,mediaKeySystemAccess:o,mediaKeys:i,askedConfiguration:s,keySystemOptions:r};p.debug("DRM","Attaching current MediaKeys"),dt.attach(e,u).then(async()=>{if(this._isStopped())return;this._stateData.isMediaKeysAttached=2;let{serverCertificate:c}=r;if(!_(c)){let f=await gd(i,c,o);f.type==="error"&&this.trigger("warning",f.value)}if(this._isStopped())return;let l=this._stateData.state;this._stateData={state:2,isMediaKeysAttached:2,isInitDataQueueLocked:!1,data:{mediaKeysData:t}},l!==2&&this.trigger("stateChange",2),this._isStopped()||this._processCurrentInitDataQueue()}).catch(c=>{this._onFatalError(c)})}dispose(){this.removeEventListener(),this._stateData={state:4,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("stateChange",this._stateData.state)}isCodecSupported(e,t){if(this._stateData.state===0){p.error("DRM","Asking for codec support while the ContentDecryptor is still initializing");return}return(this._stateData.state===3||this._stateData.state===4)&&p.error("DRM","Asking for codec support while the ContentDecryptor is disposed"),yd(e,t,this._supportedCodecWhenEncrypted)}onInitializationData(e){if(this._stateData.isInitDataQueueLocked!==!1){if(this._isStopped())throw new Error("ContentDecryptor either disposed or stopped.");this._initDataQueue.push(e);return}let{mediaKeysData:t}=this._stateData.data,r=me(oe({},e),{values:new ui(e.values)});this._processInitializationData(r,t).catch(i=>{this._onFatalError(i)})}async _processInitializationData(e,t){var I,h,y;p.hasLevel("DEBUG")&&p.debug("DRM","processing init data",(I=e.content)==null?void 0:I.adaptation.type,(h=e.content)==null?void 0:h.representation.bitrate,((y=e.keyIds)!=null?y:[]).map(T=>Ve(T)).join(", "));let{mediaKeySystemAccess:r,stores:i,options:o}=t;if(this._tryToUseAlreadyCreatedSession(e,t)||this._isStopped())return;if(o.singleLicensePer==="content"){let T=q(this._currentSessions,v=>v.source==="created-session");if(T!==void 0){let v=e.keyIds;if(v===void 0){e.content===void 0?p.warn("DRM","Unable to fallback from a non-decipherable quality."):(p.debug("DRM","Blacklisting new init data (due to singleLicensePer content policy)"),this.trigger("blackListProtectionData",e));return}if(T.record.associateKeyIds(v),e.content===void 0)p.warn("DRM","Unable to fallback from a non-decipherable quality.");else{if(p.hasLevel("DEBUG")){let E=v.reduce((R,k)=>`${R}, ${Ve(k)}`,"");p.debug("DRM","Blacklisting new key ids",E)}this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:v,delistedKeyIds:[]})}return}}else if(o.singleLicensePer==="periods"&&e.content!==void 0){let{period:T}=e.content,v=this._currentSessions.filter(R=>R.source==="created-session"),E=new Set;Sd(E,T);for(let R of v){let k=Array.from(E);for(let A of k)if(R.record.isAssociatedWithKeyId(A)){R.record.associateKeyIds(E.values());for(let P of k)!R.keyStatuses.whitelisted.some(M=>_e(M,P))&&!R.keyStatuses.blacklisted.some(M=>_e(M,P))&&R.keyStatuses.blacklisted.push(P);p.hasLevel("DEBUG")&&p.debug("DRM","Session already created for",Ve(A),'under singleLicensePer "periods" policy'),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:R.keyStatuses.whitelisted,blacklistedKeyIds:R.keyStatuses.blacklisted,delistedKeyIds:[]});return}}}this._lockInitDataQueue();let a;vh(r)&&(!_(o.persistentLicenseConfig)||!Rh(r))?a="persistent-license":a="temporary";let{EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:s,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:d}=O.getCurrent(),u=typeof o.maxSessionCacheSize=="number"?o.maxSessionCacheSize:s,c=await id(e,i,a,u,this._canceller.signal);if(this._isStopped())return;let l={record:c.value.keySessionRecord,source:c.type,keyStatuses:{whitelisted:[],blacklisted:[]},blacklistedSessionError:null};this._currentSessions.push(l);let{mediaKeySession:f,sessionType:m}=c.value,g=!1;if(pd(f,o,r,{onKeyUpdate:T=>{let v=Ph(e,l.record,o.singleLicensePer,l.source==="created-session",T.whitelistedKeyIds,T.blacklistedKeyIds);if(l.record.associateKeyIds(v.whitelisted),l.record.associateKeyIds(v.blacklisted),l.keyStatuses={whitelisted:v.whitelisted,blacklisted:v.blacklisted},l.record.getAssociatedKeyIds().length!==0&&m==="persistent-license"&&i.persistentSessionsStore!==null&&!g){let{persistentSessionsStore:E}=i;hd(E,d-1),E.add(e,l.record.getAssociatedKeyIds(),f),g=!0}e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:v.whitelisted,blacklistedKeyIds:v.blacklisted,delistedKeyIds:[]}),this._unlockInitDataQueue()},onWarning:T=>{this.trigger("warning",T)},onError:T=>{var v;if(T instanceof sr){p.warn("DRM","A session's closing condition has been triggered"),this._lockInitDataQueue();let E=this._currentSessions.indexOf(l);E>=0&&this._currentSessions.splice(E),e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:[],delistedKeyIds:l.record.getAssociatedKeyIds()}),(v=i.persistentSessionsStore)==null||v.delete(f.sessionId),i.loadedSessionsStore.closeSession(f).catch(R=>{let k=R instanceof Error?R:"unknown error";p.warn("DRM","failed to close expired session",k)}).then(()=>this._unlockInitDataQueue()).catch(R=>this._onFatalError(R)),this._isStopped()||this.trigger("warning",T.reason);return}if(!(T instanceof dr)){this._onFatalError(T);return}l.blacklistedSessionError=T,e.content!==void 0&&(p.info("DRM","blacklisting Representations based on protection data."),this.trigger("blackListProtectionData",e)),this._unlockInitDataQueue()}},this._canceller.signal),(o.singleLicensePer===void 0||o.singleLicensePer==="init-data")&&this._unlockInitDataQueue(),c.type==="created-session"){let T=e.values.constructRequestData();try{await i.loadedSessionsStore.generateLicenseRequest(f,e.type,T)}catch(v){let E=i.loadedSessionsStore.getEntryForSession(f);if(E===null||E.closingStatus.type!=="none"){let R=this._currentSessions.indexOf(l);return R>=0&&this._currentSessions.splice(R,1),Promise.resolve()}throw new be("KEY_GENERATE_REQUEST_ERROR",v instanceof Error?v.toString():"Unknown error",{keyStatuses:void 0,keySystemConfiguration:r.getConfiguration(),keySystem:r.keySystem})}}return Promise.resolve()}_tryToUseAlreadyCreatedSession(e,t){let{stores:r,options:i}=t,o=q(this._currentSessions,c=>c.record.isCompatibleWith(e));if(o===void 0)return!1;if(e.forceSessionRecreation===!0)return this.removeSessionForInitData(e,t),!1;let s=o.blacklistedSessionError;if(!_(s))return e.type===void 0||e.content===void 0?(p.error("DRM","This initialization data has already been blacklisted but the current content is not known."),!0):(p.info("DRM","This initialization data has already been blacklisted. Blacklisting the related content."),this.trigger("blackListProtectionData",e),!0);if(e.keyIds!==void 0){let c;if(i.singleLicensePer===void 0||i.singleLicensePer==="init-data"){let{blacklisted:l}=o.keyStatuses;c=Mf(e.keyIds,l)}else{let{whitelisted:l}=o.keyStatuses;c=!or(e.keyIds,l)}if(c)return e.content===void 0?(p.error("DRM","Cannot forbid key id, the content is unknown."),!0):(p.info("DRM","Current initialization data is linked to blacklisted keys. Marking Representations as not decipherable"),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:e.keyIds,delistedKeyIds:[]}),!0)}if(r.loadedSessionsStore.reuse(e)!==null)return p.debug("DRM","Init data already processed. Skipping it."),!0;let u=this._currentSessions.indexOf(o);return u===-1?p.error("DRM","Unable to remove processed init data: not found."):(p.debug("DRM","A session from a processed init data is not available anymore. Re-processing it."),this._currentSessions.splice(u,1)),!1}removeSessionForInitData(e,t){let{stores:r}=t,i=r.loadedSessionsStore.reuse(e);i!==null&&r.loadedSessionsStore.closeSession(i.mediaKeySession).catch(()=>p.error("DRM","Cannot close the session from the loaded session store"));let o=q(this._currentSessions,s=>s.record.isCompatibleWith(e));if(o===void 0)return;let a=this._currentSessions.indexOf(o);a!==-1&&(p.debug("DRM","A session from a processed init is removed due to forceSessionRecreation policy."),this._currentSessions.splice(a,1))}_onFatalError(e){if(this._canceller.isUsed())return;let t=e instanceof Error?e:new De("NONE","Unknown decryption error");this.error=t,this._initDataQueue.length=0,this._stateData={state:3,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("error",t),this._stateData.state===3&&this.trigger("stateChange",this._stateData.state)}_isStopped(){return this._stateData.state===4||this._stateData.state===3}_processCurrentInitDataQueue(){for(;this._stateData.isInitDataQueueLocked===!1;){let e=this._initDataQueue.shift();if(e===void 0)return;this.onInitializationData(e)}}_lockInitDataQueue(){this._stateData.isInitDataQueueLocked===!1&&(this._stateData.isInitDataQueueLocked=!0)}_unlockInitDataQueue(){if(this._stateData.isMediaKeysAttached!==2){p.error("DRM","Trying to unlock in the wrong state");return}this._stateData.isInitDataQueueLocked=!1,this._processCurrentInitDataQueue()}};function vh(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&J(e,"persistent-license")}function Rh(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&J(e,"temporary")}function wf(n,e){return n.filter(t=>!e.some(r=>_e(r,t)))}function kh(n,e){let t=n.getAssociatedKeyIds(),r=wf(t,e);return r.length>0&&p.hasLevel("DEBUG")&&p.debug("DRM","KeySessionRecord's keys missing in the license, blacklisting them",r.map(i=>Ve(i)).join(", ")),r}function Ch(n,e){let t=[],{keyIds:r}=n;return r!==void 0&&(t=wf(r,e)),t.length>0&&p.hasLevel("DEBUG")&&p.debug("DRM","init data keys missing in the license, blacklisting them",t.map(i=>Ve(i)).join(", ")),t}function Ph(n,e,t,r,i,o){var u;let a=[...i,...o],s=kh(e,a),d=a.concat(s);if(t!==void 0&&t!=="init-data"){let c=Ch(n,d);d.push(...c);let{content:l}=n;if(r&&l!==void 0){if(t==="content"){let f=new Set,{manifest:m}=l;for(let g of m.periods)Sd(f,g);bd(f,d)}else if(t==="periods"){let{manifest:f}=l;for(let m of f.periods){let g=new Set;if(Sd(g,m),((u=n.content)==null?void 0:u.period.id)===m.id)bd(g,d);else{let I=Array.from(g);for(let h of I)if(d.some(T=>_e(T,h))){bd(g,d);break}}}}}}return{whitelisted:i,blacklisted:d.slice(i.length)}}function bd(n,e){let t=Array.from(n.values());for(let r of t)e.some(o=>_e(o,r))||e.push(r)}function Sd(n,e){let t=e.adaptations,r=Jn(t).reduce((i,o)=>_(o)?i:i.concat(o),[]);for(let i of r)for(let o of i.representations)if(o.contentProtections!==void 0&&o.contentProtections.keyIds!==void 0)for(let a of o.contentProtections.keyIds)n.add(a)}function ur(n){let e=dt.getAwaitedState(n);return e===null?null:[e.mediaKeySystemAccess.keySystem,e.mediaKeySystemAccess.getConfiguration()]}var Of=li;function Df(n){var t,r,i,o,a;let e=[];for(let s of n.periods){let d=[...(t=s.adaptations.video)!=null?t:[],...(r=s.adaptations.audio)!=null?r:[]];for(let u of d)if(u.supportStatus.hasCodecWithUndefinedSupport)for(let c of u.representations)c.isSupported===void 0&&e.push({mimeType:(i=c.mimeType)!=null?i:"",codec:(a=(o=c.codecs)==null?void 0:o[0])!=null?a:""})}return e}function Lf(n,e,t,r){let i=new Map,o=[],a=(s,d)=>{var m;let u=`${s!=null?s:""};codecs="${d!=null?d:""}"`,c=i.get(u);if(c!==void 0)return c;let l;return Ds(t,u)?_(e)?l={isSupportedClear:!0,isSupportedEncrypted:!0}:e.getState()===0?l={isSupportedClear:!0,isSupportedEncrypted:void 0}:l={isSupportedClear:!0,isSupportedEncrypted:(m=e.isCodecSupported(s!=null?s:"",d!=null?d:""))!=null?m:!0}:l={isSupportedClear:!1,isSupportedEncrypted:!1},i.set(u,l),o.push({codec:d!=null?d:"",mimeType:s!=null?s:"",supported:l.isSupportedClear,supportedIfEncrypted:l.isSupportedEncrypted}),l};return n.periods.forEach(s=>{var d,u,c;[...(d=s.adaptations.audio)!=null?d:[],...(u=s.adaptations.video)!=null?u:[],...(c=s.adaptations.text)!=null?c:[]].forEach(l=>{let f=!1,m=!1;l.representations.forEach(g=>{var T,v;if(g.isCodecSupportedInWebWorker===!1&&r){g.isSupported=!1;return}if(g.isSupported!==void 0){g.isSupported&&(f=!0);return}let I=g.contentProtections!==void 0,h=(T=g.mimeType)!=null?T:"",y=(v=g.codecs)!=null?v:[];y.length===0&&(y=[""]);for(let E of y){let R=a(h,E);if(I?g.isSupported!==R.isSupportedEncrypted&&(g.isSupported=R.isSupportedEncrypted):g.isSupported=R.isSupportedClear,g.isSupported===void 0)m=!0;else if(g.isSupported){f=!0,g.codecs=[E];break}}}),l.supportStatus.hasCodecWithUndefinedSupport=m,m&&!f?l.supportStatus.hasSupportedCodec=void 0:l.supportStatus.hasSupportedCodec=f})}),o}var Nf=[];function jt(n){J(Nf,n)||(console.warn(n),Nf.push(n))}var ci=class{constructor(e){this.supportMap=new Map,this.addCodecs(e)}addCodecs(e){for(let t of e){let r=this.supportMap.get(t.mimeType);r===void 0&&(r=new Map,this.supportMap.set(t.mimeType,r)),r.set(t.codec,{supported:t.supported,supportedIfEncrypted:t.supportedIfEncrypted})}}isSupported(e,t,r){let i=this.supportMap.get(e);if(i===void 0)return;let o=i.get(t);if(o!==void 0)return r?o.supportedIfEncrypted:o.supported}};var mn=class{constructor(e,t,r){if(this.id=e.id,this.adaptations=Mh(e.adaptations,t,r),Bf(this.adaptations.video)&&Bf(this.adaptations.audio))throw new re("MANIFEST_PARSE_ERROR","The manifest has no video nor audio tracks.");this.thumbnailTracks=e.thumbnailTracks.map(i=>({id:i.id,mimeType:i.mimeType,index:i.index,cdnMetadata:i.cdnMetadata,height:i.height,width:i.width,horizontalTiles:i.horizontalTiles,verticalTiles:i.verticalTiles,start:i.start,end:i.end,tileDuration:i.tileDuration})),this.duration=e.duration,this.start=e.start,!_(this.duration)&&!_(this.start)&&(this.end=this.start+this.duration),this.streamEvents=e.streamEvents===void 0?[]:e.streamEvents}refreshCodecSupport(e,t){Object.keys(this.adaptations).forEach(r=>{let i=this.adaptations[r];if(i!==void 0)for(let o of i){if(!o.supportStatus.hasCodecWithUndefinedSupport)continue;let a=o.supportStatus.hasSupportedCodec;o.refreshCodecSupport(t),a!==!1&&o.supportStatus.hasSupportedCodec===!1&&e.push(o)}},{})}getAdaptations(){return xs(this)}getAdaptationsForType(e){let t=this.adaptations[e];return t!=null?t:[]}getAdaptation(e){return q(this.getAdaptations(),({id:t})=>e===t)}getSupportedAdaptations(e){return Vt(this,e)}containsTime(e,t){return As(this,e,t)}getMetadataSnapshot(){let e={},t=this.getAdaptations();for(let r of t){let i=e[r.type];i===void 0&&(i=[],e[r.type]=i),i.push(r.getMetadataSnapshot())}return{start:this.start,end:this.end,id:this.id,streamEvents:this.streamEvents,adaptations:e,thumbnailTracks:this.thumbnailTracks.map(r=>({id:r.id,mimeType:r.mimeType,height:r.height,width:r.width,horizontalTiles:r.horizontalTiles,verticalTiles:r.verticalTiles,start:r.start,end:r.end,tileDuration:r.tileDuration}))}}};function Bf(n){return Array.isArray(n)?n.length===0:!0}function Mh(n,e,t){let r={};for(let[i,o]of Object.entries(n))_(o)||(r[i]=o.map(a=>new sn(a,e,{representationFilter:t})).filter(a=>a.representations.length>0));return r}function fi(n,e,t){let r={updatedAdaptations:[],removedAdaptations:[],addedAdaptations:[],updatedThumbnailTracks:[],removedThumbnailTracks:[],addedThumbnailTracks:[]};n.start=e.start,n.end=e.end,n.duration=e.duration,n.streamEvents=e.streamEvents;let i=n.thumbnailTracks,o=e.thumbnailTracks;for(let d=0;d<i.length;d++){let u=i[d],c=Te(o,l=>l.id===u.id);if(c===-1){p.warn("manifest",'ThumbnailTrack "'+i[d].id+'" not found when merging.');let[l]=i.splice(d,1);d--,r.removedThumbnailTracks.push({id:l.id})}else{let[l]=o.splice(c,1);u.mimeType=l.mimeType,u.height=l.height,u.width=l.width,u.horizontalTiles=l.horizontalTiles,u.verticalTiles=l.verticalTiles,u.start=l.start,u.end=l.end,u.tileDuration=l.tileDuration,u.cdnMetadata=l.cdnMetadata,t===0?u.index._replace(l.index):u.index._update(l.index),r.updatedThumbnailTracks.push({id:u.id,mimeType:u.mimeType,height:u.height,width:u.width,horizontalTiles:u.horizontalTiles,verticalTiles:u.verticalTiles,start:u.start,end:u.end,tileDuration:u.tileDuration})}}o.length>0&&(p.warn("manifest",`${o.length} new Thumbnail tracks found when merging.`),r.addedThumbnailTracks.push(...o.map(d=>({id:d.id,mimeType:d.mimeType,height:d.height,width:d.width,horizontalTiles:d.horizontalTiles,verticalTiles:d.verticalTiles,start:d.start,end:d.end,tileDuration:d.tileDuration}))),n.thumbnailTracks.push(...o));let a=n.getAdaptations(),s=e.getAdaptations();for(let d=0;d<a.length;d++){let u=a[d],c=Te(s,l=>l.id===u.id);if(c===-1){p.warn("manifest",'Adaptation "'+a[d].id+'" not found when merging.');let[l]=a.splice(d,1);d--,r.removedAdaptations.push({id:l.id,trackType:l.type})}else{let[l]=s.splice(c,1),f=[],m=[],g=[];r.updatedAdaptations.push({adaptation:u.id,trackType:u.type,updatedRepresentations:f,addedRepresentations:m,removedRepresentations:g});let I=u.representations,h=l.representations.slice();for(let y=0;y<I.length;y++){let T=I[y],v=Te(h,E=>E.id===T.id);if(v===-1){p.warn("manifest",`Representation "${I[y].id}" not found when merging.`);let[E]=I.splice(y,1);y--,g.push(E.id)}else{let[E]=h.splice(v,1);f.push(T.getMetadataSnapshot()),T.cdnMetadata=E.cdnMetadata,t===0?T.index._replace(E.index):T.index._update(E.index)}}h.length>0&&(p.warn("manifest",`${h.length} new Representations found when merging.`),u.representations.push(...h),m.push(...h.map(y=>y.getMetadataSnapshot())))}}if(s.length>0){p.warn("manifest",`${s.length} new Adaptations found when merging.`);for(let d of s){let u=n.adaptations[d.type];u===void 0?n.adaptations[d.type]=[d]:u.push(d),r.addedAdaptations.push(d.getMetadataSnapshot())}}return r}function Uf(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]},r=0;for(let o=0;o<e.length;o++){let a=e[o],s=r,d=n[s];for(;d!==void 0&&d.id!==a.id;)s++,d=n[s];if(d!==void 0){let u=fi(d,a,0);t.updatedPeriods.push({period:{id:d.id,start:d.start,end:d.end,duration:d.duration,streamEvents:d.streamEvents},result:u});let c=e.slice(r,o),l=s-r,f=n.splice(r,l,...c);t.removedPeriods.push(...f.map(m=>({id:m.id,start:m.start,end:m.end}))),t.addedPeriods.push(...c.map(m=>m.getMetadataSnapshot())),r=o+1}}if(r>n.length)return p.error("manifest","error when updating Periods"),t;if(r<n.length){let o=n.splice(r,n.length-r);t.removedPeriods.push(...o.map(a=>({id:a.id,start:a.start,end:a.end})))}let i=e.slice(r,e.length);return i.length>0&&(n.push(...i),t.addedPeriods.push(...i.map(o=>o.getMetadataSnapshot()))),t}function Ff(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]};if(n.length===0)return n.splice(0,0,...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t;if(e.length===0)return t;let r=n[n.length-1];if(r.start<e[0].start){if(r.end!==e[0].start)throw new re("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");return n.push(...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t}let i=Te(n,({id:s})=>s===e[0].id);if(i<0)throw new re("MANIFEST_UPDATE_ERROR","Cannot perform partial update: incoherent data");let o=fi(n[i],e[0],1);t.updatedPeriods.push({period:G(n[i].getMetadataSnapshot(),{adaptations:void 0}),result:o});let a=i+1;for(let s=1;s<e.length;s++){let d=e[s],u=-1;for(let c=a;c<n.length;c++)if(d.id===n[c].id){u=c;break}if(u<0){let c=-1;for(let m=a;m<n.length;m++)if(d.start<n[m].start){c=m;break}let l=c-a,f=n.splice(a,l,d);t.addedPeriods.push(d.getMetadataSnapshot()),t.removedPeriods.push(...f.map(m=>({id:m.id,start:m.start,end:m.end})))}else{if(u>a){p.warn("manifest","old Periods not found in new when updating, removing");let l=n.splice(a,u-a);t.removedPeriods.push(...l.map(f=>({id:f.id,start:f.start,end:f.end}))),u=a}let c=fi(n[u],d,0);t.updatedPeriods.push({period:G(n[u].getMetadataSnapshot(),{adaptations:void 0}),result:c})}a++}if(a<n.length){p.warn("manifest","Ending Periods not found in new when updating, removing");let s=n.splice(a,n.length-a);t.removedPeriods.push(...s.map(d=>({id:d.id,start:d.start,end:d.end})))}return t}var Ah=Fe(),mi=class extends se{constructor(e,t){var o;super();let{representationFilter:r,manifestUpdateUrl:i}=t;this.manifestFormat=0,this.id=Ah(),this.expired=(o=e.expired)!=null?o:null,this.transport=e.transportType,this.clockOffset=e.clockOffset,this._cachedCodecSupport=new ci([]),this.periods=e.periods.map(a=>new mn(a,this._cachedCodecSupport,r)).sort((a,s)=>a.start-s.start),this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.timeBounds=e.timeBounds,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.uris=e.uris===void 0?[]:e.uris,this.updateUrl=i,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.availabilityStartTime=e.availabilityStartTime,this.publishTime=e.publishTime}updateCodecSupport(e=[]){if(e.length===0)return null;this._cachedCodecSupport.addCodecs(e);let t=[];for(let r of this.periods)r.refreshCodecSupport(t,this._cachedCodecSupport);return this.trigger("supportUpdate",null),t.length>0?new re("MANIFEST_INCOMPATIBLE_CODECS_ERROR","An Adaptation contains only incompatible codecs.",{tracks:t.map(Mn)}):null}getPeriod(e){return q(this.periods,t=>e===t.id)}getPeriodForTime(e){return tr(this,e)}getNextPeriod(e){return q(this.periods,t=>t.start>e)}getPeriodAfter(e){return jo(this,e)}getUrls(){return this.uris}replace(e){this._performUpdate(e,0)}update(e){this._performUpdate(e,1)}getMinimumSafePosition(){return Cn(this)}getLivePosition(){return Pn(this)}getMaximumSafePosition(){return Ot(this)}updateCodecSupportList(e){this._cachedCodecSupport=e}updateRepresentationsDeciperability(e){let t=xh(this,e);t.length>0&&this.trigger("decipherabilityUpdate",t)}addRepresentationsToAvoid(e){let t=[];for(let r of e){let i=this.getPeriod(r.period.id);if(i===void 0)continue;let o=i.getAdaptation(r.adaptation.id);if(o===void 0)continue;let a=o.getRepresentation(r.representation.id);a!==void 0&&(a.shouldBeAvoided=!0,t.push({manifest:this,period:i,adaptation:o,representation:a}))}t.length>0&&this.trigger("representationAvoidanceUpdate",t)}getAdaptations(){jt("manifest.getAdaptations() is deprecated. Please use manifest.period[].getAdaptations() instead");let e=this.periods[0];if(e===void 0)return[];let t=e.adaptations,r=[];for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let o=t[i];r.push(...o)}return r}getAdaptationsForType(e){jt("manifest.getAdaptationsForType(type) is deprecated. Please use manifest.period[].getAdaptationsForType(type) instead");let t=this.periods[0];if(t===void 0)return[];let r=t.adaptations[e];return r===void 0?[]:r}getAdaptation(e){return jt("manifest.getAdaptation(id) is deprecated. Please use manifest.period[].getAdaptation(id) instead"),q(this.getAdaptations(),({id:t})=>e===t)}getMetadataSnapshot(){let e=[];for(let t of this.periods)e.push(t.getMetadataSnapshot());return{manifestFormat:1,id:this.id,periods:e,isDynamic:this.isDynamic,isLive:this.isLive,isLastPeriodKnown:this.isLastPeriodKnown,suggestedPresentationDelay:this.suggestedPresentationDelay,clockOffset:this.clockOffset,uris:this.uris,availabilityStartTime:this.availabilityStartTime,timeBounds:this.timeBounds}}getCodecsWithUnknownSupport(){return Df(this)}_performUpdate(e,t){this.availabilityStartTime=e.availabilityStartTime,this.expired=e.expired,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.transport=e.transport,this.publishTime=e.publishTime;let r;if(t===0)this.timeBounds=e.timeBounds,this.uris=e.uris,r=Uf(this.periods,e.periods);else{this.timeBounds.maximumTimeData=e.timeBounds.maximumTimeData,this.updateUrl=e.uris[0],r=Ff(this.periods,e.periods);let i=this.getMinimumSafePosition();for(;this.periods.length>0;){let o=this.periods[0];if(o.end===void 0||o.end>i)break;this.periods.shift()}}this.updateCodecSupport(),this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.trigger("manifestUpdate",r)}};function xh(n,e){let t=[];for(let r of n.periods)for(let i of r.getAdaptations()){let o=!0;for(let a of i.representations){let s={manifest:n,period:r,adaptation:i,representation:a},d=e(s);d!==!1&&(o=!1),d!==a.decipherable&&(t.push(s),a.decipherable=d,d===!0?i.supportStatus.isDecipherable=!0:d===void 0&&i.supportStatus.isDecipherable===!1&&(i.supportStatus.isDecipherable=void 0),p.debug("manifest",`Decipherability changed for "${a.id}"`,`(${a.bitrate})`,String(a.decipherable)))}o&&(i.supportStatus.isDecipherable=!1)}return t}function zt(n,e){return n.segment.id===e.segment.id&&n.representation.uniqueId===e.representation.uniqueId}function kt(n){if(_(n))return null;let{period:e,adaptation:t,representation:r,segment:i}=n;return{t:t.type[0],p:e.id,a:t.id,r:r.id,ss:i.isInit?null:i.time,se:i.isInit||!i.complete?null:i.end}}var pn=mi;var Bt=class{constructor(e,t){this._last=e,this._wanted=t}serialize(){return[this._last,this._wanted]}getPolled(){return this._last}getWanted(){var e;return(e=this._wanted)!=null?e:this._last}forceWantedPosition(e){this._wanted=e}isAwaitingFuturePosition(){return this._wanted!==null}};function lr(n,e,t){let r=e(n.getReference(),t);return{getCurrentTime(){return n.getCurrentTime()},getReadyState(){return n.getReadyState()},getPlaybackRate(){return n.getPlaybackRate()},getIsPaused(){return n.getIsPaused()},getReference(){return r},listen(i,o){t.isCancelled()||o.clearSignal.isCancelled()||r.onUpdate(i,{clearSignal:o.clearSignal,emitCurrentValue:o.includeLastObservation})},deriveReadOnlyObserver(i){return lr(this,i,t)}}}var pi=class{constructor(e,t,r,i){this._src=e,this._contentId=t,this._messageSender=r,this._cancelSignal=i}getCurrentTime(){}getReadyState(){}getIsPaused(){}getReference(){return this._src}setPlaybackRate(e){this._messageSender({type:"update-playback-rate",contentId:this._contentId,value:e})}getPlaybackRate(){}listen(e,t){this._cancelSignal.isCancelled()||t.clearSignal.isCancelled()||this._src.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return lr(this,e,this._cancelSignal)}};var Nn=class{constructor(e){this._array=[],this._sortingFn=e}add(...e){e.sort(this._sortingFn);let t=0;for(let r=0;r<e.length;r++){let i=e[r],o=!1;for(;!o&&t<this._array.length;)this._sortingFn(i,this._array[t])<0?(this._array.splice(t,0,i),o=!0):t++;o||this._array.push(i)}}length(){return this._array.length}get(e){if(e<0||e>=this._array.length)throw new Error("Invalid index.");return this._array[e]}toArray(){return this._array.slice()}findFirst(e){return q(this._array,e)}has(e){return J(this._array,e)}removeElement(e){let t=this._array.indexOf(e);if(t>=0)return this._array.splice(t,1),t}head(){return this._array[0]}last(){return this._array[this._array.length-1]}shift(){return this._array.shift()}pop(){return this._array.pop()}};var gi=class{constructor(e){this._weakMap=new WeakMap,this._fn=e}get(e){let t=this._weakMap.get(e);if(t===void 0){let r=this._fn(e);return this._weakMap.set(e,r),r}else return t}destroy(e){this._weakMap.delete(e)}};var wh=.016666666666666666;function Kf(n,e){return Math.abs(n-e)<wh}function zf(n,e){let t=Math.min(n.start,e.start),r=Math.max(n.end,e.end);return{start:t,end:r}}function Oh(n){for(let e=0;e<n.length;e++){let t=n[e];t.start===t.end&&n.splice(e--,1)}return n}function Dh(n){for(let e=1;e<n.length;e++){let t=n[e-1],r=n[e];if(Hf(t,r)){let i=zf(t,r);n.splice(--e,2,i)}}return n}function Td(n,e){return n.end<=e.start}function Vf({start:n,end:e},t){return n<=t&&t<e}function Wf(n,e){return Vf(n,e.start)||n.start<e.end&&e.end<n.end||Vf(e,n.start)}function Hf(n,e){return Kf(e.start,n.end)||Kf(e.end,n.start)}function We(n){let e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e}function _d(n,e){for(let t=n.length-1;t>=0;t--){let r=n.start(t);if(e>=r){let i=n.end(t);if(e<i)return{start:r,end:i}}}return null}function Lh(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t].start;if(e>=r){let i=n[t].end;if(e<i)return n[t]}}return null}function qf(n,e){let t=n.length;for(let r=0;r<t;r++){let i=n.start(r);if(e<i)return i-e}return 1/0}function Gf(n,e){let t=null,r=[];for(let i=0;i<n.length;i++){let o=n[i].start,a=n[i].end;e<o||e>=a?r.push({start:o,end:a}):t={start:o,end:a}}return{outerRanges:r,innerRange:t}}function jf(n,e){let t=_d(n,e);return t!==null?t.end-e:1/0}function ka(n,e){let t=Lh(n,e);return t!==null?t.end-e:1/0}function Ut(n,e){if(e.start===e.end)return n;let t=e,r=0;for(;r<n.length;r++){let i=n[r],o=Wf(t,i),a=Hf(t,i);if(o||a)t=zf(t,i),n.splice(r--,1);else if(r===0){if(Td(t,n[0]))break}else if(Td(n[r-1],t)&&Td(t,i))break}return n.splice(r,0,t),Dh(Oh(n))}function Yf(n,e){let t=[];for(let r=0;r<e.length;r++)Wf(n,e[r])&&t.push(e[r]);return t}function Qf(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=Yf(i,e);if(o.length>0)for(let a=0;a<o.length;a++){let s=o[a];t.push({start:Math.max(i.start,s.start),end:Math.min(i.end,s.end)})}}return t}function Ca(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=[],a=Yf(i,e);if(a.length>0)for(let s=0;s<a.length;s++){let d=a[s];o.push({start:Math.max(i.start,d.start),end:Math.min(i.end,d.end)})}if(o.length===0)t.push(i);else{let s=i.start;for(let d=0;d<o.length;d++)o[d].start>s&&t.push({start:s,end:o[d].start}),s=o[d].end;s<i.end&&t.push({start:s,end:i.end})}}return t}function Pa({segmentSink:n,playbackObserver:e,maxBufferBehind:t,maxBufferAhead:r},i){let o,a=[];e.listen(d=>{o=d.position.getWanted(),a=d.buffered[n.bufferType],s()},{includeLastObservation:!0,clearSignal:i});function s(){a!==null&&Nh(n,o,a,t.getValue(),r.getValue(),i).catch(d=>{if(i.isCancelled()&&D.isCancellationError(d))return;let u=d instanceof Error?d.message:"Unknown error";p.error("Stream","Could not run BufferGarbageCollector:",u)})}t.onUpdate(s,{clearSignal:i}),r.onUpdate(s,{clearSignal:i}),s()}async function Nh(n,e,t,r,i,o){if(!isFinite(r)&&!isFinite(i))return Promise.resolve();let a=[],{innerRange:s,outerRanges:d}=Gf(t,e),u=()=>{if(isFinite(r)){for(let l of d)e-r>=l.end?a.push(l):e>=l.end&&e-r>l.start&&e-r<l.end&&a.push({start:l.start,end:e-r});_(s)||e-r>s.start&&a.push({start:s.start,end:e-r})}},c=()=>{if(isFinite(i)){for(let l of d)e+i<=l.start?a.push(l):e<=l.start&&e+i<l.end&&e+i>l.start&&a.push({start:e+i,end:l.end});_(s)||e+i<s.end&&a.push({start:e+i,end:s.end})}};u(),c();for(let l of a)if(l.start<l.end){if(p.debug("Stream","cleaning range from SegmentSink",{start:l.start,end:l.end}),o.cancellationError!==null)throw o.cancellationError;await n.removeBuffer(l.start,l.end)}}var hi=class{constructor(e,t){this._history=[],this._lifetime=e,this._maxHistoryLength=t}addBufferedSegment(e,t){let r=z();this._history.push({date:r,buffered:t,context:e}),this._cleanHistory(r)}getHistoryFor(e){return this._history.filter(t=>zt(t.context,e))}_cleanHistory(e){let t=e-this._lifetime,r=0;for(let i of this._history)if(i.date<t)r++;else break;if(r>0&&(this._history=this._history.splice(r)),this._history.length>this._maxHistoryLength){let i=this._history.length-this._maxHistoryLength;this._history=this._history.splice(i)}}};var Ii=class{constructor(){let{BUFFERED_HISTORY_RETENTION_TIME:e,BUFFERED_HISTORY_MAXIMUM_ENTRIES:t}=O.getCurrent();this._inventory=[],this._bufferedHistory=new hi(e,t)}reset(){this._inventory.length=0}synchronizeBuffered(e){var d,u,c,l,f,m,g;let t=this._inventory,r=0,i=t[0],{MINIMUM_SEGMENT_SIZE:o}=O.getCurrent(),a=i==null?void 0:i.infos.adaptation.type;if(p.hasLevel("DEBUG")){let I=e.map(h=>`${h.start}-${h.end}`).join(",");p.debug("SI",`synchronizing ${a!=null?a:"unknown"} buffered ranges:`,I)}let s=e.length;for(let I=0;I<s;I++){if(i===void 0)return;let h=e[I].start,y=e[I].end;if(y-h<o){p.warn("SI","skipped range when synchronizing because it was too small",{t:a,rangeStart:h,rangeEnd:y});continue}let T=r;for(;i!==void 0&&((d=i.bufferedEnd)!=null?d:i.end)-h<o;)i=t[++r];let v=null,E=r-T;if(E>0){let k=t[T+E-1];v={end:(u=k.bufferedEnd)!=null?u:k.end,precizeEnd:k.precizeEnd},p.debug("SI",`${E} segments GCed.`,{t:a});let A=t.splice(T,E);for(let P of A)P.bufferedStart===void 0&&P.bufferedEnd===void 0&&P.status!==2&&this._bufferedHistory.addBufferedSegment(P.infos,null);r=T}if(i===void 0)return;if(y-((c=i.bufferedStart)!=null?c:i.start)>=o){if(Bh(i,h,v,a),r===t.length-1){Xf(i,y,a);return}i=t[++r];let k=(l=i.bufferedStart)!=null?l:i.start,A=(f=i.bufferedEnd)!=null?f:i.end,P=I<s-1?e[I+1].start:void 0;for(;i!==void 0&&!(y<k||y-k<o&&A-y>=o||P!==void 0&&y-k<A-P);){let M=t[r-1];M.bufferedEnd===void 0&&(i.precizeStart?M.bufferedEnd=i.start:M.infos.segment.complete?M.bufferedEnd=M.end:M.bufferedEnd=i.start,p.debug("SI","calculating buffered end of contiguous segment",{t:a,prevSegmentBufferedEnd:M.bufferedEnd,pse:M.end})),i.bufferedStart=M.bufferedEnd,i=t[++r],i!==void 0&&(k=(m=i.bufferedStart)!=null?m:i.start,A=(g=i.bufferedEnd)!=null?g:i.end)}}let R=t[r-1];R!==void 0&&Xf(R,y,a)}if(!_(i)){let{SEGMENT_SYNCHRONIZATION_DELAY:I}=O.getCurrent(),h=z();for(let y=r;y<t.length;y++){let T=t[y];h-T.insertionTs>=I&&(p.debug("SI","A segment at the end has been completely GCed",kt(T.infos)),T.bufferedStart===void 0&&T.bufferedEnd===void 0&&T.status!==2&&this._bufferedHistory.addBufferedSegment(T.infos,null),t.splice(y,1),y--)}}a!==void 0&&p.hasLevel("DEBUG")&&p.debug("SI",`current ${a} inventory timeline:
|
|
2
|
+
`+Uh(this._inventory))}insertChunk({period:e,adaptation:t,representation:r,segment:i,chunkSize:o,start:a,end:s},d,u){if(i.isInit)return;let c=t.type;if(a>=s){p.warn("SI","Invalid chunked inserted: starts before it ends",{t:c,start:a,end:s});return}let l=this._inventory,f={status:d?0:2,insertionTs:u,chunkSize:o,splitted:!1,start:a,end:s,precizeStart:!1,precizeEnd:!1,bufferedStart:void 0,bufferedEnd:void 0,infos:{segment:i,period:e,adaptation:t,representation:r}};for(let g=l.length-1;g>=0;g--){let I=l[g];if(I.start<=a)if(I.end<=a){for(p.debug("SI","Pushing segment strictly after previous one.",{t:c,pse:I.end,ss:a}),this._inventory.splice(g+1,0,f),g+=2;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){p.debug("SI","Segment pushed updates the start of the next one",{t:c,pss:l[g].start,ss:a,se:s}),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}p.debug("SI","Segment pushed removes the next one",{t:c,ss:a,se:s,pss:l[g].start,pse:l[g].end}),l.splice(g,1)}return}else if(I.start===a)if(I.end<=s){for(p.debug("SI","Segment pushed replace another one",{t:c,ss:a,se:s,pss:I.start,pse:I.end}),this._inventory.splice(g,1,f),g+=1;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){p.debug("SI","Segment pushed updates the start of the next one",{t:c,ss:a,se:s,pss:l[g].start,pse:l[g].end}),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}p.debug("SI","Segment pushed removes the next one",{t:c,ss:a,se:s,pss:l[g].start,pse:l[g].end}),l.splice(g,1)}return}else{p.debug("SI","Segment pushed ends before another with the same start",{t:c,ss:a,se:s,pse:I.end}),l.splice(g,0,f),I.start=f.end,I.bufferedStart=void 0,I.precizeStart=I.precizeStart&&f.precizeEnd;return}else if(I.end<=f.end){for(p.debug("SI","Segment pushed updates end of previous one",{t:c,ss:a,se:s,pss:I.start,pse:I.end}),this._inventory.splice(g+1,0,f),I.end=f.start,I.bufferedEnd=void 0,I.precizeEnd=I.precizeEnd&&f.precizeStart,g+=2;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){p.debug("SI","Segment pushed updates the start of the next one",{t:c,ss:a,se:s,pss:l[g].start}),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}p.debug("SI","Segment pushed removes the next one",{t:c,ss:a,se:s,pss:l[g].start,pse:l[g].end}),l.splice(g,1)}return}else{p.warn("SI","Segment pushed is contained in a previous one",{t:c,ss:a,se:s,pss:I.start,pse:I.end});let h={status:I.status,insertionTs:I.insertionTs,chunkSize:I.chunkSize,splitted:!0,start:f.end,end:I.end,precizeStart:I.precizeStart&&I.precizeEnd&&f.precizeEnd,precizeEnd:I.precizeEnd,bufferedStart:void 0,bufferedEnd:I.end,infos:I.infos};I.end=f.start,I.splitted=!0,I.bufferedEnd=void 0,I.precizeEnd=I.precizeEnd&&f.precizeStart,l.splice(g+1,0,f),l.splice(g+2,0,h);return}}let m=this._inventory[0];if(m===void 0){p.debug("SI","first segment pushed",{t:c,ss:a,se:s}),this._inventory.push(f);return}if(m.start>=s)p.debug("SI","Segment pushed comes before all previous ones",{t:c,ss:a,se:s,pss:m.start}),this._inventory.splice(0,0,f);else if(m.end<=s){for(p.debug("SI","Segment pushed starts before and completely recovers the previous first one",{t:c,ss:a,se:s,pss:m.start,pse:m.end}),this._inventory.splice(0,1,f);l.length>1&&l[1].start<f.end;){if(l[1].end>f.end){p.debug("SI","Segment pushed updates the start of the next one",{t:c,ss:a,se:s,pss:l[1].start,pse:l[1].end}),l[1].start=f.end,l[1].bufferedStart=void 0,l[1].precizeStart=f.precizeEnd;return}p.debug("SI","Segment pushed removes the next one",{t:c,ss:a,se:s,pss:l[1].start,pse:l[1].end}),l.splice(1,1)}return}else{p.debug("SI","Segment pushed start of the next one",c,{ss:a,se:s,pss:m.start,pse:m.end}),m.start=s,m.bufferedStart=void 0,m.precizeStart=f.precizeEnd,this._inventory.splice(0,0,f);return}}completeSegment(e){if(e.segment.isInit)return;let t=this._inventory,r=[];for(let i=0;i<t.length;i++)if(zt(t[i].infos,e)){let o=!1;r.length>0&&(o=!0,r.length===1&&(p.warn("SI","Completed Segment is splitted.",kt(e)),r[0].splitted=!0));let a=i,s=t[i].chunkSize;for(i+=1;i<t.length&&zt(t[i].infos,e);){let f=t[i].chunkSize;s!==void 0&&f!==void 0&&(s+=f),i++}let d=i-1,u=d-a,c=t[d].end,l=t[d].bufferedEnd;u>0&&(this._inventory.splice(a+1,u),i-=u),this._inventory[a].status===0&&(this._inventory[a].status=1),this._inventory[a].chunkSize=s,this._inventory[a].end=c,this._inventory[a].bufferedEnd=l,this._inventory[a].splitted=o,r.push(this._inventory[a])}if(r.length===0)p.warn("SI","Completed Segment not found",kt(e));else for(let i of r)i.bufferedStart!==void 0&&i.bufferedEnd!==void 0?i.status!==2&&this._bufferedHistory.addBufferedSegment(i.infos,{start:i.bufferedStart,end:i.bufferedEnd}):p.debug("SI","buffered range not known after sync. Skipping history.",{ss:i.start,se:i.end})}getInventory(){return this._inventory}getHistoryFor(e){return this._bufferedHistory.getHistoryFor(e)}};function Ed(n){if(n.bufferedStart===void 0||n.status!==1)return!1;let{start:e,end:t}=n,r=t-e,{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:o}=O.getCurrent();return Math.abs(e-n.bufferedStart)<=i&&(n.bufferedEnd===void 0||n.bufferedEnd>n.bufferedStart&&Math.abs(n.bufferedEnd-n.bufferedStart-r)<=Math.min(o,r/3))}function $f(n){if(n.bufferedEnd===void 0||!n.infos.segment.complete||n.status!==1)return!1;let{start:e,end:t}=n,r=t-e,{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:o}=O.getCurrent();return Math.abs(t-n.bufferedEnd)<=i&&n.bufferedStart!==void 0&&n.bufferedEnd>n.bufferedStart&&Math.abs(n.bufferedEnd-n.bufferedStart-r)<=Math.min(o,r/3)}function Bh(n,e,t,r){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MISSING_DATA_TRIGGER_SYNC_DELAY:o,SEGMENT_SYNCHRONIZATION_DELAY:a}=O.getCurrent();if(n.bufferedStart!==void 0)n.bufferedStart<e&&(p.debug("SI","Segment partially GCed at the start",{t:r,firstsbs:n.bufferedStart,rs:e}),n.bufferedStart=e),!n.precizeStart&&Ed(n)&&(n.start=n.bufferedStart,n.precizeStart=!0);else if(n.precizeStart)p.debug("SI","buffered start is precize start",{t:r,firstss:n.start}),n.bufferedStart=n.start;else if(t!==null&&t.end>e&&(t.precizeEnd||n.start-t.end<=i))p.debug("SI","buffered start is end of previous segment",{t:r,rs:e,firstss:n.start,lastdelse:t.end}),n.bufferedStart=t.end,Ed(n)&&(n.start=t.end,n.precizeStart=!0);else if(n.start-e<=i){let s=z();if(n.start-e>=o&&s-n.insertionTs<a){p.debug("SI","Ignored bufferedStart synchronization",{t:r,rs:e,firstss:n.start,delta:s-n.insertionTs});return}p.debug("SI","found true buffered start",{t:r,rs:e,firstss:n.start}),n.bufferedStart=e,Ed(n)&&(n.start=e,n.precizeStart=!0)}else if(e<n.start)p.debug("SI","range start too far from expected start",{t:r,rs:e,firstss:n.start}),n.bufferedStart=n.start;else{let s=z();if(n.start-e>=o&&s-n.insertionTs<a){p.debug("SI","Ignored bufferedStart synchronization",{t:r,rs:e,firstss:n.start,delta:s-n.insertionTs});return}p.debug("SI","Segment appears immediately garbage collected at the start",{t:r,rs:e,firstss:n.start}),n.bufferedStart=e}}function Xf(n,e,t){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:r,MISSING_DATA_TRIGGER_SYNC_DELAY:i,SEGMENT_SYNCHRONIZATION_DELAY:o}=O.getCurrent();if(n.bufferedEnd!==void 0)n.bufferedEnd>e&&(p.debug("SI","Segment partially GCed at the end",{t,lastsbe:n.bufferedEnd,re:e}),n.bufferedEnd=e),!n.precizeEnd&&e-n.end<=r&&$f(n)&&(n.precizeEnd=!0,n.end=e);else if(n.precizeEnd)p.debug("SI","buffered end is precize end",{t,lastse:n.end}),n.bufferedEnd=n.end;else if(e-n.end<=r||!n.infos.segment.complete){let a=z();if(e-n.end>=i&&a-n.insertionTs<o){p.debug("SI","Ignored bufferedEnd synchronization",{t,re:e,lastse:n.end,delta:a-n.insertionTs});return}p.debug("SI","found true buffered end",{t,re:e,lastse:n.end}),n.bufferedEnd=e,$f(n)&&(n.end=e,n.precizeEnd=!0)}else if(e>n.end)p.debug("SI","range end too far from expected end",{t,re:e,lastse:n.end}),n.bufferedEnd=n.end;else{let a=z();if(e-n.end>=i&&a-n.insertionTs<o){p.debug("SI","Ignored bufferedEnd synchronization",{t,re:e,lastse:n.end,delta:a-n.insertionTs});return}p.debug("SI","Segment appears immediately garbage collected at the end",{t,lastsbe:n.bufferedEnd,re:e}),n.bufferedEnd=e}}function Uh(n){let e=.016666666666666666,t={},r=[],i=null,o=null;function a(d){let u=String.fromCharCode(r.length+65);return r.push({letter:u,periodId:d.period.id,representationId:d.representation.id,bitrate:d.representation.bitrate}),u}let s="";for(let d of n)if(d.bufferedStart!==void 0&&d.bufferedEnd!==void 0){let u=d.infos.period.id,c=d.infos.representation.id,l=t[u],f;if(l===void 0)f=a(d.infos),t[u]={[c]:f};else{let m=l[c];m===void 0?(f=a(d.infos),l[c]=f):f=m}i===null?s+=`${d.bufferedStart.toFixed(2)}|${f}|`:o===f?i.bufferedEnd+e<d.bufferedStart&&(s+=`${i.bufferedEnd.toFixed(2)} ~ ${d.bufferedStart.toFixed(2)}|${f}|`):s+=`${i.bufferedEnd.toFixed(2)} ~ ${d.bufferedStart.toFixed(2)}|${f}|`,i=d,o=f}return i!==null&&(s+=String(i.end.toFixed(2))),r.forEach(d=>{var u;s+=`
|
|
3
|
+
[${d.letter}] P: ${d.periodId} || R: ${d.representationId}(${(u=d.bitrate)!=null?u:"unknown bitrate"})`}),s}function cr(n,e){for(let t=0;t<n.length;t++)if(n[t].infos.period.start>=e.start)return t>0?n[t-1]:null;return n.length>0?n[n.length-1]:null}function fr(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var Zf=Ii;var mr=class{constructor(){this._segmentInventory=new Zf}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var yi=class extends mr{constructor(e,t,r){super(),p.info("Stream","calling `mediaSource.addSourceBuffer`",{codec:t});let i=r.addSourceBuffer(e,t);this.bufferType=e,this._sourceBuffer=i,this._lastInitSegmentUniqueId=null,this.codec=t,this._initSegmentsMap=new Map,this._pendingOperations=[]}declareInitSegment(e,t){Jf(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){Jf(e.data.chunk),p.debug("Stream","queuing push order",kt(e.inventoryInfos));let t=this._getActualDataToPush(e.data);t.length===0&&t.push(new Uint8Array);let r=Promise.all(t.map(a=>{let{codec:s,timestampOffset:d,appendWindow:u}=e.data;return p.debug("Stream","now pushing",kt(e.inventoryInfos)),this._sourceBuffer.appendBuffer(a,{codec:s,timestampOffset:d,appendWindow:u})}));this._addToOperationQueue(r,{type:0,value:e});let i;try{i=await r}catch(a){throw this._segmentInventory.insertChunk(e.inventoryInfos,!1,z()),a}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,z());let o=i[i.length-1];return this._segmentInventory.synchronizeBuffered(o),o}async removeBuffer(e,t){p.debug("Stream","queuing remove order",{bufferType:this.bufferType,start:e,end:t});let r=this._sourceBuffer.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){try{p.debug("Stream","Calling `dispose` on the SourceBufferInterface"),this._sourceBuffer.dispose()}catch(e){p.debug("Stream",`Failed to dispose a ${this.bufferType} SourceBufferInterface:`,e instanceof Error?e:"Unknown Error")}}_getActualDataToPush(e){let t=[];if(e.initSegmentUniqueId!==null&&!this._isLastInitSegment(e.initSegmentUniqueId)){let r=this._initSegmentsMap.get(e.initSegmentUniqueId);if(r===void 0)throw new Error("Invalid initialization segment uniqueId");let i=new ArrayBuffer(r.byteLength),o=new Uint8Array(i);o.set(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer)),r=o,t.push(r),this._lastInitSegmentUniqueId=e.initSegmentUniqueId}return e.chunk!==null&&t.push(e.chunk),t}_isLastInitSegment(e){return this._lastInitSegmentUniqueId===null?!1:this._lastInitSegmentUniqueId===e}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function Jf(n){if(b.CURRENT_ENV!==b.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var Aa=yi;var bi=class extends mr{constructor(e){p.debug("Stream","Creating TextSegmentSink"),super(),this.bufferType="text",this._sender=e,this._pendingOperations=[],this._sender.reset()}declareInitSegment(e){p.warn("Stream","Declaring initialization segment for Text SegmentSink",{uniqueId:e})}freeInitSegment(e){p.warn("Stream","Freeing initialization segment for Text SegmentSink",{uniqueId:e})}async pushChunk(e){let{data:t}=e;Kh(t.chunk);let r=this._sender.pushTextData(me(oe({},t),{chunk:t.chunk}));this._addToOperationQueue(r,{type:0,value:e});let i=await r;return e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,z()),this._segmentInventory.synchronizeBuffered(i),i}async removeBuffer(e,t){let r=this._sender.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){p.debug("Stream","Disposing TextSegmentSink"),this._sender.reset()}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function Kh(n){if(b.CURRENT_ENV!==b.PRODUCTION){if(typeof n!="object"||n===null||_(n.data))throw new Error("Invalid format given to a TextSegmentSink");if(!Vh(n))throw new Error("Invalid format given to a TextSegmentSink");if(typeof n.data!="string"&&typeof n.data.byteLength!="number")throw new Error("Invalid format given to a TextSegmentSink")}}function Vh(n){return!(typeof n!="object"||n===null||typeof n.type!="string"||n.language!==void 0&&typeof n.language!="string"||n.initTimescale!==null&&typeof n.initTimescale!="number"||n.start!==void 0&&typeof n.start!="number"||n.end!==void 0&&typeof n.end!="number")}b.CURRENT_ENV===b.DEV&&(zh=function(e){function t(r){}});var zh;var em=bi;var Wh=["audio","video","text"],Si=class n{static isNative(e){return tm(e)}constructor(e,t,r){this._mediaSource=e,this._textInterface=r,this._hasVideo=t,this._initializedSegmentSinks={},this._onNativeBufferAddedOrDisabled=[]}getBufferTypes(){let e=this.getNativeBufferTypes();return this._textInterface!==null&&e.push("text"),e}getNativeBufferTypes(){return this._hasVideo?["video","audio"]:["audio"]}getStatus(e){let t=this._initializedSegmentSinks[e];return t===void 0?{type:"uninitialized"}:t===null?{type:"disabled"}:{type:"initialized",value:t}}waitForUsableBuffers(e){return this._areNativeBuffersUsable()?Promise.resolve():xn(e,t=>{let r=ae,i=()=>{let o=this._onNativeBufferAddedOrDisabled.indexOf(r);o>=0&&this._onNativeBufferAddedOrDisabled.splice(o,1)};return r=()=>{this._areNativeBuffersUsable()&&(i(),t())},this._onNativeBufferAddedOrDisabled.push(r),i})}disableSegmentSink(e){let t=this._initializedSegmentSinks[e];if(t===null){p.warn("Stream",`The ${e} SegmentSink was already disabled.`);return}if(t!==void 0)throw new Error("Cannot disable an active SegmentSink.");this._initializedSegmentSinks[e]=null,n.isNative(e)&&(this._onNativeBufferAddedOrDisabled.slice().forEach(r=>r()),ee(this._onNativeBufferAddedOrDisabled.length===0))}createSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(tm(e)){if(!_(r))return r instanceof Aa&&r.codec!==t?p.warn("Stream","Reusing native SegmentSink with codec",r.codec,"for codec",t):p.info("Stream","Reusing native SegmentSink with codec",t),r;p.info("Stream","Adding native SegmentSink with codec",t);let o=e==="audio"?"audio":"video",a=new Aa(o,t,this._mediaSource);return this._initializedSegmentSinks[e]=a,this._onNativeBufferAddedOrDisabled.slice().forEach(s=>s()),ee(this._onNativeBufferAddedOrDisabled.length===0),a}if(!_(r))return p.info("Stream","Reusing a previous custom SegmentSink",{bufferType:e}),r;let i;if(e==="text"){if(p.info("Stream","Creating a new text SegmentSink"),this._textInterface===null)throw new Error("HTML Text track feature not activated");return i=new em(this._textInterface),this._initializedSegmentSinks.text=i,i}throw p.error("Stream","Unknown buffer type:",{bufferType:e}),new re("BUFFER_TYPE_UNKNOWN","The player wants to create a SegmentSink of an unknown type.")}disposeSegmentSink(e){let t=this._initializedSegmentSinks[e];if(_(t)){p.warn("Stream","Trying to dispose a SegmentSink that does not exist",{bufferType:e});return}p.info("Stream","Aborting SegmentSink",{bufferType:e}),t.dispose(),delete this._initializedSegmentSinks[e]}disposeAll(){Wh.forEach(e=>{this.getStatus(e).type==="initialized"&&this.disposeSegmentSink(e)})}_areNativeBuffersUsable(){let e=this.getNativeBufferTypes();return!(e.some(i=>this._initializedSegmentSinks[i]===void 0)||e.every(i=>this._initializedSegmentSinks[i]===null))}createSegmentSinkMetricsForType(e){var i,o;let t=(i=this._initializedSegmentSinks[e])==null?void 0:i.getLastKnownInventory(),r;if(t!==void 0){r=0;for(let a of t){if(a.chunkSize===void 0||r===void 0){r=void 0;break}r+=a.chunkSize}}return{bufferType:e,sizeEstimate:r,codec:(o=this._initializedSegmentSinks[e])==null?void 0:o.codec,segmentInventory:t==null?void 0:t.map(a=>me(oe({},a),{infos:Hh(a.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function tm(n){return n==="audio"||n==="video"}function Hh(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var gn=Si;function vd(n,e,t,r,i){let{period:o,adaptation:a,representation:s}=n,d=qh(i,e);if(d===null){if(t===null){if(r&&o.end!==void 0&&e.end>=o.end)return{start:void 0,end:null};let l=s.index.checkDiscontinuity(e.start);if(l!==null)return{start:void 0,end:l}}return null}let u=i[d];if(u.bufferedStart!==void 0&&u.bufferedStart>e.start&&(t===null||u.infos.segment.end<=t)){let l=u.bufferedStart;return!r&&s.index.awaitSegmentBetween(e.start,l)!==!1?null:(p.debug("Stream","current discontinuity encountered",{bufferType:a.type,nextSegmentTime:u.bufferedStart,checkStartTime:e.start}),{start:void 0,end:l})}let c=Gh(i,e,d+1);if(c!==null){let l=i[c-1],f=i[c];if(t===null||f.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(l.infos.segment.end,f.infos.segment.time)!==!1)return null;let m=l.bufferedEnd,g=f.bufferedStart;return p.debug("Stream","future discontinuity encountered",{bufferType:a.type,discontinuityStart:m,discontinuityEnd:g}),{start:m,end:g}}}if(t===null){if(r&&o.end!==void 0){if(e.end<o.end)return null;let l=jh(i,o.end);if(l!==null){let f=i[l];if(f.bufferedEnd!==void 0&&f.bufferedEnd<o.end)return p.debug("Stream","discontinuity encountered at the end of the current period",{bufferType:a.type,segmentsEndTimeFromPeriod:f.bufferedEnd,periodEnd:o.end}),{start:f.bufferedEnd,end:null}}}if(o.end!==void 0&&e.end>=o.end)return null;for(let l=i.length-1;l>=0;l--){let f=i[l];if(f.bufferedStart===void 0)break;if(f.bufferedStart<e.end){if(f.bufferedEnd!==void 0&&f.bufferedEnd<e.end){let m=s.index.checkDiscontinuity(e.end);if(m!==null)return{start:f.bufferedEnd,end:m}}return null}}}return null}function qh(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.bufferedStart===void 0||r.bufferedEnd===void 0||r.bufferedStart>=e.end)return null;if(r.bufferedEnd>e.start)return t}return null}function Gh(n,e,t){if(t<=0)return p.error("Stream","Asked to check a discontinuity before the first chunk."),null;for(let r=t;r<n.length;r++){let i=n[r],o=n[r-1];if(i.bufferedStart===void 0||o.bufferedEnd===void 0||i.bufferedStart>=e.end)return null;if(i.bufferedStart-o.bufferedEnd>0)return r}return null}function jh(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.bufferedStart===void 0)return null;if(r.bufferedStart<e)return t}return null}function Rd({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:o,segmentsBeingPushed:a,maxBufferSize:s}){let{adaptation:d,representation:u}=e,c=Yh(n,a,s),l=u.index.getSegments(o.start,o.end-o.start),f=n.filter(R=>!nm(R.infos,e,t,r)),m=tI(f,o,i),{MINIMUM_SEGMENT_SIZE:g,MIN_BUFFER_AHEAD:I}=O.getCurrent(),h=!1,y=Math.min(1/60,g),T=!1,v=[];return{segmentsToLoad:l.filter(R=>{let k=G({segment:R},e);if(a.length>0&&a.some(B=>zt(k,B)))return!1;let{duration:A,time:P,end:M}=R;if(R.isInit)return!0;if(h)return v.push(R),!1;if(R.complete&&A<g||a.length>0&&a.some(B=>{if(B.period.id!==e.period.id||B.adaptation.id!==e.adaptation.id)return!1;let{segment:C}=B;if(C.time-y>P)return!1;if(C.complete){if(C.end+y<M)return!1}else if(Math.abs(P-C.time)>P)return!1;return!nm(B,k,t,r)}))return!1;for(let L of m){let B=L.infos.period.id===e.period.id;if(L.status===1&&B){let C=L.infos.segment;if(P-C.time>-y){if(C.complete){if(C.end-M>-y)return!1}else if(Math.abs(P-C.time)<y)return!1}}}let N=A*e.representation.bitrate;if(c-N<0&&(T=!0,P>o.start+I))return h=!0,v.push(R),!1;let U=i(k);if(U.length>1){let L=U[U.length-1],B=U[U.length-2];if(L.buffered===null&&B.buffered===null)return p.warn("Stream","Segment GCed multiple times in a row, ignoring it.","If this happens a lot and lead to unpleasant experience, please check your device's available memory. If it's low when this message is emitted, you might want to update the RxPlayer's settings (`maxBufferAhead`, `maxVideoBufferSize` etc.) so less memory is used by regular media data buffering.",{bufferType:d.type,representationId:u.id,segmentTime:R.time}),!1}for(let L=0;L<m.length;L++){let B=m[L];if(B.end+y>P){let C=B.start>P+y||Qh(m,L).end<M-y;return C&&(c-=N),C}}return c-=N,!0}),segmentsOnHold:v,isBufferFull:T}}function Yh(n,e,t){let r=t*8e3;return r-=e.reduce((i,o)=>{let{bitrate:a}=o.representation,{duration:s}=o.segment;return i+a*s},0),n.reduce((i,o)=>o.chunkSize!==void 0?i-o.chunkSize*8:i,r)}function Qh(n,e){let t=e+1,{MINIMUM_SEGMENT_SIZE:r}=O.getCurrent(),i=Math.min(1/60,r);for(;t<n.length-1&&n[t-1].end+i>n[t].start;)t++;return t--,n[t]}function nm(n,e,t,r){let{CONTENT_REPLACEMENT_PADDING:i}=O.getCurrent();if(n.period.id!==e.period.id)return!1;let{segment:o}=n;return o.time<t+i?!1:n.adaptation.id!==e.adaptation.id?!0:$h(n.representation,e.representation,r)}function $h(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=O.getCurrent();if(t===void 0){let o=r*i;return e.bitrate>o}return r<t&&e.bitrate>r}function Xh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=O.getCurrent();return n.bufferedStart===void 0||e!==null&&e.bufferedEnd!==void 0&&n.bufferedStart-e.bufferedEnd<.1?!1:t<n.bufferedStart&&n.bufferedStart-n.start>r?(p.info("Stream","The start of the wanted segment has been garbage collected",{segmentStart:n.start,currentStartInBuffer:n.bufferedStart}),!0):!1}function Zh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=O.getCurrent();return n.bufferedEnd===void 0||e!==null&&e.bufferedStart!==void 0&&e.bufferedStart-n.bufferedEnd<.1?!1:t>n.bufferedEnd&&n.end-n.bufferedEnd>r?(p.info("Stream","The end of the wanted segment has been garbage collected",{segmentEnd:n.end,currentEndInBuffer:n.bufferedEnd}),!0):!1}function Jh(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.start;if(e!==void 0&&r!==void 0&&e-r>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.start;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function eI(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.end;if(e!==void 0&&r!==void 0&&r-e>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.end;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function tI(n,e,t){return n.filter((r,i,o)=>{let a=i===0?null:o[i-1],s=i>=o.length-1?null:o[i+1],d=null;if(Xh(r,a,e.start)){if(d=t(r.infos),Jh(d,r.bufferedStart))return!1;p.debug("Stream","skipping segment gc-ed at the start",{segmentStart:r.start,currentStartInBuffer:r.bufferedStart})}if(Zh(r,s,e.end)){if(d=d!=null?d:t(r.infos),eI(d,r.bufferedEnd))return!1;p.debug("Stream","skipping segment gc-ed at the end",{segmentEnd:r.end,currentEndInBuffer:r.bufferedEnd})}return!0})}function Ti(n,e){let t=n-e,{SEGMENT_PRIORITIES_STEPS:r}=O.getCurrent();for(let i=0;i<r.length;i++)if(t<r[i])return i;return r.length}function kd(n,e,t,r,i,o,a){var P,M,N;let{representation:s}=n,d=(M=(P=t.getIsPaused())!=null?P:t.getReference().getValue().paused.pending)!=null?M:t.getReference().getValue().paused.last,u=(N=t.getPlaybackRate())!=null?N:t.getReference().getValue().speed,c=e;(d===void 0||u===void 0||d||u<=0)&&(c-=.1);let l=nI(n,c,i),f=s.index.shouldRefresh(l.start,l.end),m=a.getPendingOperations().filter(U=>U.type===2).map(U=>U.value),g=a.getLastKnownInventory(),I=t.getCurrentTime();I===void 0&&(I=t.getReference().getValue().position.getWanted());let h=a.getSegmentHistory.bind(a),{segmentsToLoad:y,segmentsOnHold:T,isBufferFull:v}=Rd({content:n,bufferedSegments:g,currentPlaybackTime:I,fastSwitchThreshold:r,getBufferedHistory:h,neededRange:l,segmentsBeingPushed:m,maxBufferSize:o}),E=y.map(U=>({priority:Ti(U.time,c),segment:U})),R=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&l.hasReachedPeriodEnd&&E.length===0&&T.length===0,k=null;return m.length>0&&(k=Math.min(...m.map(U=>U.segment.time))),T.length>0&&(k=k!==null?Math.min(k,T[0].time):T[0].time),E.length>0&&(k=k!==null?Math.min(k,E[0].segment.time):E[0].segment.time),{imminentDiscontinuity:vd(n,l,k,R,g),hasFinishedLoading:R,neededSegments:E,isBufferFull:v,shouldRefreshManifest:f}}function nI(n,e,t){var l;let r,{manifest:i,period:o,representation:a}=n,s=a.index.getLastAvailablePosition(),d=a.index;!_(s)&&gn.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&rI(i,o,e)?r=s-1:r=e-.1;let u=r+t,c;return!a.index.isInitialized()||a.index.isStillAwaitingFutureSegments()||o.end===void 0?c=!1:s===void 0?c=u>=o.end:s===null?c=!0:c=u>=s,{start:Math.max(r,o.start),end:Math.min(u,(l=o.end)!=null?l:1/0),hasReachedPeriodEnd:c}}function rI(n,e,t){var i;let r=n.getPeriodAfter(e);return e.containsTime(t,r)&&n.isLastPeriodKnown&&e.id===((i=n.periods[n.periods.length-1])==null?void 0:i.id)}async function _i(n,e,t,r,i){try{return await e.pushChunk(t)}catch(o){if(i.isCancelled()&&o instanceof Ee)throw o;if(!(o instanceof He)||!o.isBufferFull){let d=o instanceof Error?o.toString():"An unknown error happened when pushing content";throw new re("BUFFER_APPEND_ERROR",d,{tracks:[Mn(t.inventoryInfos.adaptation)]})}let{position:a}=n.getReference().getValue(),s=a.getWanted();try{p.warn("Stream","Running garbage collector");let d=Math.max(s-5,0),u=s+r.getValue()+12;if(d>0&&await e.removeBuffer(0,d),u<Number.MAX_VALUE&&await e.removeBuffer(u,Number.MAX_VALUE),await An(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof Ee)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new re("BUFFER_FULL_ERROR",u,{tracks:[Mn(t.inventoryInfos.adaptation)]})}}}async function Cd({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:o},a){let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=G({segment:r,chunkSize:void 0,start:0,end:0},e),c=await _i(n,i,{data:d,inventoryInfos:u},o,a);return{content:e,segment:r,buffered:c}}async function Pd({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:o,segmentSink:a},s){var k,A;if(i.chunkData===null)return null;let{chunkData:d,chunkInfos:u,chunkOffset:c,chunkSize:l,appendWindow:f}=i,m=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:g}=O.getCurrent(),I=[f[0]!==void 0?Math.max(0,f[0]-g.START):void 0,f[1]!==void 0?f[1]+g.END:void 0],h={initSegmentUniqueId:r,chunk:d,timestampOffset:c,appendWindow:I,codec:m},y=(k=u==null?void 0:u.time)!=null?k:o.time,T=(A=u==null?void 0:u.duration)!=null?A:o.duration,v=y+T;I[0]!==void 0&&(y=Math.max(y,I[0])),I[1]!==void 0&&(v=Math.min(v,I[1]));let E=G({segment:o,chunkSize:l,start:y,end:v},t),R=await _i(n,a,{data:h,inventoryInfos:E},e,s);return{content:t,segment:o,buffered:R}}function Md({content:n,options:e,playbackObserver:t,segmentSink:r,segmentQueue:i,terminate:o},a,s){p.debug("Stream","Creating RepresentationStream",{periodStart:n.period.start,bufferType:n.adaptation.type,adaptationId:n.adaptation.id,representationBitrate:n.representation.bitrate,mimeType:n.representation.getMimeTypeString()});let{period:d,adaptation:u,representation:c}=n,{bufferGoal:l,maxBufferSize:f,drmSystemId:m,fastSwitchThreshold:g}=e,I=u.type,h=new D;h.linkToSignal(s);let y={segment:c.index.getInitSegment(),uniqueId:null,isLoaded:!1};h.signal.register(()=>{y.uniqueId!==null&&r.freeInitSegment(y.uniqueId)});let T=y.segment!==null;T||(y.isLoaded=!0);let v=!1;if(m!==void 0){let P=c.getEncryptionData(m);if(P.length>0&&P.every(M=>M.keyIds!==void 0)&&(v=!0,a.encryptionDataEncountered(P.map(M=>G({content:n},M))),h.isUsed()))return}i.addEventListener("error",P=>{h.signal.isCancelled()||(h.cancel(),a.error(P))}),i.addEventListener("parsedInitSegment",k,h.signal),i.addEventListener("parsedMediaSegment",k,h.signal),i.addEventListener("emptyQueue",R,h.signal),i.addEventListener("requestRetry",P=>{if(a.warning(P.error),h.signal.isCancelled())return;let M=P.segment,{index:N}=c;N.isSegmentStillAvailable(M)===!1?R():N.canBeOutOfSyncError(P.error,M)&&a.manifestMightBeOufOfSync()},h.signal),i.addEventListener("fullyLoadedSegment",P=>{r.signalSegmentComplete(G({segment:P},n)).catch(A)},h.signal);let E=i.resetForContent(n,T);h.signal.register(()=>{i.stop()}),t.listen(R,{includeLastObservation:!1,clearSignal:h.signal}),n.manifest.addEventListener("manifestUpdate",R,h.signal),l.onUpdate(R,{emitCurrentValue:!1,clearSignal:h.signal}),f.onUpdate(R,{emitCurrentValue:!1,clearSignal:h.signal}),o.onUpdate(R,{emitCurrentValue:!1,clearSignal:h.signal}),R();return;function R(){if(h.isUsed())return;let P=t.getReference().getValue(),M=P.position.getWanted(),N=kd(n,M,t,g.getValue(),l.getValue(),f.getValue(),r),{neededSegments:U}=N,L=null;if(c.index.isInitialized()){if(U.length>0&&!y.isLoaded&&y.segment!==null){let w=U[0].priority;L={segment:y.segment,priority:w}}}else if(y.segment===null)p.warn("Stream","Uninitialized index without an initialization segment",{bufferType:I,representationBitrate:n.representation.bitrate});else if(y.isLoaded)p.warn("Stream","Uninitialized index with an already loaded initialization segment",{bufferType:I,representationBitrate:n.representation.bitrate});else{let w=P.position.getWanted();L={segment:y.segment,priority:Ti(d.start,w)}}let B=o.getValue();if(B===null)E.setValue({initSegment:L,segmentQueue:U});else if(B.urgent){p.debug("Stream","Urgent switch, terminate now.",{bufferType:I,representationBitrate:n.representation.bitrate}),E.setValue({initSegment:null,segmentQueue:[]}),E.finish(),h.cancel(),a.terminating();return}else{let w=U[0],F=i.getRequestedInitSegment(),K=i.getRequestedMediaSegment(),Y=K===null||w===void 0||K.id!==w.segment.id?[]:[w],ie=F===null?null:L;if(E.setValue({initSegment:ie,segmentQueue:Y}),Y.length===0&&ie===null){p.debug("Stream","No request left, terminate",{bufferType:I,representationBitrate:n.representation.bitrate}),E.finish(),h.cancel(),a.terminating();return}}if(a.streamStatusUpdate({period:d,position:P.position.getWanted(),bufferType:I,imminentDiscontinuity:N.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:N.hasFinishedLoading,neededSegments:N.neededSegments}),h.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:C}=O.getCurrent();if(N.isBufferFull){let w=Math.max(0,M-C);w>0&&r.removeBuffer(0,w).catch(A)}N.shouldRefreshManifest&&a.needsManifestRefresh()}function k(P){for(let M of P.protectionData)c.addProtectionData(M.initDataType,M.keyId,M.initData);if(!v){let M=c.getAllEncryptionData();M.length>0&&(a.encryptionDataEncountered(M.map(N=>G({content:n},N))),v=!0)}if(P.segmentType==="init"){if(!c.index.isInitialized()&&P.segmentList!==void 0&&c.index.initialize(P.segmentList),y.isLoaded=!0,P.initializationData!==null){let M=c.uniqueId;y.uniqueId=M,r.declareInitSegment(M,P.initializationData),Cd({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:M,segment:P.segment,segmentData:P.initializationData,segmentSink:r},h.signal).then(N=>{N!==null&&a.addedSegment(N)}).catch(A)}R();return}else{let{inbandEvents:M,predictedSegments:N,needsManifestRefresh:U}=P;if(N!==void 0&&c.index.addPredictedSegments(N,P.segment),U===!0&&(a.needsManifestRefresh(),h.isUsed())||M!==void 0&&M.length>0&&(a.inbandEvent(M),h.isUsed()))return;let L=y.uniqueId;Pd({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:L,parsedSegment:P,segment:P.segment,segmentSink:r},h.signal).then(B=>{B!==null&&a.addedSegment(B)}).catch(A)}}function A(P){h.isUsed()&&P instanceof Ee||(p.warn("Stream","Received fatal buffer error",{bufferType:I,representationBitrate:n.representation.bitrate},P instanceof Error?P:null),h.cancel(),a.error(P))}}var rm=Md;function Ad(n,e,t,r,i){var f,m,g,I;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let o=r.getLastKnownInventory(),a=[];for(let h of o)h.infos.period.id===n.id&&(h.infos.adaptation.id!==e.id||!J(t.representationIds,h.infos.representation.id))&&Ut(a,{start:(f=h.bufferedStart)!=null?f:h.start,end:(m=h.bufferedEnd)!=null?m:h.end});let s=r.getPendingOperations();for(let h of s)if(h.type===0){let y=h.value.inventoryInfos;if(y.period.id===n.id&&(y.adaptation.id!==e.id||!J(t.representationIds,y.representation.id))){let T=y.segment.time,v=T+y.segment.duration;Ut(a,{start:T,end:v})}}if(a.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let h=i.getReadyState();if(h===void 0||h>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],c=cr(o,n);if(c!==null&&(c.bufferedEnd===void 0||n.start-c.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:h}=O.getCurrent(),y=e.type,T=(g=h[y].before)!=null?g:0,v=(I=h[y].after)!=null?I:0,E=i.getCurrentTime();E===void 0&&(E=i.getReference().getValue().position.getPolled()),u.push({start:E-T,end:E+v})}if(n.end!==void 0){let h=fr(o,n);h!==null&&(h.bufferedStart===void 0||h.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let l=Ca(a,u);return l.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:l}:{type:"clean-buffer",value:l}}function xd({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:o,wantedBufferAhead:a,maxVideoBufferSize:s},d,u){let{manifest:c,period:l,adaptation:f}=e,m=new D;m.linkToSignal(u);let g=new Map,I=new W(null,m.signal),h,y=e.representations.getValue().representationIds,T=im(e.adaptation.representations,y),v=new W(T,m.signal),{estimates:E,callbacks:R}=r({manifest:c,period:l,adaptation:f},I,v,n,m.signal),k=new W(!1);n.listen(C=>{var F;let w=(F=C.canStream)!=null?F:!0;k.getValue()===w&&(p.debug("Stream","isMediaSegmentQueueInterrupted updated to",!w),k.setValue(!w))},{clearSignal:m.signal});let A=o.createSegmentQueue(f.type,{onRequestBegin:R.requestBegin,onRequestEnd:R.requestEnd,onProgress:R.requestProgress,onMetrics:R.metrics},k),P=new W(0);E.onUpdate(({bitrate:C,knownStableBitrate:w})=>{t.enableFastSwitching&&P.setValueIfChanged(w),!(C===void 0||C===h)&&(h=C,p.debug("Stream",`new ${f.type} bitrate estimate received from ABR`,{bitrate:C}),d.bitrateEstimateChange({type:f.type,bitrate:C}))},{emitCurrentValue:!0,clearSignal:m.signal});let M;e.representations.onUpdate(C=>{M!==void 0&&M.cancel();let w=e.representations.getValue().representationIds,F=im(e.adaptation.representations,w);v.setValueIfChanged(F),M=new D,M.linkToSignal(m.signal),N(C,M.signal).catch(K=>{(M==null?void 0:M.isUsed())===!0&&D.isCancellationError(K)||(m.cancel(),d.error(K))})},{clearSignal:m.signal,emitCurrentValue:!0});return;async function N(C,w){let F=Ad(l,f,C,i,n);switch(F.type){case"continue":break;case"needs-reload":return Rt(()=>{n.listen(()=>{if(w.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:K}=O.getCurrent(),Y=K.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:Y,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:w})});case"flush-buffer":case"clean-buffer":for(let K of F.value)if(await i.removeBuffer(K.start,K.end),w.isCancelled())return;if(F.type==="flush-buffer"&&(d.needsBufferFlush(),w.isCancelled()))return;break;default:we(F)}U(w)}function U(C){let w=new D;w.linkToSignal(C);let{representation:F}=E.getValue();if(F===null)return;let K=new W(null,w.signal);E.onUpdate(j=>{if(!(j.representation===null||j.representation.id===F.id))return j.urgent?(p.info("Stream","urgent Representation switch",{bufferType:f.type,estimateBitrate:j.bitrate,prevRepresentationBitrate:F.bitrate,newRepresentationBitrate:j.representation.bitrate}),K.setValue({urgent:!0})):(p.info("Stream","slow Representation switch",{bufferType:f.type,estimateBitrate:j.bitrate,prevRepresentationBitrate:F.bitrate,newRepresentationBitrate:j.representation.bitrate}),K.setValue({urgent:!1}))},{clearSignal:w.signal,emitCurrentValue:!0});let Y={type:f.type,adaptation:f,period:l,representation:F};if(I.setValue(F),C.isCancelled()||(d.representationChange(Y),C.isCancelled()))return;let ie={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(j){m.cancel(),d.error(j)},addedSegment(j){R.addedSegment(j)},terminating(){if(!w.isUsed())return w.cancel(),U(C)}};L(F,K,ie,C)}function L(C,w,F,K){let Y=!1,ie=new D;ie.linkToSignal(K);let j=vn(a,X=>B(C,X),ie.signal),Q=f.type==="video"?s:new W(1/0);p.info("Stream","changing representation",{bufferType:f.type,representationId:C.id,representationBitrate:C.bitrate});let ne=G({},F,{error(X){var ue;if(Y){p.warn("Stream","Ignoring RepresentationStream error",X);return}Y=!0;let de=Ae(X,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(de.code!=="BUFFER_FULL_ERROR")F.error(X);else{p.warn("Stream","received BUFFER_FULL_ERROR",{bufferType:f.type,representationBitrate:C.bitrate});let ve=a.getValue(),ye=((ue=g.get(C.id))!=null?ue:1)*.7;if(g.set(C.id,ye),ye<=.05||B(C,ve)<=2){F.error(de);return}un(4e3,K).then(()=>L(C,w,F,K)).catch(ae)}},terminating(){ie.cancel(),F.terminating()}});rm({playbackObserver:n,content:{representation:C,adaptation:f,period:l,manifest:c},segmentSink:i,segmentQueue:A,terminate:w,options:{bufferGoal:j,maxBufferSize:Q,drmSystemId:t.drmSystemId,fastSwitchThreshold:P}},ne,K),c.addEventListener("manifestUpdate",X=>{for(let de of X.updatedPeriods)if(de.period.id===l.id){for(let ue of de.result.updatedAdaptations)if(ue.adaptation===f.id){for(let ve of ue.removedRepresentations)if(ve===C.id)return K.isCancelled()?void 0:d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:0,stayInPeriod:!0})}}else if(de.period.start>l.start)break},K)}function B(C,w){let F=g.get(C.id),K=F!==void 0?F:1;return F===void 0&&g.set(C.id,K),K<1&&w===1/0?300*1e3*K:w*K}}function im(n,e){let t=n.filter(r=>J(e,r.id)&&!r.shouldBeAvoided&&r.isPlayable()!==!1);return t.length>0?t:n.filter(r=>J(e,r.id)&&r.isPlayable()!==!1)}var om=xd;function wd(n,e,t,r,i,o){var m,g,I,h;if(n.codec!==void 0&&o.onCodecSwitch==="reload"&&!iI(t,n.codec))return{type:"needs-reload",value:void 0};let a=n.getLastKnownInventory(),s=[];for(let y of a)y.infos.period.id===e.id&&y.infos.adaptation.id!==t.id&&Ut(s,{start:(m=y.bufferedStart)!=null?m:y.start,end:(g=y.bufferedEnd)!=null?g:y.end});let d=n.getPendingOperations();for(let y of d)if(y.type===0){let T=y.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let v=T.segment.time,E=v+T.segment.duration;Ut(s,{start:v,end:E})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let y=i.getReadyState();if(y===void 0||y>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",c=[],l=cr(a,e);if(l!==null&&(l.bufferedEnd===void 0||e.start-l.bufferedEnd<1)&&c.push({start:0,end:e.start+1}),!u){let y=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=O.getCurrent(),v=(I=T[y].before)!=null?I:0,E=(h=T[y].after)!=null?h:0,R=i.getCurrentTime();R===void 0&&(R=i.getReference().getValue().position.getPolled()),c.push({start:R-v,end:R+E})}if(e.end!==void 0){let y=fr(a,e);y!==null&&(y.bufferedStart===void 0||y.bufferedStart-e.end<1)&&c.push({start:e.end-1,end:Number.MAX_VALUE})}let f=Ca(s,c);return f.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:f}:{type:"clean-buffer",value:f}}function iI(n,e){return n.representations.some(t=>t.isPlayable()===!0&&va(t.getMimeTypeString(),e))}function Od({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:o,segmentSinksStore:a,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},c,l){let{manifest:f,period:m}=e,g=new W(void 0,l);if(c.periodStreamReady({type:n,manifest:f,period:m,adaptationRef:g}),l.isCancelled())return;let I,h=!0;g.onUpdate(v=>{(async()=>{var B;if(v===void 0)return;let E=new D;if(E.linkToSignal(l),I==null||I.cancel(),I=E,v===null){p.info("Stream","Set no Adaptation",{periodStart:m.start,bufferType:n});let C=a.getStatus(n);if(C.type==="initialized"){if(p.info("Stream","Clearing previous SegmentSink",{periodStart:m.start,bufferType:n}),gn.isNative(n))return T(0,!0,E.signal);{let w=(B=m.end)!=null?B:1/0;if(m.start>w)p.warn("Stream","Can't free buffer: period's start is after its end",{periodStart:m.start,periodEnd:w,bufferType:n});else if(await C.value.removeBuffer(m.start,w),E.isUsed())return}}else if(C.type==="uninitialized"&&(a.disableSegmentSink(n),E.isUsed()))return;return c.adaptationChange({type:n,adaptation:null,period:m}),E.isUsed()?void 0:am(r,d,n,{period:m},c,E.signal)}let R=m.adaptations[n],k=q(R!=null?R:[],C=>C.id===v.adaptationId);if(k===void 0){I.cancel(),p.warn("Stream","Unfound chosen Adaptation choice",{adaptationId:v.adaptationId});return}let{DELTA_POSITION_AFTER_RELOAD:A}=O.getCurrent(),P=!1,M;if(h)M=0;else if(v.relativeResumingPosition!==void 0)M=v.relativeResumingPosition;else switch(P=!0,n){case"audio":M=A.trackSwitch.audio;break;case"video":M=A.trackSwitch.video;break;default:M=A.trackSwitch.other;break}if(h=!1,gn.isNative(n)&&a.getStatus(n).type==="disabled")return T(M,!0,E.signal);f.addEventListener("manifestUpdate",C=>{for(let w of C.updatedPeriods)if(w.period.id===m.id){for(let F of w.result.removedAdaptations)if(F.id===k.id)return T(M,!0,E.signal)}else if(w.period.start>m.start)break},I.signal);let{representations:N}=v;if(p.info("Stream","Updating adaptation",{bufferType:k.type,periodStart:m.start,adaptationId:k.id}),c.adaptationChange({type:n,adaptation:k,period:m}),E.isUsed())return;let U=oI(a,n,k),L=wd(U,m,k,v.switchingMode,r,s);if(L.type==="needs-reload")return T(M,!0,E.signal);if(await a.waitForUsableBuffers(E.signal),!E.isUsed()){if(L.type==="flush-buffer"||L.type==="clean-buffer"){for(let{start:C,end:w}of L.value)if(await U.removeBuffer(C,w),E.isUsed())return;if(L.type==="flush-buffer"&&(c.needsBufferFlush({relativeResumingPosition:M,relativePosHasBeenDefaulted:P}),E.isUsed()))return}t.get(U)(E.signal),y(k,N,U,E.signal)}})().catch(E=>{E instanceof Ee||(I==null||I.cancel(),c.error(E))})},{clearSignal:l,emitCurrentValue:!0});function y(v,E,R,k){let A=sI(r,v.type);om({content:{manifest:f,period:m,adaptation:v,representations:E},options:s,playbackObserver:A,representationEstimator:i,segmentSink:R,segmentQueueCreator:o,wantedBufferAhead:d,maxVideoBufferSize:u},me(oe({},c),{error:P}),k);function P(M){if(!gn.isNative(n)){p.error("Stream",`${n} Stream crashed. Aborting it.`,M instanceof Error?M:""),a.disposeSegmentSink(n);let N=Ae(M,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return c.warning(N),k.isCancelled()?void 0:am(r,d,n,{period:m},c,k)}p.error("Stream",`${n} Stream crashed. Stopping playback.`,M instanceof Error?M:""),c.error(M)}}function T(v,E,R){Rt(()=>{r.listen(()=>{R.isCancelled()||c.waitingMediaSourceReload({bufferType:n,period:m,timeOffset:v,stayInPeriod:E})},{includeLastObservation:!0,clearSignal:R})})}}function oI(n,e,t){let r=n.getStatus(e);if(r.type==="initialized")return p.info("Stream","Reusing a previous SegmentSink for the type",{bufferType:e}),r.value;let i=aI(t);return n.createSegmentSink(e,i)}function aI(n){let e=n.representations.filter(t=>t.isPlayable()!==!1);if(e.length>0)return e[0].getMimeTypeString();if(n.representations.length>0)return n.representations[0].getMimeTypeString();throw new re("NO_PLAYABLE_REPRESENTATION","No Representation in the chosen "+n.type+" Adaptation can be played",{tracks:[Mn(n)]})}function sI(n,e){return n.deriveReadOnlyObserver(function(r,i){let o=new W(a(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),o;function a(){let d=r.getValue(),u=d.buffered[e],c=u!==null?ka(u,d.position.getWanted()):0;return G({},d,{bufferGap:c,buffered:u})}function s(){o.setValue(a())}})}function am(n,e,t,r,i,o){let{period:a}=r,s=!1;e.onUpdate(d,{emitCurrentValue:!1,clearSignal:o}),n.listen(d,{includeLastObservation:!1,clearSignal:o}),d();function d(){let u=n.getReference().getValue(),c=e.getValue(),l=u.position.getWanted();a.end!==void 0&&l+c>=a.end&&(p.debug("Stream",'full "empty" AdaptationStream',{bufferType:t,periodEnd:a.end,position:l,wantedBufferAhead:c}),s=!0),i.streamStatusUpdate({period:a,bufferType:t,imminentDiscontinuity:null,position:l,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var sm=Od;function xa(n,e){if(e.length===0)return[];let t=[],r=n.getLastKnownInventory(),i=n.getPendingOperations();for(let o of r)if(e.some(s=>o.infos.period.id===s.period.id&&o.infos.adaptation.id===s.adaptation.id&&o.infos.representation.id===s.representation.id)){let{bufferedStart:s,bufferedEnd:d}=o;if(s===void 0||d===void 0)return p.warn("Stream","No buffered start or end found from a segment.",{bufferType:o.infos.adaptation.type,segmentStart:o.infos.segment.time}),[{start:0,end:Number.MAX_VALUE}];let u=t[t.length-1];u!==void 0&&u.end===s?u.end=d:t.push({start:s,end:d})}for(let o of i){if(o.type!==0)continue;let a=o.value;e.some(d=>a.inventoryInfos.period.id===d.period.id&&a.inventoryInfos.adaptation.id===d.adaptation.id&&a.inventoryInfos.representation.id===d.representation.id)&&Ut(t,{start:a.inventoryInfos.start,end:a.inventoryInfos.end})}return t}function Dd(n,e,t,r,i,o,a,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:c,maxBufferBehind:l,wantedBufferAhead:f,maxVideoBufferSize:m}=o,{MINIMUM_MAX_BUFFER_AHEAD:g,MAXIMUM_MAX_BUFFER_AHEAD:I,MAXIMUM_MAX_BUFFER_BEHIND:h}=O.getCurrent(),y=new gi(E=>{var P,M;let{bufferType:R}=E,k=(P=h[R])!=null?P:1/0,A=(M=I[R])!=null?M:1/0;return N=>{Pa({segmentSink:E,playbackObserver:e,maxBufferBehind:vn(l,U=>Math.min(U,k),N),maxBufferAhead:vn(c,U=>{var B;let L=Math.max(U,(B=g[R])!=null?B:0);return Math.min(L,A)},N)},N)}});for(let E of r.getBufferTypes())T(E,u);function T(E,R){let k=new Nn((L,B)=>L.start-B.start),A=!1,P=new D;return P.linkToSignal(s),e.listen(({position:L})=>{let B=L.getWanted();if(!A||!N(B))return;let C=()=>{var F;return(F=d.getPeriodForTime(B))!=null?F:d.getNextPeriod(B)},w=C();if(!(!_(w)&&k.has(w))){for(p.info("Stream","Destroying all PeriodStreams due to out of bounds situation",{bufferType:E,time:B}),A=!1;k.length()>0;){let F=k.get(k.length()-1);k.removeElement(F),a.periodStreamCleared({type:E,manifest:d,period:F})}if(P.cancel(),P=new D,P.linkToSignal(s),w=C(),w===void 0){p.warn("Stream","The wanted position is not found in the Manifest."),A=!0;return}M(w)}},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",L=>{s.isCancelled()||U(L).catch(B=>{s.isCancelled()||(P.cancel(),a.error(B))})},s),M(R);function M(L){let B=me(oe({},a),{waitingMediaSourceReload(C){let w=k.head();w===void 0||w.id!==C.period.id?a.lockedStream({bufferType:C.bufferType,period:C.period}):a.needsMediaSourceReload({timeOffset:C.timeOffset,minimumPosition:C.stayInPeriod?C.period.start:void 0,maximumPosition:C.stayInPeriod?C.period.end:void 0})},periodStreamReady(C){A=!0,k.add(C.period),a.periodStreamReady(C)},periodStreamCleared(C){k.removeElement(C.period),a.periodStreamCleared(C)},error(C){P.cancel(),a.error(C)}});v(E,L,B,P.signal)}function N(L){let B=k.head(),C=k.last();return B===void 0||C===void 0?!0:B.start>L||(_(C.end)?1/0:C.end)<L}async function U(L){let B=r.getStatus(E),C=L.filter(j=>j.adaptation.type===E);if(C.length===0||B.type!=="initialized"||C.every(j=>j.representation.decipherable===!0))return;let w=B.value,F=C.filter(j=>j.representation.decipherable===void 0),K=C.filter(j=>j.representation.decipherable===!1),Y=xa(w,K),ie=xa(w,F);for(A=!1,p.info("Stream","Destroying all PeriodStreams for decipherability matters",{bufferType:E});k.length()>0;){let j=k.get(k.length()-1);k.removeElement(j),a.periodStreamCleared({type:E,manifest:d,period:j})}P.cancel(),P=new D,P.linkToSignal(s);for(let{start:j,end:Q}of[...Y,...ie]){if(s.isCancelled())return;if(j<Q){if(s.isCancelled())return;await w.removeBuffer(j,Q)}}Rt(()=>{if(s.isCancelled())return;let j=e.getReference().getValue();if(dm(j,Y)){if(a.needsDecipherabilityFlush(),s.isCancelled())return}else if(dm(j,ie)&&(a.needsBufferFlush(),s.isCancelled()))return;let Q=j.position.getWanted(),ne=d.getPeriodForTime(Q);if(ne===void 0&&(ne=d.getNextPeriod(Q),p.warn("Stream","No Period found for the reloading position, selecting next one instead",{reloadPosition:Q,nextPeriodStart:ne==null?void 0:ne.start})),ne===void 0&&(ne=d.periods[d.periods.length-1],p.warn("Stream","No Period found for of after the reloading position, selecting the last one",{reloadPosition:Q,nextPeriodStart:ne==null?void 0:ne.start,nextPeriodEnd:ne==null?void 0:ne.end})),ne===void 0){a.error(new re("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}M(ne)})}}function v(E,R,k,A){p.info("Stream","Creating new PeriodStream",{bufferType:E,periodStart:R.start});let P=null,M=new D;M.linkToSignal(A),e.listen(({position:C},w)=>{if(R.end!==void 0&&C.getWanted()>=R.end){let F=d.getPeriodAfter(R);if(R.containsTime(C.getWanted(),F))return;p.info("Stream","Destroying PeriodStream as the current playhead moved above it",{bufferType:E,periodStart:R.start,periodEnd:R.end,position:C.getWanted()}),w(),k.periodStreamCleared({type:E,manifest:d,period:R}),M.cancel()}},{clearSignal:A,includeLastObservation:!0});let N={bufferType:E,content:{manifest:d,period:R},garbageCollectors:y,maxVideoBufferSize:m,segmentQueueCreator:i,segmentSinksStore:r,options:o,playbackObserver:e,representationEstimator:t,wantedBufferAhead:f},U=me(oe({},k),{streamStatusUpdate(C){if(C.hasFinishedLoading){let w=d.getPeriodAfter(R);w!==null&&L(w)}else P!==null&&(p.info("Stream","Destroying next PeriodStream due to current one being active",{bufferType:E,periodStart:R.start,nextPeriodStart:P.period.start}),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel(),P=null);k.streamStatusUpdate(C)},error(C){P!==null&&(P.canceller.cancel(),P=null),M.cancel(),k.error(C)}});sm(N,U,M.signal),B(M.signal);function L(C){if(P!==null){if(P.period.id===C.id)return;p.warn("Stream","Creating next `PeriodStream` while one was already created.",{bufferType:E,nextPeriodStart:C.start}),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel()}let w=new D;w.linkToSignal(A),P={canceller:w,period:C},v(E,C,k,P.canceller.signal)}function B(C){d.addEventListener("manifestUpdate",w=>{for(let F of w.removedPeriods)if(F.id===R.id){if(d.periods.length>0&&d.periods[0].start<=F.start)return Rt(()=>{if(!C.isCancelled())return a.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(F.start>R.start)break;if(w.addedPeriods.length>0&&P!==null){let F=d.getPeriodAfter(R);(F===null||P.period.id!==F.id)&&(p.warn("Stream","Destroying next PeriodStream due to new one being added",{bufferType:E,nextPeriodStart:P.period.start}),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel(),P=null)}},C)}}}function dm(n,e){if(e.length===0)return!1;let t=n.position.getPolled();return n.speed>=0?e[e.length-1].end>=t-5:e[0].start<=t+5}var um=Dd;var lm=um;function Ld(n,e){if(typeof n.changeType=="function"){try{n.changeType(e)}catch(t){return p.warn("mse","Could not call 'changeType' on the given SourceBuffer:",t instanceof Error?t:""),!1}return!0}return!1}function dI(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function Ei(n,e){if(p.debug("mse","Trying to call endOfStream"),n.readyState!=="open"){p.debug("mse","MediaSource not open, cancel endOfStream");return}let{sourceBuffers:t}=n,r=dI(t);if(r.length===0){p.info("mse","Triggering end of stream");try{n.endOfStream()}catch(o){p.error("mse","Unable to call endOfStream",o instanceof Error?o:new Error("Unknown error"))}return}p.debug("mse","Waiting SourceBuffers to be updated before calling endOfStream.");let i=new D;i.linkToSignal(e);for(let o of r)tf(o,()=>{i.cancel(),Ei(n,e)},i.signal);nf(t,()=>{i.cancel(),Ei(n,e)},i.signal)}function cm(n,e){let t=new D;t.linkToSignal(e),rr(n,()=>{p.debug("mse","MediaSource re-opened while end-of-stream is active"),t.cancel(),t=new D,t.linkToSignal(e),Ei(n,t.signal)},e),Ei(n,t.signal)}function Nd(){let{FORCE_HAS_ISSUES_WITH_HIGH_MEDIA_SOURCE_DURATION:n}=O.getCurrent();return n||V.device===V.DEVICES.PlayStation5}var uI=365*24*3600,vi=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=new D;let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,o=fI(r,i),a=new D;a.linkToSignal(i),o.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(a.cancel(),!o.getValue())return;a=new D,a.linkToSignal(i);let d=cI(r.sourceBuffers,a.signal),u=new D;return u.linkToSignal(a.signal),d.onUpdate(c=>{u.cancel(),u=new D,u.linkToSignal(a.signal),!c&&mm(r,e,t,u.signal)},{clearSignal:a.signal,emitCurrentValue:!0})}}stopUpdating(){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=null)}};function lI(n,e,t){let r=e;t||(r=Nd()?1/0:fm(e));let i=0;for(let o=0;o<n.sourceBuffers.length;o++){let a=n.sourceBuffers[o],s=a.buffered.length;s>0&&(i=Math.max(i,a.buffered.end(s-1)))}if(r===n.duration)return"success";if(i>r){if(i<n.duration)try{p.info("mse","Updating duration to what is currently buffered",{maxBufferedEnd:i}),n.duration=i}catch(o){return p.warn("mse","Can't update duration on the MediaSource.",o instanceof Error?o:""),"failed"}return"partial"}else{let o=n.duration;try{if(p.info("mse","Updating duration",{newDuration:r}),n.duration=r,n.readyState==="open"&&!isFinite(r)){let s=fm(e);p.info("mse","calling `mediaSource.setLiveSeekableRange`",{maxSeekable:s}),n.setLiveSeekableRange(0,s)}}catch(s){return p.warn("mse","Can't update duration on the MediaSource.",s instanceof Error?s:""),"failed"}let a=Math.abs(n.duration-r);if(a>=.1){let s=Math.abs(n.duration-o);return a<s?"partial":"failed"}return"success"}}function cI(n,e){if(n.length===0){let i=new W(!1);return i.finish(),i}let t=new W(!1,e);r();for(let i=0;i<n.length;i++){let o=n[i];o.addEventListener("updatestart",r),o.addEventListener("update",r),e.register(()=>{o.removeEventListener("updatestart",r),o.removeEventListener("update",r)})}return t;function r(){for(let i=0;i<n.length;i++)if(n[i].updating){t.setValueIfChanged(!0);return}t.setValueIfChanged(!1)}}function fI(n,e){let t=new W(n.readyState==="open",e);return rr(n,()=>{p.debug("mse","Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),aa(n,()=>{p.debug("mse","Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),oa(n,()=>{p.debug("mse","Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function mm(n,e,t,r){if(lI(n,e,t)==="success")return;let o=setTimeout(()=>{a(),mm(n,e,t,r)},2e3),a=r.register(()=>{clearTimeout(o)})}function fm(n){return Math.max(Math.pow(2,32),n+uI)}var Bn=class extends se{constructor(e,t){if(super(),this.id=e,this.sourceBuffers=[],this._canceller=new D,_(ht))throw new re("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");p.info("mse","Creating MediaSource");let r=t!==void 0?new t:new ht,i=r.handle;this.handle=_(i)?{type:"media-source",value:r}:{type:"handle",value:i},this._mediaSource=r,this.readyState=r.readyState,this._durationUpdater=new vi(r),this._endOfStreamCanceller=null,rr(r,()=>{this.readyState=r.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),aa(r,()=>{this.readyState=r.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),oa(r,()=>{this.readyState=r.readyState,this.trigger("mediaSourceClose",null)},this._canceller.signal),this._mediaSource.streaming!==void 0&&(this.streaming=this._mediaSource.streaming),this._mediaSource.addEventListener("startstreaming",()=>{this.streaming=!0,this.trigger("streamingChanged",null)}),this._mediaSource.addEventListener("endstreaming",()=>{this.streaming=!1,this.trigger("streamingChanged",null)})}addSourceBuffer(e,t){let r=this._mediaSource.addSourceBuffer(t),i=new Bd(e,t,r);return this.sourceBuffers.push(i),i}setDuration(e,t){this._durationUpdater.updateDuration(e,t)}interruptDurationSetting(){this._durationUpdater.stopUpdating()}maintainEndOfStream(){this._endOfStreamCanceller===null&&(this._endOfStreamCanceller=new D,this._endOfStreamCanceller.linkToSignal(this._canceller.signal),p.debug("mse","end-of-stream order received."),cm(this._mediaSource,this._endOfStreamCanceller.signal))}stopEndOfStream(){this._endOfStreamCanceller!==null&&(p.debug("mse","resume-stream order received."),this._endOfStreamCanceller.cancel(),this._endOfStreamCanceller=null)}dispose(){this.sourceBuffers.forEach(e=>e.dispose()),this._canceller.cancel(),mI(this._mediaSource)}},Bd=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new D,this._sourceBuffer=r,this._operationQueue=[],this._currentOperations=[];let i=this._onError.bind(this),o=this._onUpdateEnd.bind(this);r.addEventListener("updateend",o),r.addEventListener("error",i),this._canceller.signal.register(()=>{r.removeEventListener("updateend",o),r.removeEventListener("error",i)})}appendBuffer(...e){return p.debug("mse","receiving order to push data to the SourceBuffer",{type:this.type}),this._addToQueue({operationName:0,params:e})}remove(e,t){return p.debug("mse","receiving order to remove data from the SourceBuffer",{type:this.type,start:e,end:t}),this._addToQueue({operationName:1,params:[e,t]})}getBuffered(){try{return We(this._sourceBuffer.buffered)}catch(e){return p.error("mse","Failed to get buffered time range of SourceBuffer",{type:this.type},e instanceof Error?e:"Unknown Error"),[]}}abort(){try{this._sourceBuffer.abort()}catch(e){p.debug("mse","Failed to abort SourceBuffer:",e instanceof Error?e:"Unknown Error")}this._emptyCurrentQueue()}dispose(){try{this._sourceBuffer.abort()}catch(e){}this._emptyCurrentQueue()}_onError(e){let t;e instanceof Error?t=e:e.error instanceof Error?t=e.error:t=new Error("Unknown SourceBuffer Error");let r=this._currentOperations;if(this._currentOperations=[],r.length===0)p.error("mse","error for an unknown operation",t);else{let i=new He(t.name,t.message,t.name==="QuotaExceededError");for(let o of r)o.reject(i)}}_onUpdateEnd(){let e=this._currentOperations;this._currentOperations=[];try{for(let t of e)t.resolve(We(this._sourceBuffer.buffered))}catch(t){for(let r of e)t instanceof Error&&t.name==="InvalidStateError"?r.resolve([]):r.reject(t)}this._performNextOperation()}_emptyCurrentQueue(){let e=new Ee;this._currentOperations.length>0&&(this._currentOperations.forEach(t=>{t.reject(e)}),this._currentOperations=[]),this._operationQueue.length>0&&(this._operationQueue.forEach(t=>{t.reject(e)}),this._operationQueue=[])}_addToQueue(e){return new Promise((t,r)=>{let i=this._operationQueue.length===0&&this._currentOperations.length===0,o=G({resolve:t,reject:r},e);this._operationQueue.push(o),i&&this._performNextOperation()})}_performNextOperation(){var t,r,i,o,a;if(this._currentOperations.length!==0||this._sourceBuffer.updating)return;let e=this._operationQueue.shift();if(e!==void 0)if(e.operationName===0){this._currentOperations=[{operationName:0,resolve:e.resolve,reject:e.reject}];let s=e.params[0],d=e.params[1],u=s;if(this._operationQueue.length>0&&this._operationQueue[0].operationName===0){let c;s instanceof ArrayBuffer?c=new Uint8Array(s):s instanceof Uint8Array?c=s:c=new Uint8Array(s.buffer);let l=[c];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let f=this._operationQueue[0],m=(r=d.appendWindow)!=null?r:[void 0,void 0],g=(i=f.params[1].appendWindow)!=null?i:[void 0,void 0],I=(o=d.timestampOffset)!=null?o:0,h=(a=f.params[1].timestampOffset)!=null?a:0;if(m[0]===g[0]&&m[1]===g[1]&&d.codec===f.params[1].codec&&I===h){let y=f.params[0],T;y instanceof ArrayBuffer?T=new Uint8Array(y):y instanceof Uint8Array?T=y:T=new Uint8Array(y.buffer),l.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:f.resolve,reject:f.reject})}else break}l.length>1&&(p.info("mse",`: Merging ${l.length} segments together for perf`,{type:this.type}),u=le(...l).buffer)}try{this._appendBufferNow(u,d)}catch(c){let l=c instanceof Error?new He(c.name,c.message,c.name==="QuotaExceededError"):new He("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(f=>{f.reject(l)}),this._currentOperations=[],this._performNextOperation()}}else{this._currentOperations=[e];let[s,d]=e.params;p.debug("mse","removing data from SourceBuffer",{type:this.type,start:s,end:d});try{this._sourceBuffer.remove(s,d)}catch(u){let c=u instanceof Error?new He(u.name,u.message,!1):new He("Error","Unknown SourceBuffer Error during remove",!1);e.reject(c),this._currentOperations.forEach(l=>{l.reject(c)}),this._currentOperations=[],this._performNextOperation()}}}_appendBufferNow(e,t){let r=this._sourceBuffer,{codec:i,timestampOffset:o,appendWindow:a=[]}=t;if(i!==void 0&&i!==this.codec&&(p.debug("mse","updating codec",{prevCodec:this.codec,newCodec:i}),Ld(r,i)?this.codec=i:p.debug("mse","could not update codec",{prevCodec:this.codec,newCodec:i})),o!==void 0&&r.timestampOffset!==o){let s=o;p.debug("mse","updating timestampOffset",{codec:i,prevTimestampOffset:r.timestampOffset,newTimestampOffset:s}),r.timestampOffset=s}if(a[0]===void 0)r.appendWindowStart>0&&(p.debug("mse","re-setting `appendWindowStart`",{prevWindowStart:r.appendWindowStart}),r.appendWindowStart=0);else if(a[0]!==r.appendWindowStart){if(a[0]>=r.appendWindowEnd){let s=a[0]+1;p.debug("mse","pre-updating `appendWindowEnd`",{prevWindowEnd:r.appendWindowEnd,newWindowEnd:s}),r.appendWindowEnd=s}p.debug("mse","setting `appendWindowStart`",{appendWindowStart:a[0]}),r.appendWindowStart=a[0]}a[1]===void 0?r.appendWindowEnd!==1/0&&(p.debug("mse","re-setting `appendWindowEnd`",{prevWindowStart:r.appendWindowStart}),r.appendWindowEnd=1/0):a[1]!==r.appendWindowEnd&&(p.debug("mse","setting `appendWindowEnd`",{prevWindowEnd:r.appendWindowEnd,newWindowEnd:a[1]}),r.appendWindowEnd=a[1]),p.debug("mse","pushing segment",{type:this.type}),r.appendBuffer(e)}};function mI(n){if(n.readyState!=="closed"){let{readyState:e,sourceBuffers:t}=n;for(let r=t.length-1;r>=0;r--){let i=t[r];try{if(e==="open"){p.info("mse","Aborting SourceBuffer before removing");try{i.abort()}catch(o){}}p.info("mse","Removing SourceBuffer from mediaSource"),n.removeSourceBuffer(i)}catch(o){}}t.length>0&&p.info("mse","Not all SourceBuffers could have been removed.")}}var pI=Fe(),wa=Fe(),pm=1/0,Ri=class extends se{constructor(e,t,r){super(),this.id=e,this.sourceBuffers=[],this._canceller=new D,this.readyState="closed",this._messageSender=r;let i=pI();this._messageSender({type:"create-media-source",contentId:t,mediaSourceId:i})}onMediaSourceReadyStateChanged(e){switch(e){case"closed":this.readyState="closed",this.trigger("mediaSourceClose",null);break;case"open":this.readyState="open",this.trigger("mediaSourceOpen",null);break;case"ended":this.readyState="ended",this.trigger("mediaSourceEnded",null);break}}addSourceBuffer(e,t){this._messageSender({type:"add-source-buffer",mediaSourceId:this.id,value:{sourceBufferType:e,codec:t}});let r=new Ud(e,t,this.id,this._messageSender);return this.sourceBuffers.push(r),r}setDuration(e,t){this._messageSender({type:"update-media-source-duration",mediaSourceId:this.id,value:{duration:e,isRealEndKnown:t}})}interruptDurationSetting(){this._messageSender({type:"stop-media-source-duration",mediaSourceId:this.id,value:null})}maintainEndOfStream(){this._messageSender({type:"end-of-stream",mediaSourceId:this.id,value:null})}stopEndOfStream(){this._messageSender({type:"stop-end-of-stream",mediaSourceId:this.id,value:null})}dispose(){this.sourceBuffers.forEach(e=>e.dispose()),this._canceller.cancel(),this._messageSender({type:"dispose-media-source",mediaSourceId:this.id,value:null})}},Ud=class{constructor(e,t,r,i){this.type=e,this.codec=t,this._canceller=new D,this._mediaSourceId=r,this._queuedOperations=[],this._pendingOperations=new Map,this._messageSender=i}onOperationSuccess(e,t){let r=this._pendingOperations.get(e);r===void 0?p.warn("mse","unknown SourceBuffer operation succeeded"):(this._pendingOperations.delete(e),r.resolve(t)),this._performNextQueuedOperationIfItExists()}onOperationFailure(e,t){let r=t.errorName==="CancellationError"?new Ee:new He(t.errorName,t.message,t.isBufferFull),i=this._pendingOperations.get(e);i===void 0?p.info("mse","unknown SourceBuffer operation failed",r):(this._pendingOperations.delete(e),i.reject(r));let o=new Ee;for(let a of this._queuedOperations)a.reject(o);this._queuedOperations=[]}appendBuffer(e,t){return new Promise((r,i)=>{if(this._queuedOperations.length>0||this._pendingOperations.size>=pm){this._queuedOperations.push({operationName:0,params:[e,t],resolve:r,reject:i});return}try{let o;e instanceof ArrayBuffer?o=e:e.byteLength===e.buffer.byteLength?o=e.buffer:o=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);let a=wa();this._messageSender({type:"source-buffer-append",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:a,value:{data:o,params:t}},[o]),this._addOperationToQueue(a,r,i)}catch(o){i(o)}})}remove(e,t){return new Promise((r,i)=>{if(this._queuedOperations.length>0||this._pendingOperations.size>=pm){this._queuedOperations.push({operationName:1,params:[e,t],resolve:r,reject:i});return}try{let o=wa();this._messageSender({type:"source-buffer-remove",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:o,value:{start:e,end:t}}),this._addOperationToQueue(o,r,i)}catch(o){i(o)}})}abort(){this._messageSender({type:"abort-source-buffer",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,value:null})}dispose(){this.abort(),this._canceller.cancel()}getBuffered(){}_addOperationToQueue(e,t,r){this._pendingOperations.set(e,{resolve:o,reject:a});let i=this._canceller.signal.register(s=>{this._pendingOperations.delete(e),r(s)});function o(s){i(),t(s)}function a(s){i(),r(s)}}_performNextQueuedOperationIfItExists(){let e=this._queuedOperations.shift();if(e!==void 0)try{if(e.operationName===0){let[t,r]=e.params,i;t instanceof ArrayBuffer?i=t:t.byteLength===t.buffer.byteLength?i=t.buffer:i=t.buffer.slice(t.byteOffset,t.byteLength+t.byteOffset);let o=wa();this._messageSender({type:"source-buffer-append",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:o,value:{data:i,params:r}},[i]),this._addOperationToQueue(o,e.resolve,e.reject)}else{let[t,r]=e.params,i=wa();this._messageSender({type:"source-buffer-remove",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:i,value:{start:t,end:r}}),this._addOperationToQueue(i,e.resolve,e.reject)}}catch(t){e.reject(t)}}};function Fd(n){let e=n.map(a=>Math.log(a/n[0])),t=e.map(a=>a-e[0]+1),r=(t[t.length-1]-1)/(n.length*2+10),i=1/r;return n.map((a,s)=>o(s));function o(a){if(a===0)return 0;let s=Math.min(Math.max(1,a),n.length-1);return n[s]===n[s-1]?o(a-1):i*(r+(n[s]*t[s-1]-n[s-1]*t[s])/(n[s]-n[s-1]))+4}}var bt=class{constructor(e){this._alpha=Math.exp(Math.log(.5)/e),this._lastEstimate=0,this._totalWeight=0}addSample(e,t){let r=Math.pow(this._alpha,e),i=t*(1-r)+r*this._lastEstimate;isNaN(i)||(this._lastEstimate=i,this._totalWeight+=e)}getEstimate(){let e=1-Math.pow(this._alpha,this._totalWeight);return this._lastEstimate/e}};var ki=class{constructor(){this._currentRepresentationData=null,this._lastRepresentationWithGoodScore=null}addSample(e,t,r){let i=r/t,o=this._currentRepresentationData,a;o!==null&&o.representation.id===e.id?(a=o.ewma,o.ewma.addSample(t,i),o.loadedDuration+=r,o.loadedSegments++):(a=new bt(5),a.addSample(t,i),this._currentRepresentationData={representation:e,ewma:a,loadedDuration:r,loadedSegments:0}),a.getEstimate()>1&&this._lastRepresentationWithGoodScore!==e&&(p.debug("ABR","New last stable representation",{bitrate:e.bitrate}),this._lastRepresentationWithGoodScore=e)}getEstimate(e){if(this._currentRepresentationData===null||this._currentRepresentationData.representation.id!==e.id)return;let{ewma:t,loadedSegments:r,loadedDuration:i}=this._currentRepresentationData,o=t.getEstimate(),a=r>=5&&i>=10?1:0;return{score:o,confidenceLevel:a}}getLastStableRepresentation(){return this._lastRepresentationWithGoodScore}};var gm=6e3,gI=15e3,hI=3e3,II=1e3,yI=9e3,Ci=class{constructor(e){this._levelsMap=Fd(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=gm,p.debug("ABR","Steps for buffer based chooser.",this._levelsMap.map((t,r)=>`bufferLevel: ${t}, bitrate: ${e[r]}`).join(" ,"))}onAddedSegment(e){let t=this._levelsMap,r=this._bitrates,{bufferGap:i,currentBitrate:o,currentScore:a,speed:s}=e;if(_(o)){this._currentEstimate=r[0];return}let d=-1;for(let g=0;g<r.length;g++){let I=r[g];if(I===o)d=g;else if(I>o)break}if(d<0||r.length!==t.length){p.info("ABR","Current Bitrate not found in the calculated levels"),this._currentEstimate=r[0];return}let u;a!==void 0&&(u=s===0?a.score:a.score/s);let c=isFinite(i)?i:0,l=z();if(c<t[d]||u!==void 0&&u<1&&(a==null?void 0:a.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:l-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+yI){let h=this._blockRaiseDelay+hI;p.debug("ABR","Incrementing blocking raise in BufferBasedChooser due to unstable quality",{prevDelay:this._blockRaiseDelay,newDelay:h}),this._blockRaiseDelay=Math.min(h,gI)}else{let h=this._blockRaiseDelay-II;p.debug("ABR","Lowering quality in BufferBasedChooser",{prevDelay:this._blockRaiseDelay,newDelay:h}),this._blockRaiseDelay=Math.max(gm,h)}this._lastUnsuitableQualityTimestamp=l;let I=Te(r,h=>h===o);for(let h=I-1;h>=0;h--)if(c>=t[h]){this._currentEstimate=r[h];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&l-this._lastUnsuitableQualityTimestamp<this._blockRaiseDelay||u===void 0||u<1.15||(a==null?void 0:a.confidenceLevel)!==1){this._currentEstimate=o;return}let f=t[d],m=(()=>{for(let g=d+1;g<t.length;g++)if(t[g]>f)return g})();if(m!==void 0){let g=t[m];if(i>=g){p.debug("ABR","Raising quality in BufferBasedChooser",{bitrate:r[m]}),this._currentEstimate=r[m];return}}this._currentEstimate=o}getLastEstimate(){return this._currentEstimate}};function bI(n,e){let t=-1;for(let a=0;a<n.length;a++){let{segment:s}=n[a].content;if(s.duration<=0)continue;let d=s.time+s.duration;if(!s.complete&&a===n.length-1&&e-s.time>-1.2){t=a;break}if(d>e&&e-s.time>-1.2){t=a;break}}if(t<0)return[];let r=n[t],i=r.content.segment.time,o=[r];for(let a=t+1;a<n.length&&n[a].content.segment.time===i;a++)o.push(n[a]);return o}function Oa(n){if(n.progress.length<5)return;let e=new bt(2),{progress:t}=n;for(let r=1;r<t.length;r++){let i=t[r].size-t[r-1].size,o=t[r].timestamp-t[r-1].timestamp,a=i*8/(o/1e3);e.addSample(o/1e3,a)}return e.getEstimate()}function hm(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function SI(n,e,t,r,i){if(r)return;let{bufferGap:o,speed:a,position:s}=e,d=isFinite(o)?o:0,u=s.getWanted()+d,c=bI(n,u);if(c.length!==1)return;let l=c[0],f=z(),m=l.content.segment.duration*1.5;if(m=Math.min(m,3e3),m=Math.max(m,12e3),f-l.requestTimestamp<m)return;let g=l.progress.length>0?l.progress[l.progress.length-1]:void 0,I=Oa(l);if(g!==void 0&&I!==void 0){let R=hm(g,I);if((f-g.timestamp)/1e3<=R&&R-d/a>2500)return I}if(!l.content.segment.complete)return;let h=l.content.segment.duration,y=(f-l.requestTimestamp)/1e3,T=y<=(h*1.5+2)/a;if(_(t)||T)return;let v=h/y,E=t.bitrate*Math.min(.7,v);if(i===void 0||E<i)return E}function TI(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,o=q(e,({content:l})=>l.segment.duration>0&&l.segment.time+l.segment.duration>i);if(o===void 0)return!0;let a=z(),s=o.progress.length>0?o.progress[o.progress.length-1]:void 0,d=Oa(o);if(s===void 0||d===void 0)return!0;let u=hm(s,d);return(a-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var Pi=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:o,ABR_REGULAR_FACTOR:a}=O.getCurrent();this._initialBitrate=e,this._inStarvationMode=!1,this._lowLatencyMode=t,t?this._config={starvationGap:r.LOW_LATENCY,outOfStarvationGap:i.LOW_LATENCY,starvationBitrateFactor:o.LOW_LATENCY,regularBitrateFactor:a.LOW_LATENCY}:this._config={starvationGap:r.DEFAULT,outOfStarvationGap:i.DEFAULT,starvationBitrateFactor:o.DEFAULT,regularBitrateFactor:a.DEFAULT}}getBandwidthEstimate(e,t,r,i,o){let a,s,d=this._config,{bufferGap:u,position:c,duration:l}=e,f=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:m}=O.getCurrent();return isNaN(l)||f+c.getWanted()<l-m?!this._inStarvationMode&&f<=d.starvationGap?(p.info("ABR","enter starvation mode.",{buffergap:f,enterStarvation:d.starvationGap}),this._inStarvationMode=!0):this._inStarvationMode&&f>=d.outOfStarvationGap&&(p.info("ABR","exit starvation mode.",{bufferGap:f,outOfStarvation:d.starvationGap}),this._inStarvationMode=!1):this._inStarvationMode&&(p.info("ABR","exit starvation mode.",{bufferGap:f}),this._inStarvationMode=!1),this._inStarvationMode&&(s=SI(i,e,r,this._lowLatencyMode,o),s!==void 0&&(p.info("ABR","starvation mode emergency estimate:",{bandwidth:s}),t.reset(),a=_(r)?s:Math.min(s,r.bitrate))),_(a)&&(s=t.getEstimate(),s!==void 0?a=s*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):o!==void 0?a=o*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):a=this._initialBitrate),e.speed>1&&(a/=e.speed),{bandwidthEstimate:s,bitrateChosen:a}}isUrgent(e,t,r,i){return t===null?!0:e>=t.bitrate?!1:TI(i,r,this._lowLatencyMode)}};var Mi=class{constructor(){this.bandwidth=void 0,this.representation=null,this.algorithmType=3}update(e,t,r){this.representation=e,this.bandwidth=t,this.algorithmType=r}};var Ai=class{constructor(e,t){this._scoreCalculator=e,this._lastAbrEstimate=t,this._consecutiveWrongGuesses=0,this._blockGuessesUntil=0,this._lastMaintanableBitrate=null}getGuess(e,t,r,i,o){let{bufferGap:a,speed:s}=t,d=this._lastAbrEstimate.representation;if(d===null)return null;if(i>d.bitrate)return this._lastAbrEstimate.algorithmType===2&&(this._lastAbrEstimate.representation!==null&&(this._lastMaintanableBitrate=this._lastAbrEstimate.representation.bitrate),this._consecutiveWrongGuesses=0),null;let u=this._scoreCalculator.getEstimate(r);if(this._lastAbrEstimate.algorithmType!==2){if(u===void 0)return null;if(this._canGuessHigher(a,s,u)){let l=Im(e,r);if(l!==null)return l}return null}if(this._isLastGuessValidated(d,i,u)&&(p.debug("ABR","Guessed Representation validated",{chosenBitrate:d.bitrate,otherAbrAlgosBitrate:i,scoreData:u==null?void 0:u.score,scoreConfidence:u==null?void 0:u.confidenceLevel}),this._lastMaintanableBitrate=d.bitrate,this._consecutiveWrongGuesses=0),r.id!==d.id)return d;if(this._shouldStopGuess(r,u,a,o))return this._consecutiveWrongGuesses++,this._blockGuessesUntil=z()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),_I(e,r);if(u===void 0)return r;if(this._canGuessHigher(a,s,u)){let l=Im(e,r);if(l!==null)return l}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&z()>this._blockGuessesUntil&&i===1&&r/t>1.01}_shouldStopGuess(e,t,r,i){if(t!==void 0&&t.score<1.01)return!0;if((t===void 0||t.score<1.2)&&r<.6)return!0;let o=i.filter(s=>s.content.representation.id===e.id),a=z();for(let s of o){let d=a-s.requestTimestamp;if(s.content.segment.isInit){if(d>1e3)return!0}else{if(d>s.content.segment.duration*1e3+200)return!0;{let u=Oa(s);if(u!==void 0&&u<e.bitrate*.8)return!0}}}return!1}_isLastGuessValidated(e,t,r){return r!==void 0&&r.confidenceLevel===1&&r.score>1.5?!0:t>=e.bitrate&&(this._lastMaintanableBitrate===null||this._lastMaintanableBitrate<e.bitrate)}};function Im(n,e){let t=n.length,r=Te(n,({id:i})=>i===e.id);if(r<0)return p.error("ABR","Current Representation not found."),null;for(;++r<t;)if(n[r].bitrate>e.bitrate)return n[r];return null}function _I(n,e){let t=Te(n,({id:r})=>r===e.id);if(t<0)return p.error("ABR","Current Representation not found."),null;for(;--t>=0;)if(n[t].bitrate<e.bitrate)return n[t];return null}var xi=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=O.getCurrent();this._fastEWMA=new bt(e),this._slowEWMA=new bt(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=O.getCurrent();if(t<r)return;let i=t*8e3/e,o=e/1e3;this._bytesSampled+=t,this._fastEWMA.addSample(o,i),this._slowEWMA.addSample(o,i)}getEstimate(){let{ABR_MINIMUM_TOTAL_BYTES:e}=O.getCurrent();if(!(this._bytesSampled<e))return Math.min(this._fastEWMA.getEstimate(),this._slowEWMA.getEstimate())}reset(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=O.getCurrent();this._fastEWMA=new bt(e),this._slowEWMA=new bt(t),this._bytesSampled=0}};function Kd(n,e){if(n.length===0)return[];n.sort((o,a)=>o.bitrate-a.bitrate);let t=n[0].bitrate,r=Math.max(e,t),i=Te(n,o=>o.bitrate>r);return i===-1?n:n.slice(0,i)}function Vd(n,e){if(e.width===void 0||e.height===void 0)return n;let t=e.width*e.pixelRatio,r=e.height*e.pixelRatio,i=n.slice().sort((s,d)=>{var u,c;return((u=s.width)!=null?u:0)-((c=d.width)!=null?c:0)}),o=q(i,s=>typeof s.width=="number"&&s.width>=t&&typeof s.height=="number"&&s.height>=r);if(o===void 0)return n;let a=typeof o.width=="number"?o.width:0;return n.filter(s=>typeof s.width=="number"?s.width<=a:!0)}var wi=class{constructor(){this._currentRequests={}}add(e){let{id:t,requestTimestamp:r,content:i}=e;this._currentRequests[t]={requestTimestamp:r,progress:[],content:i}}addProgress(e){let t=this._currentRequests[e.id];if(_(t)){if(b.CURRENT_ENV===b.DEV)throw new Error("ABR: progress for a request not added");p.warn("ABR","progress for a request not added",{requestId:e.id});return}t.progress.push(e)}remove(e){if(_(this._currentRequests[e])){if(b.CURRENT_ENV===b.DEV)throw new Error("ABR: can't remove unknown request");p.warn("ABR","can't remove unknown request",{requestId:e})}delete this._currentRequests[e]}getRequests(){return er(this._currentRequests).filter(e=>!_(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function Da(n,e){let t=Te(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var ym=new W(void 0);ym.finish();var bm=new W(1/0);bm.finish();function zd(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,c,l){var h,y,T;let{type:f}=s.adaptation,m=o(f),g=(h=t[f])!=null?h:0,I={limitResolution:(y=r.limitResolution[f])!=null?y:ym,throttleBitrate:(T=r.throttleBitrate[f])!=null?T:bm};return EI({bandwidthEstimator:m,context:s,currentRepresentation:d,filters:I,initialBitrate:g,playbackObserver:c,representations:u,lowLatencyMode:i},l)};function o(a){let s=e[a];if(_(s)){p.debug("ABR","Creating new BandwidthEstimator",{bufferType:a});let d=new xi;return e[a]=d,d}return s}}function EI({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:o,playbackObserver:a,representations:s},d){let u=new ki,c=new Pi(i!=null?i:0,o),l=new wi,f=ae,m={metrics:T,requestBegin:v,requestProgress:E,requestEnd:R,addedSegment(k){f(k)}},g=new D;g.linkToSignal(d);let I=h(s.getValue(),g.signal);return s.onUpdate(y,{clearSignal:d}),{estimates:I,callbacks:m};function h(k,A){if(k.length<=1)return new W({bitrate:void 0,representation:k[0],urgent:!0,knownStableBitrate:void 0});let P=!1,M=k.sort((K,Y)=>K.bitrate-Y.bitrate),N=new Ci(M.map(K=>K.bitrate)),U=new Mi,L=new Ai(u,U),B=a.getReference().getValue(),C=new W(F());return a.listen(K=>{B=K,w()},{includeLastObservation:!1,clearSignal:A}),f=function(K){if(B===null)return;let{position:Y,speed:ie}=B,j=K.buffered,Q=ka(j,Y.getWanted()),{representation:ne}=K.content,X=u.getEstimate(ne),de=ne.bitrate,ue={bufferGap:Q,currentBitrate:de,currentScore:X,speed:ie};N.onAddedSegment(ue),w()},A.register(()=>{f=ae}),r.throttleBitrate.onUpdate(w,{clearSignal:A}),r.limitResolution.onUpdate(w,{clearSignal:A}),C;function w(){C.setValue(F())}function F(){let{bufferGap:K,position:Y,maximumPosition:ie}=B,j=r.limitResolution.getValue(),Q=r.throttleBitrate.getValue(),ne=t.getValue(),X=vI(M,j,Q),de=l.getRequests(),{bandwidthEstimate:ue,bitrateChosen:ve}=c.getBandwidthEstimate(B,n,ne,de,U.bandwidth),ce=u.getLastStableRepresentation(),ye=ce===null?void 0:ce.bitrate/(B.speed>0?B.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:ct,ABR_EXIT_BUFFER_BASED_ALGO:Et}=O.getCurrent();P&&K<=Et?P=!1:!P&&isFinite(K)&&K>=ct&&(P=!0);let $=Da(X,ve),Be=N.getLastEstimate(),rt=$.bitrate,it=null;P&&Be!==void 0&&Be>rt&&(it=Da(X,Be),rt=it.bitrate);let ot=null;return o&&ne!==null&&e.manifest.isDynamic&&ie-Y.getWanted()<40&&(ot=L.getGuess(M,B,ne,rt,de)),ot!==null&&ot.bitrate>rt?(p.debug("ABR","new guess-based estimate",{bitrate:ot.bitrate,representation:ot.id}),U.update(ot,ue,2),{bitrate:ue,representation:ot,urgent:ne===null||ot.bitrate<ne.bitrate,knownStableBitrate:ye}):it!==null?(p.debug("ABR","new buffer-based estimate",{bitrate:it.bitrate,representation:it.id}),U.update(it,ue,0),{bitrate:ue,representation:it,urgent:c.isUrgent(it.bitrate,ne,de,B),knownStableBitrate:ye}):(p.debug("ABR","new bandwidth estimate",{bitrate:$.bitrate,representation:$.id}),U.update($,ue,1),{bitrate:ue,representation:$,urgent:c.isUrgent($.bitrate,ne,de,B),knownStableBitrate:ye})}}function y(){let k=s.getValue();g.cancel(),g=new D,g.linkToSignal(d),h(k,g.signal).onUpdate(function(M){I.setValue(M)},{clearSignal:g.signal,emitCurrentValue:!0})}function T(k){let{requestDuration:A,segmentDuration:P,size:M,content:N}=k;if(n.addSample(A,M),!N.segment.isInit){let{segment:U,representation:L}=N;if(P===void 0&&!U.complete)return;let B=P!=null?P:U.duration;u.addSample(L,A/1e3,B)}}function v(k){l.add(k)}function E(k){l.addProgress(k)}function R(k){l.remove(k.id)}}function vI(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=Kd(r,t)),e!==void 0&&(r=Vd(r,e)),r}var Sm=zd;function La(){var t;if(typeof((t=Z.crypto)==null?void 0:t.randomUUID)=="function")return Z.crypto.randomUUID();let n=new Date().getTime(),e=z();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let i=Math.random()*16;return n>0?(i=(n+i)%16|0,n=Math.floor(n/16)):(i=(e+i)%16|0,e=Math.floor(e/16)),(r==="x"?i:i&3|8).toString(16)})}var RI=/^(?:[a-z]+:)?\/\//i,kI=/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function Li(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(RI.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?Li(n.substring(0,t)):e+1}function Tm(n,e){let t=Na(n),r=Na(e);if(t.scheme!==r.scheme||t.authority!==r.authority||t.path[0]!==void 0&&t.path[0]!=="/"&&r.path[0]==="/"||r.path[0]!==void 0&&r.path[0]!=="/"&&t.path[0]==="/")return null;let i=Di(t.path),o=Di(r.path),a;if(i===o)a="";else{let d=i.split("/");d.pop();let u=o.split("/");for(;d.length>0&&u.length>0&&d[0]===u[0];)d.shift(),u.shift();for(;d.length>0;)d.shift(),u.unshift("..");let c=u.join("/");(c.endsWith("../")||c.endsWith("./"))&&(c=c.slice(0,c.length-1)),a=c===""?".":c}let s=a;return a===""&&r.query===t.query||x(r.query)&&(s+="?",s+=r.query),x(r.fragment)&&(s+="#",s+=r.fragment),s}function CI(n,e){let t=Na(n),r=Na(e);if(x(r.scheme))return Wd(r);let i={scheme:t.scheme,authority:t.authority,path:"",query:r.query,fragment:r.fragment};return x(r.authority)?(i.authority=r.authority,i.path=Di(r.path),Wd(i)):(r.path===""?(i.path=t.path,x(r.query)||(i.query=t.query)):Le(r.path,"/")?i.path=Di(r.path):i.path=Di(MI(t,r.path)),Wd(i))}var Oi=new Map,PI=200;function Na(n){var r,i,o,a,s;if(Oi.has(n))return Oi.get(n);let e=n.match(kI),t;return e===null?t={scheme:"",authority:"",path:"",query:"",fragment:""}:t={scheme:(r=e[1])!=null?r:"",authority:(i=e[2])!=null?i:"",path:(o=e[3])!=null?o:"",query:(a=e[4])!=null?a:"",fragment:(s=e[5])!=null?s:""},Oi.size>=PI&&Oi.clear(),Oi.set(n,t),t}function Wd(n){let e="";return x(n.scheme)&&(e+=n.scheme+":"),x(n.authority)&&(e+="//"+n.authority),e+=n.path,x(n.query)&&(e+="?"+n.query),x(n.fragment)&&(e+="#"+n.fragment),e}function Di(n){let e=n.split(/(?=\/)/),t=[];for(let r=0;r<e.length;r++){let i=e[r];if(!(i===".."||i==="."||i==="")){if(i==="/.."){t.pop(),r===e.length-1&&t.push("/");continue}if(i==="/."){r===e.length-1&&t.push("/");continue}t.push(i)}}return t.join("")}function MI(n,e){if(x(n.authority)&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function Un(...n){var r,i,o;let e=n.filter(a=>a!==""),t=e.length;if(t===0)return"";if(t===1)return(r=e[0])!=null?r:"";{let a=(i=e[0])!=null?i:"",s=(o=e[1])!=null?o:"",d=CI(a,s),u=e.slice(2);return Un(d,...u)}}var AI=4,Ni=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:La(),this._contentId=(r=e.contentId)!=null?r:La(),this._typePreference=e.communicationType==="headers"?0:1,this._bufferStarvationToggle=!1,this._playbackObserver=null,this._lastThroughput={},this._canceller=null}startMonitoringPlayback(e){var t;(t=this._canceller)==null||t.cancel(),this._canceller=new D,this._playbackObserver=e,e.listen(r=>{r.rebuffering!==null&&(this._bufferStarvationToggle=!0)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}stopMonitoringPlayback(){var e;(e=this._canceller)==null||e.cancel(),this._canceller=null,this._playbackObserver=null}updateThroughput(e,t){this._lastThroughput[e]=t}_getCommonCmcdData(e){var i;let t={};t.bs=this._bufferStarvationToggle,this._bufferStarvationToggle=!1,t.cid=this._contentId,t.mtp=e!==void 0?Math.floor(Math.round(e/1e3/100)*100):void 0,t.sid=this._sessionId;let r=(i=this._playbackObserver)==null?void 0:i.getReference().getValue();return t.pr=r===void 0||r.speed===1?void 0:r.speed,r!==void 0&&(t.su=r.rebuffering!==null),t}getCmcdDataForManifest(e){var r;let t=this._getCommonCmcdData((r=this._lastThroughput.video)!=null?r:this._lastThroughput.audio);switch(t.ot="m",e){case"dash":t.sf="d";break;case"smooth":t.sf="s";break;default:t.sf="o";break}return this._producePayload(t)}getCmcdDataForSegmentRequest(e){var a,s,d,u;let t=(a=this._playbackObserver)==null?void 0:a.getReference().getValue(),r=this._getCommonCmcdData(this._lastThroughput[e.adaptation.type]);switch(r.br=Math.round(e.representation.bitrate/1e3),r.d=Math.round(e.segment.duration*1e3),e.adaptation.type){case"video":r.ot="v";break;case"audio":r.ot="a";break;case"text":r.ot="c";break}if(e.segment.isInit&&(r.ot="i"),!_(e.nextSegment)&&e.segment.url!==null&&e.nextSegment.url!==null&&(!e.nextSegment.isInit||e.nextSegment.indexRange===void 0)){let c=e.segment.url,l=e.nextSegment.url,f=Tm(c,l);f!==null&&(f!=="."&&(r.nor=encodeURIComponent(f)),e.nextSegment.range!==void 0&&(r.nrr=String(e.nextSegment.range[0])+"-",isFinite(e.nextSegment.range[1])&&(r.nrr+=String(e.nextSegment.range[1]))))}let i;if(t!==void 0&&(r.ot==="v"||r.ot==="a"||r.ot==="av")){let c=t.buffered[e.adaptation.type];if(!_(c)){let l=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let f of c)if(l>=f.start&&l<f.end){i=(f.end-l)*1e3,r.bl=Math.floor(Math.round(i/100)*100);break}}}let o=i===void 0||t===void 0?void 0:i/t.speed;if(r.dl=o===void 0?void 0:Math.floor(Math.round(o/100)*100),o!==void 0){let l=e.representation.bitrate*e.segment.duration/1e3/(o/1e3);r.rtp=Math.floor(Math.round(l*AI/100)*100)}switch(e.manifest.transport){case"dash":r.sf="d";break;case"smooth":r.sf="s";break;default:r.sf="o";break}return r.st=e.manifest.isDynamic?"l":"v",r.tb=e.adaptation.representations.reduce((c,l)=>l.isPlayable()!==!0?c:c===void 0?Math.round(l.bitrate/1e3):Math.max(c,Math.round(l.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,c)=>{this._typePreference===0?t[c]+=u:r+=u},o=(u,c)=>{let l=e[u];if(l!==void 0){let f=`${u}=${String(l)},`;i(f,c)}},a=(u,c)=>{if(e[u]===!0){let l=`${u},`;i(l,c)}},s=(u,c)=>{let l=e[u];if(l!==void 0){let m=`prop=${`"${l.replace("\\","\\\\").replace('"','\\"')}"`},`;i(m,c)}},d=(u,c)=>{let l=e[u];if(l!==void 0){let f=`prop=${l},`;i(f,c)}};return o("bl","request"),o("br","object"),a("bs","status"),s("cid","session"),o("d","object"),o("dl","request"),o("mtp","request"),s("nor","request"),s("nrr","request"),d("ot","object"),o("pr","session"),o("rtp","status"),d("sf","session"),s("sid","session"),d("st","session"),a("su","request"),o("tb","object"),this._typePreference===0?(t.object[t.object.length-1]===","&&(t.object=t.object.substring(0,t.object.length-1)),t.request[t.request.length-1]===","&&(t.request=t.request.substring(0,t.request.length-1)),t.session[t.session.length-1]===","&&(t.session=t.session.substring(0,t.session.length-1)),t.status[t.status.length-1]===","&&(t.status=t.status.substring(0,t.status.length-1)),p.debug("CMCD","proposing headers payload"),{type:"headers",value:{"CMCD-Object":t.object,"CMCD-Request":t.request,"CMCD-Session":t.session,"CMCD-Status":t.status}}):(r[r.length-1]===","&&(r=r.substring(0,r.length-1)),r=encodeURIComponent(r),p.debug("CMCD","proposing query string payload",{queryString:r}),{type:"query",value:[["CMCD",r]]})}};var _m=Ni;var Bi=class extends se{constructor(e){super(),this._downgradedCdnList={metadata:[],timeouts:[]},e.register(()=>{for(let t of this._downgradedCdnList.timeouts)clearTimeout(t);this._downgradedCdnList={metadata:[],timeouts:[]}})}getCdnPreferenceForResource(e){return e.length<=1?e:this._innerGetCdnPreferenceForResource(e)}downgradeCdn(e){let t=Em(this._downgradedCdnList.metadata,e);t>=0&&this._removeIndexFromDowngradeList(t);let{DEFAULT_CDN_DOWNGRADE_TIME:r}=O.getCurrent(),i=r;this._downgradedCdnList.metadata.push(e);let o=setTimeout(()=>{let a=Em(this._downgradedCdnList.metadata,e);a>=0&&this._removeIndexFromDowngradeList(a),this.trigger("priorityChange",null)},i);this._downgradedCdnList.timeouts.push(o),this.trigger("priorityChange",null)}_innerGetCdnPreferenceForResource(e){let[t,r]=e.reduce((i,o)=>(this._downgradedCdnList.metadata.some(a=>a.id===o.id&&a.baseUrl===o.baseUrl)?i[1].push(o):i[0].push(o),i),[[],[]]);return t.concat(r)}_removeIndexFromDowngradeList(e){this._downgradedCdnList.metadata.splice(e,1);let t=this._downgradedCdnList.timeouts.splice(e,1);clearTimeout(t[0])}};function Em(n,e){return n.length===0?-1:e.id!==void 0?Te(n,t=>t.id===e.id):Te(n,t=>t.baseUrl===e.baseUrl)}function St(n){return n instanceof Me?new at("PIPELINE_LOAD_ERROR",n):Ae(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function xI(n){return n instanceof Me?n.type===Rn.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412:n.type===Rn.TIMEOUT||n.type===Rn.ERROR_EVENT:n instanceof gt?typeof n.canRetry=="boolean"?n.canRetry:n.xhr!==void 0?n.xhr.status>=500||n.xhr.status===404||n.xhr.status===415||n.xhr.status===412:!1:on(n)&&n.code==="INTEGRITY_ERROR"}async function Ui(n,e,t,r,i){if(i.cancellationError!==null)return Promise.reject(i.cancellationError);let{baseDelay:o,maxDelay:a,maxRetry:s,onRetry:d}=r;n!==null&&n.length===0&&p.warn("utils","No CDN given to `scheduleRequestWithCdns`.");let u=new Map,c=l();if(c===void 0)throw new Error("No CDN to request");return f(c);function l(){if(n===null){let h=u.get(null);return h!==void 0&&h.isBlacklisted?void 0:null}else{if(e===null)return I(n);{let h=e.getCdnPreferenceForResource(n);return I(h)}}}async function f(h){try{return await t(h,i)}catch(y){if(D.isCancellationError(y))throw y;h!==null&&e!==null&&e.downgradeCdn(h);let T=u.get(h);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(h,T)):T.errorCounter++,!xI(y))return T.blockedUntil=void 0,T.isBlacklisted=!0,m(y);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let v=T.errorCounter,E=Math.min(o*Math.pow(2,v-1),a),R=si(E);T.blockedUntil=z()+R}return m(y)}}async function m(h){let y=l();if(i.isCancelled())throw i.cancellationError;if(y===void 0)throw h;if(d(h),i.isCancelled())throw i.cancellationError;return g(y,h)}function g(h,y){let T=u.get(h);if(T===void 0||T.blockedUntil===void 0)return f(h);let v=z(),E=T.blockedUntil-v;if(E<=0)return f(h);let R=new D,k=R.linkToSignal(i);return new Promise((A,P)=>{e==null||e.addEventListener("priorityChange",()=>{let U=l();if(i.isCancelled())throw i.cancellationError;if(U===void 0)return N(y);U!==h&&(R.cancel(),g(U,y).then(M,N))},R.signal),un(E,R.signal).then(()=>f(h).then(M,N),ae);function M(U){k(),A(U)}function N(U){k(),P(U)}})}function I(h){var T;if(u.size===0)return h[0];let y=z();return(T=h.filter(v=>{var E;return((E=u.get(v))==null?void 0:E.isBlacklisted)!==!0}).reduce((v,E)=>{var k;let R=(k=u.get(E))==null?void 0:k.blockedUntil;return R!==void 0&&R<=y&&(R=void 0),v===void 0?[E,R]:v[1]===void 0?v:R===void 0?[E,void 0]:R<v[1]?[E,R]:v},void 0))==null?void 0:T[0]}}function Hd(n,e,t){return Ui(null,null,n,e,t)}var Fi=class extends se{constructor(e,t,r){super(),this.scheduleManualRefresh=ae,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new D,this._isStarted=!1,this._isRefreshPending=!1,this._consecutiveUnsafeMode=0,this._prioritizedContentUrl=null}dispose(){this._canceller.cancel(),this.removeEventListener()}start(){if(this._isStarted)return;this._isStarted=!0;let e,t=this._settings.initialManifest;t instanceof pn?e=Promise.resolve({manifest:t}):t!==void 0?e=this.parse(t,{previousManifest:null,unsafeMode:!1},void 0):e=this._fetchManifest(void 0).then(r=>r.parse({previousManifest:null,unsafeMode:!1})),e.then(r=>{this.trigger("manifestReady",r.manifest),this._canceller.isUsed()||this._recursivelyRefreshManifest(r.manifest,r)}).catch(r=>this._onFatalError(r))}updateContentUrls(e,t){var r;this._prioritizedContentUrl=(r=e==null?void 0:e[0])!=null?r:void 0,t&&this.scheduleManualRefresh({enablePartialRefresh:!1,delay:0,canUseUnsafeMode:!1})}async _fetchManifest(e){var u;let t=this._canceller.signal,r=this._settings,i=this._transportName,o=this._pipelines,a=e!=null?e:(u=this._manifestUrls)==null?void 0:u[0],s=this._getBackoffSetting(c=>{this.trigger("warning",St(c))});try{let c=await d(a);return{parse:l=>this._parseLoadedManifest(c,l,a)}}catch(c){throw St(c)}function d(c){var h;let{loadManifest:l}=o,f=r.requestTimeout===void 0?O.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,m=r.connectionTimeout===void 0?O.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;f<0&&(f=void 0),m<0&&(m=void 0);let g={timeout:f,connectionTimeout:m,cmcdPayload:(h=r.cmcdDataBuilder)==null?void 0:h.getCmcdDataForManifest(i)};return Hd(()=>l(c,g,t),s,t)}}parse(e,t,r){return this._parseLoadedManifest({responseData:e,size:void 0,requestDuration:void 0},t,r)}async _parseLoadedManifest(e,t,r){var I;let i=z(),o=this._canceller.signal,a=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(h=>{this.trigger("warning",St(h))}),c=r!=null?r:(I=this._manifestUrls)==null?void 0:I[0],l={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:c};try{let h=this._pipelines.parseManifest(e,l,m,o,f);if(wI(h)){let{manifest:y}=await h;return g(y)}else return g(h.manifest)}catch(h){throw Ae(h,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function f(h){try{return await Hd(h,u,o)}catch(y){throw St(y)}}function m(h){for(let y of h){if(o.isCancelled())return;let T=Ae(y,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});a("warning",T)}}function g(h){let y=z()-i;return p.info("MF",`Manifest parsed in ${y}ms`),{manifest:h,sendingTime:s,receivedTime:d,parsingTime:y}}}_getBackoffSetting(e){let{DEFAULT_MAX_MANIFEST_REQUEST_RETRY:t,INITIAL_BACKOFF_DELAY_BASE:r,MAX_BACKOFF_DELAY_BASE:i}=O.getCurrent(),{lowLatencyMode:o,maxRetry:a}=this._settings,s=o?r.LOW_LATENCY:r.REGULAR,d=o?i.LOW_LATENCY:i.REGULAR,u=a!=null?a:t;return{onRetry:e,baseDelay:s,maxDelay:d,maxRetry:u}}_recursivelyRefreshManifest(e,{sendingTime:t,parsingTime:r,updatingTime:i}){let{MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:o,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:a}=O.getCurrent(),s=r!==void 0?r+(i!=null?i:0):void 0,d=!1;this._consecutiveUnsafeMode>0?d=this._consecutiveUnsafeMode<o:s!==void 0&&(d=s>=a);let u=t===void 0?0:z()-t,c=Math.max(this._settings.minimumManifestUpdateInterval-u,0),l=new D;if(l.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=f=>{let{enablePartialRefresh:m,delay:g,canUseUnsafeMode:I}=f,h=I&&d,y=t===void 0?0:z()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-y,0),v=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:m,unsafeMode:h})},Math.max((g!=null?g:0)-y,T));l.signal.register(()=>{clearTimeout(v)})},e.expired!==null){let f=setTimeout(()=>{var m;(m=e.expired)==null||m.then(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},ae)},c);l.signal.register(()=>{clearTimeout(f)})}if(e.lifetime!==void 0&&e.lifetime>=0){let f=e.lifetime*1e3-u,m;s===void 0?m=f:e.lifetime<3&&s>=100?(m=Math.min(Math.max(3e3-u,Math.max(f,0)+s),f*6),p.info("MF","Manifest update rythm is too frequent. Postponing next request.",{regularRefreshDelay:f,newRefreshDelay:m})):s>=e.lifetime*1e3/10?(m=Math.min(Math.max(f,0)+s,f*6),p.info("MF","Manifest took too long to parse. Postponing next request",{regularRefreshDelay:f,newRefreshDelay:m})):m=f;let g=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(m,c));l.signal.register(()=>{clearTimeout(g)})}}_triggerNextManifestRefresh(e,{enablePartialRefresh:t,unsafeMode:r}){let i=e.updateUrl,o,a;this._prioritizedContentUrl!==null?(o=!0,a=this._prioritizedContentUrl,this._prioritizedContentUrl=null):(o=!t||i===void 0,a=o?e.getUrls()[0]:i);let s=e.clockOffset;r?(this._consecutiveUnsafeMode+=1,p.info("MF",'Refreshing the Manifest in "unsafeMode" for the '+String(this._consecutiveUnsafeMode)+" consecutive time.")):this._consecutiveUnsafeMode>0&&(p.info("MF",'Not parsing the Manifest in "unsafeMode" anymore after '+String(this._consecutiveUnsafeMode)+" consecutive times."),this._consecutiveUnsafeMode=0),!this._isRefreshPending&&(this._isRefreshPending=!0,this._fetchManifest(a).then(d=>d.parse({externalClockOffset:s,previousManifest:e,unsafeMode:r})).then(d=>{this._isRefreshPending=!1;let{manifest:u,sendingTime:c,parsingTime:l}=d,f=z();if(o)e.replace(u);else try{e.update(u)}catch(g){let I=g instanceof Error?g.message:"unknown error";p.warn("MF",`Attempt to update Manifest failed: ${I}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:h}=O.getCurrent(),y=c===void 0?0:z()-c,T=Math.max(this._settings.minimumManifestUpdateInterval-y,0),v=ae,E=setTimeout(()=>{v(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(h-y,T));v=this._canceller.signal.register(()=>{clearTimeout(E)});return}let m=z()-f;this._recursivelyRefreshManifest(e,{sendingTime:c,parsingTime:l,updatingTime:m})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose())}};function wI(n){return n instanceof Promise}var qd=Fi;function Gd(n,e){let t=new WeakMap;return{createRequest(r,i,o,a){let s=u=>e(r,o,u),d=n.create(s,i,o,a);return t.set(d,s),d},updatePriority(r,i){let o=t.get(r);if(o===void 0){p.warn("SF","Cannot update the priority of a request: task not found.");return}n.updatePriority(o,i)}}}var jd=class{constructor(){this._cache=new WeakMap}add({representation:e,segment:t},r){t.isInit&&this._cache.set(e,r)}get({representation:e,segment:t}){if(t.isInit){let r=this._cache.get(e);if(r!==void 0)return r}return null}},vm=jd;var OI=Fe();function Yd({bufferType:n,pipeline:e,cdnPrioritizer:t,cmcdDataBuilder:r,eventListeners:i,requestOptions:o}){let a;o.connectionTimeout===void 0||o.connectionTimeout<0?a=void 0:a=o.connectionTimeout;let s={timeout:o.requestTimeout<0?void 0:o.requestTimeout,connectionTimeout:a,cmcdPayload:void 0},d=J(["audio","video"],n)?new vm:void 0,{loadSegment:u,parseSegment:c}=e;return async function(f,m,g){var Y,ie,j;let{segment:I,adaptation:h,representation:y,manifest:T,period:v}=f,E=kt(f),R=OI(),k,A=[],P=0,M=!1,N={segment:I,type:h.type,language:h.language,isLive:T.isLive,periodStart:v.start,periodEnd:v.end,mimeType:y.mimeType,codecs:y.codecs[0],manifestPublishTime:T.publishTime},U={onProgress(Q){var ne;k===void 0&&Q.totalSize!==void 0&&Q.size<Q.totalSize&&((ne=i.onProgress)==null||ne.call(i,{duration:Q.duration,size:Q.size,totalSize:Q.totalSize,timestamp:z(),id:R}))},onNewChunk(Q){m.onChunk(w(Q,!0))}},L=d!==void 0?d.get(f):null;if(L!==null)return p.debug("SF","Found wanted segment in cache",E),m.onChunk(w(L,!1)),Promise.resolve();p.debug("SF","Beginning request",E),(Y=i.onRequestBegin)==null||Y.call(i,{requestTimestamp:z(),id:R,content:f}),g.register(B);try{let Q=await Ui(f.representation.cdnMetadata,t,C,G({onRetry:F},o),g);if(Q.resultType==="segment-loaded"){let ne=Q.resultData.responseData;d!==void 0&&d.add(f,Q.resultData.responseData),m.onChunk(w(ne,!1))}else Q.resultType==="segment-created"&&m.onChunk(w(Q.resultData,!1));p.debug("SF","Segment request ended with success",E),m.onAllChunksReceived(),Q.resultType!=="segment-created"?(k=Q.resultData,K()):k=null,g.isCancelled()||(ie=i.onRequestEnd)==null||ie.call(i,{id:R}),g.deregister(B)}catch(Q){throw g.deregister(B),k=null,Q instanceof Ee?(p.debug("SF","Segment request aborted",E),Q):(p.debug("SF","Segment request failed",E),(j=i.onRequestEnd)==null||j.call(i,{id:R}),St(Q))}function B(){var Q;k===void 0&&(p.debug("SF","Segment request cancelled",E),k=null,(Q=i.onRequestEnd)==null||Q.call(i,{id:R}))}function C(Q){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(f),u(Q,N,s,g,U)}function w(Q,ne){A.push(!1);let X=A.length-1;return function(ue){let ve={data:Q,isChunked:ne};try{let ce=c(ve,N,ue);return A[X]||(P=P!==void 0&&ce.segmentType==="media"&&ce.chunkInfos!==null&&ce.chunkInfos.duration!==void 0?P+ce.chunkInfos.duration:void 0,A[X]=!0,K()),ce}catch(ce){throw Ae(ce,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function F(Q){m.onRetry(St(Q))}function K(){var Q;M||!_(k)&&k.size!==void 0&&k.requestDuration!==void 0&&A.length>0&&A.every(ne=>ne)&&(M=!0,(Q=i.onMetrics)==null||Q.call(i,{size:k.size,requestDuration:k.requestDuration,content:f,segmentDuration:P}))}}}function Rm({maxRetry:n,lowLatencyMode:e,requestTimeout:t,connectionTimeout:r}){let{DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:i,DEFAULT_REQUEST_TIMEOUT:o,DEFAULT_CONNECTION_TIMEOUT:a,INITIAL_BACKOFF_DELAY_BASE:s,MAX_BACKOFF_DELAY_BASE:d}=O.getCurrent();return{maxRetry:n!=null?n:i,baseDelay:e?s.LOW_LATENCY:s.REGULAR,maxDelay:e?d.LOW_LATENCY:d.REGULAR,requestTimeout:t===void 0?o:t,connectionTimeout:r===void 0?a:r}}var Ki=class extends se{constructor(e,t){super(),this._segmentFetcher=e,this._currentContentInfo=null,this.isMediaSegmentQueueInterrupted=t}getRequestedInitSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.initSegmentRequest)==null?void 0:t.segment)!=null?r:null}getRequestedMediaSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.mediaSegmentRequest)==null?void 0:t.segment)!=null?r:null}resetForContent(e,t){var a;(a=this._currentContentInfo)==null||a.currentCanceller.cancel();let r=new W({initSegment:null,segmentQueue:[]}),i=new D;i.signal.register(()=>{r.finish()});let o={content:e,downloadQueue:r,initSegmentInfoRef:t?new W(void 0):new W(null),currentCanceller:i,initSegmentRequest:null,mediaSegmentRequest:null,mediaSegmentAwaitingInitMetadata:null};return this._currentContentInfo=o,this.isMediaSegmentQueueInterrupted.onUpdate(s=>{s||(p.debug("SF","Media segment can be loaded again, restarting queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o))},{clearSignal:i.signal}),r.onUpdate(s=>{let{segmentQueue:d}=s;if(d.length>0&&d[0].segment.id===o.mediaSegmentAwaitingInitMetadata)return;let u=o.mediaSegmentRequest;if(d.length===0){if(u===null)return;p.debug("SF","no more media segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o);return}else if(u===null){p.debug("SF","Media segments now need to be requested. Starting queue.",{type:e.adaptation.type,queueLength:d.length}),this._restartMediaSegmentDownloadingQueue(o);return}else{let c=d[0];if(u.segment.id!==c.segment.id){p.debug("SF","Next media segment changed, cancelling previous",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o);return}u.priority!==c.priority&&(p.debug("SF","Priority of next media segment changed, updating",{type:e.adaptation.type,prevPriority:u.priority,newPriority:c.priority}),this._segmentFetcher.updatePriority(u.request,c.priority));return}},{emitCurrentValue:!0,clearSignal:i.signal}),r.onUpdate(s=>{var u;let d=o.initSegmentRequest;if(s.initSegment!==null&&d!==null){s.initSegment.priority!==d.priority&&this._segmentFetcher.updatePriority(d.request,s.initSegment.priority);return}else if(((u=s.initSegment)==null?void 0:u.segment.id)===(d==null?void 0:d.segment.id))return;s.initSegment===null&&p.debug("SF","no more init segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartInitSegmentDownloadingQueue(o,s.initSegment)},{emitCurrentValue:!0,clearSignal:i.signal}),r}stop(){var e;(e=this._currentContentInfo)==null||e.currentCanceller.cancel(),this._currentContentInfo=null}_restartMediaSegmentDownloadingQueue(e){e.mediaSegmentRequest!==null&&e.mediaSegmentRequest.canceller.cancel();let{downloadQueue:t,content:r,initSegmentInfoRef:i,currentCanceller:o}=e,a=()=>{var v;if(this.isMediaSegmentQueueInterrupted.getValue()){p.debug("SF","Segment fetching postponed because it cannot stream now.");return}let{segmentQueue:s}=t.getValue(),d=s[0];if(o!==null&&o.isUsed()){e.mediaSegmentRequest=null;return}if(d===void 0){e.mediaSegmentRequest=null,this.trigger("emptyQueue",null);return}let u=new D,c=o===null?ae:u.linkToSignal(o.signal),{segment:l,priority:f}=d,m=G({segment:l,nextSegment:(v=s[1])==null?void 0:v.segment},r),g=!1,I=!1;u.signal.register(()=>{e.mediaSegmentRequest=null,!g&&(e.mediaSegmentAwaitingInitMetadata===l.id&&(e.mediaSegmentAwaitingInitMetadata=null),g=!0,I=!1)});let h=E=>{ee(E.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",G({},E,{segment:l}))},y=()=>{let E=t.getValue().segmentQueue;if(E.length===0){g=!0,this.trigger("emptyQueue",null);return}else E[0].segment.id===l.id&&E.shift();g=!0,a()},T=this._segmentFetcher.createRequest(m,f,{onRetry:E=>{this.trigger("requestRetry",{segment:l,error:E})},beforeInterrupted(){p.info("SF","segment request interrupted temporarly.",{segmentId:l.id,segmentTime:l.time})},onChunk:E=>{let R=i.getValue();R!==void 0?h(E(R!=null?R:void 0)):(I=!0,i.waitUntilDefined(k=>{h(E(k!=null?k:void 0))},{clearSignal:u.signal}))},onAllChunksReceived:()=>{I?(e.mediaSegmentAwaitingInitMetadata=l.id,i.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,I=!1,this.trigger("fullyLoadedSegment",l)},{clearSignal:u.signal})):this.trigger("fullyLoadedSegment",l)},beforeEnded:()=>{c(),e.mediaSegmentRequest=null,I?i.waitUntilDefined(y,{clearSignal:u.signal}):y()}},u.signal);T.catch(E=>{c(),g||(g=!0,this.stop(),this.trigger("error",E))}),e.mediaSegmentRequest={segment:l,priority:f,request:T,canceller:u}};a()}_restartInitSegmentDownloadingQueue(e,t){let{content:r,initSegmentInfoRef:i}=e;if(e.initSegmentRequest!==null&&e.initSegmentRequest.canceller.cancel(),t===null)return;let o=new D,a=e.currentCanceller===null?ae:o.linkToSignal(e.currentCanceller.signal),{segment:s,priority:d}=t,u=G({segment:s,nextSegment:void 0},r),c=!1,l=this._segmentFetcher.createRequest(u,d,{onRetry:f=>{this.trigger("requestRetry",{segment:s,error:f})},beforeInterrupted:()=>{p.info("SF","init segment request interrupted temporarly.",{segmentId:s.id})},beforeEnded:()=>{a(),e.initSegmentRequest=null,c=!0},onChunk:f=>{var g;let m=f(void 0);ee(m.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",G({},m,{segment:s})),m.segmentType==="init"&&i.setValue((g=m.initTimescale)!=null?g:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",s)}},o.signal);l.catch(f=>{a(),c||(c=!0,this.stop(),this.trigger("error",f))}),o.signal.register(()=>{e.initSegmentRequest=null,!c&&(c=!0)}),e.initSegmentRequest={segment:s,priority:d,request:l,canceller:o}}};var zi=class{constructor({prioritySteps:e}){if(this._minPendingPriority=null,this._waitingQueue=[],this._pendingTasks=[],this._prioritySteps=e,this._prioritySteps.high>=this._prioritySteps.low)throw new Error("The max high level priority should be given a lowerpriority number than the min low priority.")}create(e,t,r,i){let o;return xn(i,(a,s)=>(o={hasEnded:!1,priority:t,trigger:()=>{if(o.hasEnded)return;let u=()=>{m(),this._endTask(o)},c=g=>{r.beforeEnded(),u(),a(g)},l=g=>{u(),s(g)},f=new D,m=f.linkToSignal(i);o.interrupter=f,f.signal.register(()=>{o.interrupter=null,i.isCancelled()||r.beforeInterrupted()}),this._minPendingPriority=this._minPendingPriority===null?o.priority:Math.min(this._minPendingPriority,o.priority),this._pendingTasks.push(o),o.taskFn(f.signal).then(c).catch(g=>{!i.isCancelled()&&f.isUsed()&&g instanceof Ee||l(g)})},taskFn:e,interrupter:null},this._canBeStartedNow(o)?(o.trigger(),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()):this._waitingQueue.push(o),()=>this._endTask(o)))}_endTask(e){e.hasEnded=!0;let t=Vi(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=Vi(e.taskFn,this._pendingTasks);if(r<0)return;this._pendingTasks.splice(r,1),this._pendingTasks.length>0?this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))):this._minPendingPriority=null,this._loopThroughWaitingQueue()}}updatePriority(e,t){let r=Vi(e,this._waitingQueue);if(r>=0){let s=this._waitingQueue[r];if(s.priority===t||(s.priority=t,!this._canBeStartedNow(s)))return;this._findAndRunWaitingQueueTask(r),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks();return}let i=Vi(e,this._pendingTasks);if(i<0){p.warn("SF","request to update the priority of a non-existent task");return}let o=this._pendingTasks[i];if(o.priority===t)return;let a=o.priority;o.priority=t,this._minPendingPriority===null||t<this._minPendingPriority?this._minPendingPriority=t:this._minPendingPriority===a&&(this._pendingTasks.length===1?this._minPendingPriority=t:this._minPendingPriority=Math.min(...this._pendingTasks.map(s=>s.priority)),this._loopThroughWaitingQueue()),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()}_loopThroughWaitingQueue(){let e=this._waitingQueue.reduce((t,r)=>t===null||t>r.priority?r.priority:t,null);if(!(e===null||this._minPendingPriority!==null&&this._minPendingPriority<e))for(let t=0;t<this._waitingQueue.length;t++){let r=this._minPendingPriority===null?e:Math.min(this._minPendingPriority,e);this._waitingQueue[t].priority<=r&&(this._findAndRunWaitingQueueTask(t),t--)}}_interruptCancellableTasks(){for(let e of this._pendingTasks)if(e.priority>=this._prioritySteps.low)return this._interruptPendingTask(e),this._interruptCancellableTasks()}_findAndRunWaitingQueueTask(e){return e>=this._waitingQueue.length||e<0?(p.warn("SF","Tried to start a non existing task"),!1):(this._waitingQueue.splice(e,1)[0].trigger(),!0)}_interruptPendingTask(e){var r;let t=Vi(e.taskFn,this._pendingTasks);if(t<0){p.warn("SF","Interrupting a non-existent pending task. Aborting...");return}this._pendingTasks.splice(t,1),this._waitingQueue.push(e),this._pendingTasks.length===0?this._minPendingPriority=null:this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))),(r=e.interrupter)==null||r.cancel()}_canBeStartedNow(e){return this._minPendingPriority===null||e.priority<=this._minPendingPriority}_isRunningHighPriorityTasks(){return this._minPendingPriority!==null&&this._minPendingPriority<=this._prioritySteps.high}};function Vi(n,e){return Te(e,t=>t.taskFn===n)}var Wi=class{constructor(e,t,r,i){let{MIN_CANCELABLE_PRIORITY:o,MAX_HIGH_PRIORITY_LEVEL:a}=O.getCurrent();this._transport=e,this._prioritizer=new zi({prioritySteps:{high:a,low:o}}),this._cdnPrioritizer=t,this._backoffOptions=i,this._cmcdDataBuilder=r}createSegmentQueue(e,t,r){let i=Rm(this._backoffOptions),o=this._transport[e],a=Yd({bufferType:e,pipeline:o,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=Gd(this._prioritizer,a);return new Ki(s,r)}};var Qd=Wi;function $d(n,e){let{loadThumbnail:t}=n,r=[];return async function(o,a){a.register(T);let s,d=q(r,({thumbnailContext:R})=>R.period.id===o.period.id&&R.track.id===o.track.id&&R.segment.id===o.segment.id);if(d!==void 0){p.debug("Thumbnails","Requesting same thumbnail than the pending one",{time:o.segment.time}),s=d,s.referenceCount++;let R;try{R=await s.promise}catch(k){throw a.deregister(T),k}return a.deregister(T),R}let{segment:u,track:c}=o,l=DI({}),f;l.connectionTimeout===void 0||l.connectionTimeout<0?f=void 0:f=l.connectionTimeout;let m={timeout:l.requestTimeout<0?void 0:l.requestTimeout,connectionTimeout:f,cmcdPayload:void 0},g=new D,I=y();s={thumbnailContext:o,promise:I,referenceCount:1},r.push(s);let h=()=>{let R=r.indexOf(s);R>=0&&r.splice(R,1)};try{let R=await I;return h(),R}catch(R){throw h(),R}async function y(){p.debug("Thumbnails","Beginning thumbnail request",{time:u.time});let R;try{if(R=await Ui(c.cdnMetadata,e,v,G({onRetry:E},l),g.signal),a.isCancelled())return Promise.reject(a.cancellationError);p.debug("Thumbnails","Thumbnail request ended with success",{time:u.time}),a.deregister(T)}catch(k){throw a.deregister(T),k instanceof Ee?(p.debug("Thumbnails","Thumbnail request aborted",{time:u.time}),k):(p.debug("Thumbnails","Thumbnail request failed",{time:u.time}),St(k))}try{return n.parseThumbnail(R.responseData,{thumbnail:u,thumbnailTrack:c})}catch(k){throw Ae(k,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}function T(){p.debug("Thumbnails","Thumbnail request cancelled",{time:u.time});let R=r.indexOf(s);R<0||(r[R].referenceCount--,r[R].referenceCount<=0&&(g.cancel(),r.splice(R,1)))}function v(R){return t(R,u,m,a)}function E(R){let k=St(R);p.warn("Thumbnails","Thumbnail request retry ",{time:u.time},k)}}}function DI({maxRetry:n,requestTimeout:e,connectionTimeout:t}){let{DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:r,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:i,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:o,INITIAL_BACKOFF_DELAY_BASE:a,MAX_BACKOFF_DELAY_BASE:s}=O.getCurrent();return{maxRetry:n!=null?n:r,baseDelay:a.REGULAR,maxDelay:s.REGULAR,requestTimeout:e===void 0?i:e,connectionTimeout:t===void 0?o:t}}var Hi=class{constructor(e,t){this._contentId=e,this._messageSender=t,this._queues={pushTextData:[],remove:[]}}pushTextData(e){return new Promise((t,r)=>{this._messageSender({type:"push-text-data",contentId:this._contentId,value:e}),this._queues.pushTextData.push({resolve:t,reject:r})})}remove(e,t){return new Promise((r,i)=>{this._messageSender({type:"remove-text-data",contentId:this._contentId,value:{start:e,end:t}}),this._queues.remove.push({resolve:r,reject:i})})}reset(){this._messageSender({type:"reset-text-displayer",contentId:this._contentId,value:null}),this._resetCurrentQueue()}stop(){this._messageSender({type:"stop-text-displayer",contentId:this._contentId,value:null}),this._resetCurrentQueue()}_resetCurrentQueue(){let e=new Ee;this._queues.pushTextData.forEach(t=>{t.reject(e)}),this._queues.remove.forEach(t=>{t.reject(e)})}onPushedTrackSuccess(e){let t=this._queues.pushTextData.shift();if(t===void 0){p.error("text","pushTextData success for inexistant operation");return}t.resolve(e)}onPushedTrackError(e){let t=this._queues.pushTextData.shift();if(t===void 0){p.error("text","pushTextData error for inexistant operation");return}t.reject(e)}onRemoveSuccess(e){let t=this._queues.remove.shift();if(t===void 0){p.error("text","remove success for inexistant operation");return}t.resolve(e)}onRemoveError(e){let t=this._queues.pushTextData.shift();if(t===void 0){p.error("text","pushTextData error for inexistant operation");return}t.reject(e)}};var km=6,Xd=4e3,Ba=6e3,LI=6e4,pr=class{constructor(e){this._segmentSinksStore=e,this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=null,this._lastFlushAttempt=null,this._lastSegmentInfo={audio:[],video:[]}}onNewObservation(e){var h,y;let t=z();if(this._addPositionToHistory(e,t),this._ignoreFreezeUntil!==null&&t<this._ignoreFreezeUntil)return null;this._ignoreFreezeUntil=null;let{UNFREEZING_SEEK_DELAY:r,UNFREEZING_DELTA_POSITION:i,FREEZING_FLUSH_FAILURE_DELAY:o}=O.getCurrent(),{readyState:a,rebuffering:s,freezing:d,fullyLoaded:u}=e,c=e.position.getPolled(),l=Cm(e.bufferGap);if(!(d!==null||a===1&&(l>=km||u)))return this._decipherabilityFreezeStartingTimestamp=null,null;let m=(y=(h=d==null?void 0:d.timestamp)!=null?h:s==null?void 0:s.timestamp)!=null?y:null;if(p.info("Freeze","Freeze detected",{freezeStart:m,timeFrozen:t-(m!=null?m:t)}),this._lastFlushAttempt!==null&&t-this._lastFlushAttempt.timestamp<o.MAXIMUM&&t-this._lastFlushAttempt.timestamp>=o.MINIMUM&&Math.abs(c-this._lastFlushAttempt.position)<o.POSITION_DELTA){let T=this._getStrategyIfFlushingFails(c);return this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+Ba,T}let I=this._checkForDecipherabilityRelatedFreeze(e,t);return I!==null?I:m!==null&&t-m>r?(this._lastFlushAttempt={timestamp:t,position:c+i},p.debug("Freeze","Trying to flush to un-freeze"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+Ba,{type:"flush",value:{relativeSeek:i}}):null}_checkForDecipherabilityRelatedFreeze(e,t){let{readyState:r,rebuffering:i,freezing:o,fullyLoaded:a}=e,s=Cm(e.bufferGap),d=i!==null&&t-i.timestamp>Xd,{hasUndecipherableData:u,hasEncryptedData:c}=NI(this._segmentSinksStore);if(u===!0)return p.warn("Freeze","we have undecipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+Ba,{type:"reload",value:null};let l=o!==null&&t-o.timestamp>Xd;return(d||l)&&(s>=km||a)&&r<=1?this._decipherabilityFreezeStartingTimestamp===null&&(p.debug("Freeze","Start of a potential decipherability freeze detected"),this._decipherabilityFreezeStartingTimestamp=t):this._decipherabilityFreezeStartingTimestamp=null,this._decipherabilityFreezeStartingTimestamp!==null&&z()-this._decipherabilityFreezeStartingTimestamp>Xd&&c&&u===!1?(p.warn("Freeze","we are frozen despite only having decipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+Ba,{type:"reload",value:null}):null}_getStrategyIfFlushingFails(e){p.warn("Freeze","A recent flush seemed to have no effect on freeze, checking for transitions");let t=[];for(let r of["audio","video"]){let i=this._lastSegmentInfo[r];if(i.length===0)continue;let o=i[i.length-1];if(o.segment===null)continue;let a=o.segment,s;for(let d=i.length-2;d>=0;d--){let u=i[d];if(u.segment===null){s=u;break}else if(u.segment.infos.representation.uniqueId!==a.infos.representation.uniqueId&&o.timestamp-u.timestamp<5e3){s=u;break}else u.segment.start===a.start&&e-u.position<3e3&&(o=u)}if(s===void 0||s.segment===null)p.debug("Freeze","Freeze when beginning to play a content, try avoiding this quality"),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation});else{if(a.infos.period.id!==s.segment.infos.period.id)return p.debug("Freeze","Freeze when switching Period, reloading"),{type:"reload",value:null};a.infos.representation.uniqueId!==s.segment.infos.representation.uniqueId&&(p.warn("Freeze","Freeze when switching Representation, avoiding",{bitrate:a.infos.representation.bitrate}),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation}))}}return t.length>0?{type:"avoid-representations",value:t}:(p.debug("Freeze","Reloading because flush doesn't work"),{type:"reload",value:null})}_addPositionToHistory(e,t){var i,o;let r=e.position.getPolled();for(let a of["audio","video"]){let s=this._segmentSinksStore.getStatus(a);if(s.type==="initialized")for(let c of s.value.getLastKnownInventory())((i=c.bufferedStart)!=null?i:c.start)<=r&&((o=c.bufferedEnd)!=null?o:c.end)>r&&this._lastSegmentInfo[a].push({segment:c,position:r,timestamp:t});else this._lastSegmentInfo[a].push({segment:null,position:r,timestamp:t});if(this._lastSegmentInfo[a].length>100){let c=this._lastSegmentInfo[a].length-100;this._lastSegmentInfo[a].splice(0,c)}let d=t-LI,u;for(u=0;u<this._lastSegmentInfo[a].length&&!(this._lastSegmentInfo[a][u].timestamp>d);u++);u>0&&this._lastSegmentInfo[a].splice(0,u)}}};function NI(n){let e=!0,t=!0;for(let r of["audio","video"]){let i=n.getStatus(r);if(i.type==="initialized")for(let o of i.value.getLastKnownInventory()){let{representation:a}=o.infos;if(a.decipherable===!1)return{hasUndecipherableData:!0,hasEncryptedData:!0};a.contentProtections!==void 0&&(t=!1,a.decipherable!==!0&&(e=!1))}}return{hasEncryptedData:!t,hasUndecipherableData:e?!1:void 0}}function Cm(n){return n!==void 0&&isFinite(n)?n:0}var qi=class{constructor(){this._refs=new Map}reset(){var e,t,r,i,o,a,s,d,u,c,l,f;for(let m of this._refs.keys())(t=(e=this._refs.get(m))==null?void 0:e.audio)==null||t.trackReference.finish(),(i=(r=this._refs.get(m))==null?void 0:r.audio)==null||i.representations.finish(),(a=(o=this._refs.get(m))==null?void 0:o.video)==null||a.trackReference.finish(),(d=(s=this._refs.get(m))==null?void 0:s.video)==null||d.representations.finish(),(c=(u=this._refs.get(m))==null?void 0:u.text)==null||c.trackReference.finish(),(f=(l=this._refs.get(m))==null?void 0:l.text)==null||f.representations.finish();this._refs=new Map}addTrackSetter(e,t,r){var s,d;let i=this._refs.get(e);i===void 0&&(i={},this._refs.set(e,i)),i[t]!==void 0&&(p.warn("Track","Track for periodId already declared",{periodId:e,bufferType:t}),(s=i[t])==null||s.trackReference.finish(),(d=i[t])==null||d.representations.finish());let o=r.getValue(),a;_(o)?a=new W({representationIds:[],switchingMode:"lazy"}):(a=new W(o.representations.getValue()),r.setValue(G({},o,{representations:a}))),i[t]={trackReference:r,representations:a}}setTrack(e,t,r){var o;let i=(o=this._refs.get(e))==null?void 0:o[t];return i===void 0?(p.debug("Track","Setting track for inexistent periodId",{periodId:e,bufferType:t}),!1):(_(r)?(i.representations=new W({representationIds:[],switchingMode:"lazy"}),i.trackReference.setValue(r)):(i.representations=new W(r.initialRepresentations),i.trackReference.setValue({adaptationId:r.adaptationId,switchingMode:r.switchingMode,representations:i.representations,relativeResumingPosition:r.relativeResumingPosition})),!0)}updateRepresentations(e,t,r,i){var s;let o=(s=this._refs.get(e))==null?void 0:s[r];if(o===void 0)return p.debug("Track","Setting track for inexistent periodId",{periodId:e,bufferType:r}),!1;let a=o.trackReference.getValue();return _(a)||a.adaptationId!==t?(p.debug("Track","Desynchronized Adaptation id",{oldId:a==null?void 0:a.adaptationId,newId:t}),!1):(o.representations.setValue(i),!0)}removeTrackSetter(e,t){let r=this._refs.get(e),i=r==null?void 0:r[t];return r===void 0||i===void 0?(p.debug("Track","Removing track setter for inexistent periodId",{periodId:e,bufferType:t}),!1):(i.trackReference.finish(),i.representations.finish(),delete r[t],Object.keys(r).length===0&&this._refs.delete(e),!0)}};function Je(n){return Ae(n,{defaultCode:"NONE",defaultReason:"An unknown error stopped content playback."}).serialize()}var Pm=Fe(),gr=class{constructor({hasVideo:e}){this._currentContent=null,this._currentMediaSourceCanceller=new D,this._hasVideo=e;let t=new D;this._contentCanceller=t}initializeNewContent(e,t,r){return new Promise((i,o)=>{var F,K;this.disposeCurrentContent();let a=this._contentCanceller,s=new D;this._currentMediaSourceCanceller=s,s.linkToSignal(a.signal);let{contentId:d,url:u,hasText:c,transportOptions:l,useMseInWorker:f,enableRepresentationAvoidance:m,transport:g}=t,I=null,h=pe.transports[g];if(typeof h!="function"){o(new Error(`transport "${g}" not supported. Did you add the corresponding feature?`));return}let y=typeof l.representationFilter=="string"?Kc(l.representationFilter):l.representationFilter,T=h(me(oe({},l),{representationFilter:y})),v=t.cmcd===void 0?null:new _m(t.cmcd),E=new qd(u===void 0?void 0:[u],T,oe({cmcdDataBuilder:v},t.manifestRetryOptions)),R=Sm({initialBitrates:{audio:(F=t.initialAudioBitrate)!=null?F:0,video:(K=t.initialVideoBitrate)!=null?K:0},lowLatencyMode:l.lowLatencyMode,throttlers:r}),k=s.signal.register(Y=>{o(Y)}),A=new Bi(a.signal),P=new Qd(T,A,v,t.segmentRetryOptions),M=$d(T.thumbnails,A),N=new qi,[U,L,B]=Mm(e,d,{useMseInWorker:f,hasVideo:this._hasVideo,hasText:c},s.signal),C=new pr(L);this._currentContent={cmcdDataBuilder:v,contentId:d,enableRepresentationAvoidance:m,freezeResolver:C,mediaSource:U,manifest:null,manifestFetcher:E,representationEstimator:R,segmentSinksStore:L,segmentQueueCreator:P,fetchThumbnailData:M,coreTextSender:B,trackChoiceSetter:N,useMseInWorker:f},U.addEventListener("mediaSourceOpen",function(){w()},s.signal),a.signal.register(()=>{E.dispose()}),E.addEventListener("warning",Y=>{e({type:"warning",contentId:d,value:Je(Y)})},a.signal),E.addEventListener("manifestReady",Y=>{if(I!==null){p.warn("Core","Multiple `manifestReady` events, ignoring");return}I=Y,this._currentContent!==null&&(this._currentContent.manifest=I),w()},s.signal),E.addEventListener("error",Y=>{e({type:"error",contentId:d,value:Je(Y)}),o(Y)},a.signal),E.start();function w(){I===null||U.readyState==="closed"||s.isUsed()||(BI(I),I.addEventListener("manifestUpdate",Y=>{I!==null&&e({type:"manifest-update",contentId:d,value:{manifest:I,updates:Y}})},a.signal),k(),i(I))}})}getCurrentContent(){return this._currentContent}scheduleManifestRefresh(e){var t;(t=this._currentContent)==null||t.manifestFetcher.scheduleManualRefresh(e)}reloadMediaSource(e){if(this._currentMediaSourceCanceller.cancel(),this._currentContent===null)return Promise.reject(new Error("CP: No content anymore"));this._currentContent.trackChoiceSetter.reset(),this._currentMediaSourceCanceller=new D;let[t,r,i]=Mm(e,this._currentContent.contentId,{useMseInWorker:this._currentContent.useMseInWorker,hasVideo:this._hasVideo,hasText:this._currentContent.coreTextSender!==null},this._currentMediaSourceCanceller.signal);return this._currentContent.mediaSource=t,this._currentContent.segmentSinksStore=r,this._currentContent.freezeResolver=new pr(r),this._currentContent.coreTextSender=i,new Promise((o,a)=>{t.addEventListener("mediaSourceOpen",function(){o()},this._currentMediaSourceCanceller.signal),t.addEventListener("mediaSourceClose",function(){a(new Error("MediaSource ReadyState changed to close during init."))},this._currentMediaSourceCanceller.signal),this._currentMediaSourceCanceller.signal.register(s=>{a(s)})})}disposeCurrentContent(){this._contentCanceller.cancel(),this._contentCanceller=new D}};function Mm(n,e,t,r){let i;if(t.useMseInWorker){let d=new Bn(Pm());i=d;let u,c=d.handle;if(c.type==="handle")u={type:"handle",value:c.value};else{let l=URL.createObjectURL(c.value);u={type:"url",value:l},r.register(()=>{URL.revokeObjectURL(l)})}n({type:"attach-media-source",contentId:e,value:u,mediaSourceId:i.id},[c.value])}else i=new Ri(Pm(),e,n);let o=t.hasText?new Hi(e,n):null,{hasVideo:a}=t,s=new gn(i,a,o);return r.register(()=>{s.disposeAll(),o==null||o.stop(),i.dispose()}),[i,s,o]}function BI(n){var t,r;if(_(ht))return;let e=new Map;for(let i of n.periods){let o=[...(t=i.adaptations.video)!=null?t:[],...(r=i.adaptations.audio)!=null?r:[]];for(let a of o)for(let s of a.representations){let d=`${s.mimeType};codecs="${s.codecs[0]}"`;if(e.has(d))s.isCodecSupportedInWebWorker=e.get(d);else{let u=ht.isTypeSupported(d);s.isCodecSupportedInWebWorker=u,e.set(d,u)}}}}var Gi=class extends se{constructor(e,t,r){super(),this._canceller=new D,this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new Zd(e);this._maximumPositionCalculator=i;let o=this._canceller.signal;Rt(()=>{t.listen(({position:a})=>{let s=a.getWanted();if(s<e.getMinimumSafePosition()){let d=new re("MEDIA_TIME_BEFORE_MANIFEST","The current position is behind the earliest time announced in the Manifest.");this.trigger("warning",d)}else if(s>i.getMaximumAvailablePosition()){let d=new re("MEDIA_TIME_AFTER_MANIFEST","The current position is after the latest time announced in the Manifest.");this.trigger("warning",d)}},{includeLastObservation:!1,clearSignal:o})}),e.addEventListener("manifestUpdate",()=>{this.trigger("endingPositionChange",this._getManifestEndTime()),!o.isCancelled()&&this._checkEndOfStream()},o)}getCurrentEndingTime(){return this._getManifestEndTime()}onAdaptationChange(e,t,r){if(this._manifest.isLastPeriodKnown){let i=this._manifest.periods[this._manifest.periods.length-1];if(t.id===(i==null?void 0:i.id)&&(e==="audio"||e==="video")){e==="audio"?this._maximumPositionCalculator.updateLastAudioAdaptation(r):this._maximumPositionCalculator.updateLastVideoAdaptation(r);let o=this._maximumPositionCalculator.getEndingPosition(),a=o!==void 0?{isEnd:!0,endingPosition:o}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()};this.trigger("endingPositionChange",a)}}this._canceller.isUsed()||r===null&&this._addActivelyLoadedPeriod(t,e)}onRepresentationChange(e,t){this._addActivelyLoadedPeriod(t,e)}onPeriodCleared(e,t){this._removeActivelyLoadedPeriod(t,e)}onLastSegmentFinishedLoading(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod||(t.hasFinishedLoadingLastPeriod=!0,this._checkEndOfStream())}onLastSegmentLoadingResume(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod&&(t.hasFinishedLoadingLastPeriod=!1,this._checkEndOfStream())}dispose(){this.removeEventListener(),this._canceller.cancel()}_addActivelyLoadedPeriod(e,t){let r=this._lazilyCreateActiveStreamInfo(t);r.activePeriods.has(e)||(r.activePeriods.add(e),this._checkCurrentPeriod())}_removeActivelyLoadedPeriod(e,t){let r=this._activeStreams.get(t);r!==void 0&&r.activePeriods.has(e)&&(r.activePeriods.removeElement(e),this._checkCurrentPeriod())}_checkCurrentPeriod(){if(this._allBufferTypes.length===0)return;let e=this._activeStreams.get(this._allBufferTypes[0]);if(e!==void 0)for(let t of e.activePeriods.toArray()){let r=!0;for(let i of this._allBufferTypes){let o=this._activeStreams.get(i);if(o===void 0)return;if(!o.activePeriods.toArray().some(d=>d.id===t.id)){r=!1;break}}if(r){this._lastCurrentPeriodId!==t.id&&(this._lastCurrentPeriodId=t.id,this.trigger("periodChange",t));return}}}_getManifestEndTime(){let e=this._maximumPositionCalculator.getEndingPosition();return e!==void 0?{isEnd:!0,endingPosition:e}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()}}_lazilyCreateActiveStreamInfo(e){let t=this._activeStreams.get(e);return t===void 0&&(t={activePeriods:new Nn((r,i)=>r.start-i.start),hasFinishedLoadingLastPeriod:!1},this._activeStreams.set(e,t)),t}_checkEndOfStream(){if(!this._manifest.isLastPeriodKnown)return;this._allBufferTypes.every(t=>{let r=this._activeStreams.get(t);return r!==void 0&&r.hasFinishedLoadingLastPeriod})?this.trigger("endOfStream",null):this.trigger("resumeStream",null)}},Zd=class{constructor(e){this._manifest=e,this._lastAudioAdaptation=void 0,this._lastVideoAdaptation=void 0}updateLastAudioAdaptation(e){this._lastAudioAdaptation=e}updateLastVideoAdaptation(e){this._lastVideoAdaptation=e}getMaximumAvailablePosition(){if(this._manifest.isDynamic)return this._manifest.getMaximumSafePosition();if(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)return this._manifest.getMaximumSafePosition();if(this._lastAudioAdaptation===null){if(this._lastVideoAdaptation===null)return this._manifest.getMaximumSafePosition();{let e=Ua(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=Ua(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=Ua(this._lastAudioAdaptation),t=Ua(this._lastVideoAdaptation);return typeof e!="number"||typeof t!="number"?this._manifest.getMaximumSafePosition():Math.min(e,t)}}getEndingPosition(){var e,t;if(!this._manifest.isDynamic)return this.getMaximumAvailablePosition();if(!(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)){if(this._lastAudioAdaptation===null)return this._lastVideoAdaptation===null?void 0:(e=Fa(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=Fa(this._lastAudioAdaptation))!=null?t:void 0;{let r=Fa(this._lastAudioAdaptation),i=Fa(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function Ua(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getLastAvailablePosition();if(o===void 0)return;o!==null&&(t=_(t)?o:Math.min(t,o))}return t}function Fa(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getEnd();if(o===void 0)return;o!==null&&(t=_(t)?o:Math.min(t,o))}return t}function Jd(n,e,t,r,i,o){o.register(()=>{e.interruptDurationSetting()});let a=new Gi(n,t,r.getBufferTypes());o.register(()=>{a.dispose()}),a.addEventListener("warning",d=>i.onWarning(d)),a.addEventListener("periodChange",d=>i.onPeriodChanged(d)),a.addEventListener("endingPositionChange",d=>{e.setDuration(d.endingPosition,d.isEnd)}),a.addEventListener("endOfStream",()=>{p.debug("mse","Start applying end-of-stream order."),e.maintainEndOfStream()}),a.addEventListener("resumeStream",()=>{e.stopEndOfStream()});let s=a.getCurrentEndingTime();return e.setDuration(s.endingPosition,s.isEnd),a}function ji(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=q(n.sourceBuffers,s=>s.type==="audio"),i=q(n.sourceBuffers,s=>s.type==="video"),o=r==null?void 0:r.getBuffered();o!==void 0&&(t.audio=o);let a=i==null?void 0:i.getBuffered();return a!==void 0&&(t.video=a),t}async function eu(n,e,t,r,i){let o=e.getPeriod(t);if(o===void 0)throw new Error("Wanted Period not found.");let a=q(o.thumbnailTracks,d=>d.id===r);if(a===void 0)throw new Error("Wanted Period has no thumbnail track.");let s=a.index.getSegments(i,1)[0];if(s===void 0)throw new Error("No thumbnail for the given timestamp");return n({segment:s,track:a,period:o},new D().signal)}function tu(n,e){["video","audio","text"].forEach(t=>{var i;let r=e.getStatus(t);r.type==="initialized"&&r.value.synchronizeInventory((i=n.buffered[t])!=null?i:[])})}function nu(n,e){let{DEFAULT_WANTED_BUFFER_AHEAD:t,DEFAULT_MAX_VIDEO_BUFFER_SIZE:r,DEFAULT_MAX_BUFFER_AHEAD:i,DEFAULT_MAX_BUFFER_BEHIND:o}=O.getCurrent(),a={wantedBufferAhead:new W(t),maxVideoBufferSize:new W(r),maxBufferAhead:new W(i),maxBufferBehind:new W(o),limitVideoResolution:new W({height:void 0,width:void 0,pixelRatio:1}),throttleVideoBitrate:new W(1/0)},s=!1,d=new gr({hasVideo:!0}),u=null,c=null;n(l=>{var m,g;p.debug("Core","received message",{name:l.data.type});let f=l.data;switch(f.type){case"init":{ee(!s),s=!0,xc(f.value),Am(f.value.logLevel,f.value.logFormat,f.value.sendBackLogs);let I=pe.dashParsers.wasm;I!==null&&f.value.dashWasmUrl!==void 0&&I.isCompatible()&&I.initialize({wasmUrl:f.value.dashWasmUrl}).catch(h=>{let y=h instanceof Error?h.toString():"Unknown Error";p.error("Core","Could not initialize DASH_WASM parser",y)}),f.value.hasVideo||(d.disposeCurrentContent(),d=new gr({hasVideo:f.value.hasVideo})),e({type:"init-success",value:null})}break;case"log-level-update":Am(f.value.logLevel,f.value.logFormat,f.value.sendBackLogs);break;case"prepare":UI(e,d,f.value,a);break;case"start":{let I=d.getCurrentContent();if(f.contentId!==(I==null?void 0:I.contentId))return;u==null||u.stop(),c==null||c.finish();let h=new W(G(f.value.initialObservation,{position:new Bt(...f.value.initialObservation.position)}));c=h,u=KI(e,f.value,d,h,a);break}case"observation":{let I=d.getCurrentContent();if(f.contentId!==(I==null?void 0:I.contentId))return;let h=f.value,{buffered:y}=h,T=ji(I.mediaSource,null);T.audio!==null&&(y.audio=T.audio),T.video!==null&&(y.video=T.video),c==null||c.setValue(G(h,{position:new Bt(...f.value.position)}));break}case"ref-update":FI(f,a);break;case"stop":if(f.contentId!==((m=d.getCurrentContent())==null?void 0:m.contentId))return;d.disposeCurrentContent(),u==null||u.stop(),u=null,c==null||c.finish(),c=null;break;case"ms-reload":{let I=d.getCurrentContent();if(f.mediaSourceId!==(I==null?void 0:I.mediaSource.id))return;u==null||u.signalMediaSourceReload()}break;case"sb-success":{let I=d.getCurrentContent();if(f.mediaSourceId!==(I==null?void 0:I.mediaSource.id))return;let{sourceBuffers:h}=I.mediaSource,y=q(h,T=>T.type===f.sourceBufferType);if(y===void 0){p.info("Core","Success for an unknown SourceBuffer",{sourceBufferType:f.sourceBufferType});return}if(y.onOperationSuccess===void 0){p.warn("Core","A SourceBufferInterface with MSE performed a cross-thread operation",{sourceBufferType:f.sourceBufferType});return}y.onOperationSuccess(f.operationId,f.value.buffered);break}case"sb-error":{let I=d.getCurrentContent();if(f.mediaSourceId!==(I==null?void 0:I.mediaSource.id))return;let{sourceBuffers:h}=I.mediaSource,y=q(h,T=>T.type===f.sourceBufferType);if(y===void 0){p.info("Core","Error for an unknown SourceBuffer",{sourceBufferType:f.sourceBufferType});return}if(y.onOperationFailure===void 0){p.warn("Core","A SourceBufferInterface with MSE performed a cross-thread operation",{sourceBufferType:f.sourceBufferType});return}y.onOperationFailure(f.operationId,f.value);break}case"media-source-ready-state-change":{let I=d.getCurrentContent();if(f.mediaSourceId!==(I==null?void 0:I.mediaSource.id))return;if(I.mediaSource.onMediaSourceReadyStateChanged===void 0){p.warn("Core","A MediaSourceInterface with MSE performed a cross-thread operation");return}I.mediaSource.onMediaSourceReadyStateChanged(f.value);break}case"decipherability-update":{if(f.contentId!==((g=d.getCurrentContent())==null?void 0:g.contentId))return;let I=d.getCurrentContent();if(I===null||I.manifest===null)return;let h=f.value;I.manifest.updateRepresentationsDeciperability(y=>{for(let T of h)if(y.representation.uniqueId===T.representationUniqueId)return T.decipherable;return y.representation.decipherable});break}case"codec-support-update":{let I=d.getCurrentContent();if(I===null||I.manifest===null)return;let h=f.value;try{let y=I.manifest.updateCodecSupport(h);y!==null&&e({type:"warning",contentId:I.contentId,value:Je(y)})}catch(y){e({type:"error",contentId:I.contentId,value:Je(y)})}break}case"urls-update":{let I=d.getCurrentContent();if(I===null||I.contentId!==f.contentId)return;I.manifestFetcher.updateContentUrls(f.value.urls,f.value.refreshNow);break}case"track-update":{let I=d.getCurrentContent();if(I===null||I.contentId!==f.contentId)return;I.trackChoiceSetter.setTrack(f.value.periodId,f.value.bufferType,f.value.choice);break}case"rep-update":{let I=d.getCurrentContent();if(I===null||I.contentId!==f.contentId)return;I.trackChoiceSetter.updateRepresentations(f.value.periodId,f.value.adaptationId,f.value.bufferType,f.value.choice);break}case"add-text-success":{let I=d.getCurrentContent();if(I===null||I.contentId!==f.contentId)return;if(I.coreTextSender===null){p.error("Core","Added text track but text track aren't enabled");return}I.coreTextSender.onPushedTrackSuccess(f.value.ranges);break}case"push-text-error":{let I=d.getCurrentContent();if(I===null||I.contentId!==f.contentId)return;if(I.coreTextSender===null){p.error("Core","Added text track but text track aren't enabled");return}I.coreTextSender.onPushedTrackError(new Error(f.value.message));break}case"remove-text-success":{let I=d.getCurrentContent();if(I===null||I.contentId!==f.contentId)return;if(I.coreTextSender===null){p.error("Core","Removed text track but text track aren't enabled");return}I.coreTextSender.onRemoveSuccess(f.value.ranges);break}case"remove-text-error":{let I=d.getCurrentContent();if(I===null||I.contentId!==f.contentId)return;if(I.coreTextSender===null){p.error("Core","Removed text track but text track aren't enabled");return}I.coreTextSender.onRemoveError(new Error(f.value.message));break}case"pull-segment-sink-store-infos":{VI(e,d,f.value.requestId);break}case"thumbnail-request":{WI(e,d,f);break}case"config-update":{O.update(f.value);break}default:we(f)}})}function UI(n,e,t,r){e.initializeNewContent(n,t,{limitResolution:{video:r.limitVideoResolution},throttleBitrate:{video:r.throttleVideoBitrate}}).then(i=>{n({type:"manifest-ready",contentId:t.contentId,value:{manifest:i}})},i=>{n({type:"error",contentId:t.contentId,value:Je(i)})})}function FI(n,e){switch(n.value.name){case"wantedBufferAhead":e.wantedBufferAhead.setValueIfChanged(n.value.newVal);break;case"maxVideoBufferSize":e.maxVideoBufferSize.setValueIfChanged(n.value.newVal);break;case"maxBufferBehind":e.maxBufferBehind.setValueIfChanged(n.value.newVal);break;case"maxBufferAhead":e.maxBufferAhead.setValueIfChanged(n.value.newVal);break;case"limitVideoResolution":e.limitVideoResolution.setValueIfChanged(n.value.newVal);break;case"throttleVideoBitrate":e.throttleVideoBitrate.setValueIfChanged(n.value.newVal);break;default:we(n.value)}}function KI(n,e,t,r,i){p.debug("Core","Loading pepared content.");let o=new D,a=null;return s(e.initialTime),{signalMediaSourceReload:()=>u(),stop:()=>{o.cancel()}};function s(c){var B;a==null||a.cancel(),a=new D,a.linkToSignal(o.signal);let l=new Map,f=t.getCurrentContent();if(f===null||f.manifest===null){let C=new De("NONE","Loading content when none is prepared");throw n({type:"error",contentId:void 0,value:Je(C)}),C}let{contentId:m,cmcdDataBuilder:g,enableRepresentationAvoidance:I,manifest:h,mediaSource:y,representationEstimator:T,segmentSinksStore:v,segmentQueueCreator:E}=f,{drmSystemId:R,enableFastSwitching:k,onCodecSwitch:A}=e;r.onUpdate(C=>{tu(C,v);let w=f.freezeResolver.onNewObservation(C);w!==null&&zI(n,w,{contentId:m,manifest:h,handleMediaSourceReload:d,enableRepresentationAvoidance:I})},{clearSignal:a.signal});let P=(B=h.getPeriodForTime(c))!=null?B:h.getNextPeriod(c);if(P===void 0){let C=new re("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");throw n({type:"error",contentId:m,value:Je(C)}),C}let M=new pi(r,m,n,a.signal);g==null||g.startMonitoringPlayback(M),a.signal.register(()=>{g==null||g.stopMonitoringPlayback()});let N=Jd(h,y,M,v,{onWarning:C=>n({type:"warning",contentId:m,value:Je(C)}),onPeriodChanged:C=>{n({type:"active-period-changed",contentId:m,value:{periodId:C.id}})}},a.signal);lm({initialPeriod:P,manifest:h},M,T,v,E,{wantedBufferAhead:i.wantedBufferAhead,maxVideoBufferSize:i.maxVideoBufferSize,maxBufferAhead:i.maxBufferAhead,maxBufferBehind:i.maxBufferBehind,drmSystemId:R,enableFastSwitching:k,onCodecSwitch:A},U(),a.signal);function U(){return{needsBufferFlush(C){n({type:"needs-buffer-flush",contentId:m,value:C})},streamStatusUpdate(C){L(C),h.isLastPeriodKnown&&C.period.id===h.periods[h.periods.length-1].id&&(C.hasFinishedLoading||C.isEmptyStream?N.onLastSegmentFinishedLoading(C.bufferType):N.onLastSegmentLoadingResume(C.bufferType))},needsManifestRefresh(){t.scheduleManifestRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0})},manifestMightBeOufOfSync(){let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:C}=O.getCurrent();t.scheduleManifestRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:C})},lockedStream(C){n({type:"locked-stream",contentId:m,value:{periodId:C.period.id,bufferType:C.bufferType}})},adaptationChange(C){var w,F;N.onAdaptationChange(C.type,C.period,C.adaptation),!(a===null||a.signal.isCancelled())&&n({type:"adaptation-changed",contentId:m,value:{adaptationId:(F=(w=C.adaptation)==null?void 0:w.id)!=null?F:null,periodId:C.period.id,type:C.type}})},representationChange(C){var w,F;N.onRepresentationChange(C.type,C.period),!(a===null||a.signal.isCancelled())&&n({type:"representation-changed",contentId:m,value:{adaptationId:C.adaptation.id,representationId:(F=(w=C.representation)==null?void 0:w.id)!=null?F:null,periodId:C.period.id,type:C.type}})},inbandEvent(C){n({type:"inband-event",contentId:m,value:C})},warning(C){n({type:"warning",contentId:m,value:Je(C)})},periodStreamReady(C){f!==null&&(f.trackChoiceSetter.addTrackSetter(C.period.id,C.type,C.adaptationRef),n({type:"period-stream-ready",contentId:m,value:{periodId:C.period.id,bufferType:C.type}}))},periodStreamCleared(C){if(f===null)return;let w=l.get(C.period);w!==void 0&&(w.delete(C.type),w.size===0&&l.delete(C.period)),N.onPeriodCleared(C.type,C.period),f.trackChoiceSetter.removeTrackSetter(C.period.id,C.type),n({type:"period-stream-cleared",contentId:m,value:{periodId:C.period.id,bufferType:C.type}})},bitrateEstimateChange(C){var w;f!==null&&((w=f.cmcdDataBuilder)==null||w.updateThroughput(C.type,C.bitrate)),n({type:"bitrate-estimate-change",contentId:m,value:{bitrate:C.bitrate,bufferType:C.type}})},needsMediaSourceReload(C){d(C)},needsDecipherabilityFlush(){n({type:"needs-decipherability-flush",contentId:m,value:null})},encryptionDataEncountered(C){for(let w of C){let F=w.content,K=oe({},F);K.manifest instanceof pn&&(K.manifest=K.manifest.getMetadataSnapshot()),K.period instanceof mn&&(K.period=K.period.getMetadataSnapshot()),K.adaptation instanceof sn&&(K.adaptation=K.adaptation.getMetadataSnapshot()),K.representation instanceof zr&&(K.representation=K.representation.getMetadataSnapshot()),n({type:"encryption-data-encountered",contentId:m,value:{keyIds:w.keyIds,values:w.values,content:K,type:w.type}})}},error(C){n({type:"error",contentId:m,value:Je(C)})}}}function L(C){let{imminentDiscontinuity:w}=C,F=l.get(C.period),K=F==null?void 0:F.get(C.bufferType);if(K!==void 0){if(K.discontinuity===null){if(w===null)return}else if(w!==null&&K.discontinuity.start===w.start&&K.discontinuity.end===w.end)return}F===void 0&&(F=new Map,l.set(C.period,F));let Y={periodId:C.period.id,bufferType:C.bufferType,discontinuity:C.imminentDiscontinuity,position:C.position};F.set(C.bufferType,Y),n({type:"discontinuity-update",contentId:m,value:Y})}}function d(c){var f;a!==null&&(a.cancel(),a=null);let l=(f=t.getCurrentContent())==null?void 0:f.mediaSource.id;if(l===void 0){p.warn("Core","Cannot reload MediaSource: no MediaSource currently.");return}p.debug("Core","Reloading MediaSource",{timeOffset:c.timeOffset,minimumPosition:c.minimumPosition,maximumPosition:c.maximumPosition}),n({type:"reloading-media-source",mediaSourceId:l,value:c},[]),u()}function u(){var m;let l=r.getValue().position.getWanted();a!==null&&(a.cancel(),a=null);let f=(m=t.getCurrentContent())==null?void 0:m.contentId;t.reloadMediaSource(n).then(()=>{p.info("Core","MediaSource Reloaded, loading content again",{newInitialTime:l}),s(l)},g=>{if(D.isCancellationError(g)){p.info("Core","A reloading operation was cancelled");return}n({type:"error",contentId:f,value:Je(g)})})}}function Am(n,e,t){t?p.setLevel(n,"standard",(r,i,o)=>{let a=o.map(s=>s instanceof Error?Je(s):s);postMessage({type:"log",value:{namespace:i,logLevel:r,logs:a}})}):p.setLevel(n,e)}function VI(n,e,t){let r=e.getCurrentContent();if(r===null)return;let i=r.segmentSinksStore.getSegmentSinksMetrics();n({type:"segment-sink-store-update",contentId:r.contentId,value:{segmentSinkMetrics:i,requestId:t}})}function zI(n,e,{contentId:t,manifest:r,handleMediaSourceReload:i,enableRepresentationAvoidance:o}){switch(e.type){case"reload":{p.info("Core","Planning reload due to freeze"),i({timeOffset:0,minimumPosition:0,maximumPosition:1/0});break}case"flush":{p.info("Core","Flushing buffer due to freeze"),n({type:"needs-buffer-flush",contentId:t,value:{relativeResumingPosition:e.value.relativeSeek,relativePosHasBeenDefaulted:!1}});break}case"avoid-representations":{p.info("Core","Planning Representation avoidance due to freeze");let a=e.value;o&&r.addRepresentationsToAvoid(a),i({timeOffset:0,minimumPosition:0,maximumPosition:1/0});break}default:we(e)}}function WI(n,e,t){let r=e.getCurrentContent(),i=o=>{n({type:"thumbnail-response",contentId:t.contentId,value:{status:"error",requestId:t.value.requestId,error:Je(o)}})};if(r===null||r.manifest===null||r.contentId!==t.contentId)return i(new Error("Content changed"));eu(r.fetchThumbnailData,r.manifest,t.value.periodId,t.value.thumbnailTrackId,t.value.time).then(o=>{n({type:"thumbnail-response",contentId:t.contentId,value:{status:"success",requestId:t.value.requestId,data:o}},[o.data])},o=>i(o))}var Ka=nu;var Yi=class{constructor(){this.listeners=[];this.listenersError=[]}addMessageListener(e){this.listeners.push(e)}removeMessageListener(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}addErrorListener(e){this.listenersError.push(e)}removeErrorListener(e){let t=this.listenersError.indexOf(e);t>=0&&this.listenersError.splice(t,1)}dispose(){this.listeners.length=0,this.listenersError.length=0}};var hr=class extends Yi{constructor(){super(),this._currentCoreListener=ae}sendMessage(e){p.debug("M-->C","Sending message",{name:e.type}),queueMicrotask(()=>{this._currentCoreListener({data:e})})}getCallbacks(){return{setCoreMessageReceiver:r=>{this._currentCoreListener=r},sendCoreMessage:(r,i)=>{queueMicrotask(()=>{r.type!=="log"&&p.debug("M<--C","Sending message",{name:r.type}),this.listeners.forEach(o=>{o(r)})})}}}};function Va(){let{FORCE_MEDIA_ELEMENT_FAIL_ON_UNDECIPHERABLE_DATA:n}=O.getCurrent();return n||V.device===V.DEVICES.PlayStation5}function ru(n){let{FORCE_SHOULD_RELOAD_MEDIA_SOURCE_ON_DECIPHERABILITY_UPDATE:e}=O.getCurrent();return e||n===void 0||n.indexOf("widevine")<0}var Ir=class extends se{};function iu(n,{autoPlay:e,initialPlayPerformed:t,manifest:r,mediaSource:i,speed:o,textDisplayer:a},s){return n.deriveReadOnlyObserver(function(u,c){let l=new D;l.linkToSignal(c),l.linkToSignal(s);let f=new W(m(),l.signal);return o.onUpdate(g,{clearSignal:l.signal,emitCurrentValue:!1}),u.onUpdate(g,{clearSignal:l.signal,emitCurrentValue:!1}),i==null||i.addEventListener("streamingChanged",()=>{g()},l.signal),f;function m(){var y;let I=u.getValue(),h=o.getValue();return HI(I,r),{maximumPosition:Ot(r),bufferGap:I.bufferGap,position:I.position,buffered:ji(i,a),duration:I.duration,rebuffering:I.rebuffering,freezing:I.freezing,paused:{last:I.paused,pending:qI(t,e)},readyState:I.readyState,speed:h,canStream:(y=i==null?void 0:i.streaming)!=null?y:!0,fullyLoaded:I.fullyLoaded}}function g(){f.setValue(m())}})}function HI(n,e){if(!e.isDynamic||e.isLastPeriodKnown){let t=e.periods[e.periods.length-1];if(t!==void 0&&t.end!==void 0){let r=n.position.getWanted();if(r>=t.start&&r>=t.end-1){let i=n.buffered;(i.length===0||i.end(i.length-1)<n.duration-1)&&n.position.forceWantedPosition(t.end-1)}}}}function qI(n,e){return n.getValue()?void 0:!e}function yr(n){let{textTracks:e}=n;if(!_(e)){for(let t=0;t<e.length;t++)e[t].mode="disabled";if(n.hasChildNodes()){let{childNodes:t}=n;for(let r=t.length-1;r>=0;r--)if(t[r].nodeName==="track")try{n.removeChild(t[r])}catch(i){p.warn("media","Could not remove text track child from element.")}}}n.src="",n.removeAttribute("src")}var K8=Fe();function ou(n,e){if(e!==null&&n.src===e&&(p.info("media","Clearing HTMLMediaElement's src"),yr(n)),e!==null)try{p.debug("media","Revoking previous URL"),URL.revokeObjectURL(e)}catch(t){p.warn("media","Error while revoking the media source URL",t instanceof Error?t:"")}}function au(n,e){if(Qc&&"disableRemotePlayback"in n){let t=n.disableRemotePlayback;e.register(()=>{n.disableRemotePlayback=t}),n.disableRemotePlayback=!0}}function su(n,e,t){var i;if(!_(t)){let o=Cn(n),a=Ot(n);if(_(t.position))if(_(t.wallClockTime))if(_(t.fromFirstPosition))if(_(t.fromLastPosition))if(_(t.fromLivePosition)){if(!_(t.percentage)){let{percentage:s}=t;if(p.debug("Init","Initial Position: using startAt.percentage",{percentage:s,min:o,max:a}),s>100)return a;if(s<0)return o;let d=+s/100,u=a-o;return o+u*d}}else{let s=(i=Pn(n))!=null?i:a,{fromLivePosition:d}=t;return p.debug("Init","Initial Position: using startAt.fromLivePosition",{fromLivePosition:d,livePosition:s,min:o}),d>=0?s:Math.max(o,s+d)}else{let{fromLastPosition:s}=t;return p.debug("Init","Initial Position: using startAt.fromLastPosition",{fromLastPosition:s,min:o,max:a}),s>=0?a:Math.max(o,a+s)}else{let{fromFirstPosition:s}=t;return p.debug("Init","Initial Position: using startAt.fromFirstPosition",{fromFirstPosition:s,min:o,max:a}),s<=0?o:Math.min(a,o+s)}else{let s=n.availabilityStartTime===void 0?0:n.availabilityStartTime,d=t.wallClockTime-s;return p.debug("Init","Initial Position: using startAt.wallClockTime",{wallClockTime:t.wallClockTime,wallClockOffset:s,deOffseted:d,min:o,max:a,isDynamic:n.isDynamic}),n.isDynamic?d:Math.max(Math.min(d,a),o)}else return p.debug("Init","Initial Position: using startAt.position",{position:t.position,min:o,max:a,isDynamic:n.isDynamic}),n.isDynamic?t.position:Math.max(Math.min(t.position,a),o)}let r=Cn(n);if(n.isLive){let{suggestedPresentationDelay:o,clockOffset:a}=n,s=Ot(n),d,{DEFAULT_LIVE_GAP:u}=O.getCurrent();if(a===void 0)p.info("Init","no clock offset found for a live content, starting close to maximum available position",{maximumPosition:s}),d=s;else{let l=n.availabilityStartTime===void 0?0:n.availabilityStartTime,f=(z()+a)/1e3-l;d=Math.min(s,f),p.info("Init","clock offset found for a live content, checking if we can start close to it",{wallClockOffset:l,clockRelativeLiveTime:f,liveTime:d})}let c=o!=null?o:e?u.LOW_LATENCY:u.DEFAULT;return p.debug("Init","Initial Position: Applying gap from live time",{liveTime:d,diffFromLiveTime:c,minimumPosition:r}),Math.max(d-c,r)}return p.info("Init","Initial Position: starting at the minimum available position",{minimumPosition:r}),r}function Qi(){let{FORCE_SHOULD_VALIDATE_METADATA:n}=O.getCurrent();return n||V.isSamsungBrowser}function du(n){let{FORCE_DONT_WAIT_FOR_DATA_BEFORE_LOADED:e}=O.getCurrent();return!(e||n&&(V.browser===V.BROWSERS.SafariMobile||V.browser===V.BROWSERS.SafariDesktop))}function uu(){let{FORCE_WAIT_FOR_HAVE_ENOUGH_DATA:n}=O.getCurrent();return n||V.device===V.DEVICES.PlayStation5}function $i(n,e,t){let r=new D;r.linkToSignal(t);let i=new W(!1,r.signal);return n.listen(o=>{if(o.rebuffering!==null||o.freezing!==null||o.readyState===0)return;if(!du(e)){if(isNaN(o.duration))return;if(o.duration>0){i.setValue(!0),r.cancel();return}}let a=uu()?4:3;if(o.readyState>=a&&(o.currentRange!==null||o.ended)&&(!Qi()||o.duration>0)){i.setValue(!0),r.cancel();return}},{includeLastObservation:!0,clearSignal:r.signal}),i}function Xi({mediaElement:n,playbackObserver:e,startTime:t,mustAutoPlay:r,isDirectfile:i,onWarning:o},a){let s=new W(!1,a);return{autoPlayResult:new Promise((u,c)=>{let l=a.register(y=>{c(y)});if(a.isCancelled())return;let f=!1,m=y=>{let T=e.getPendingSeekInformation();(T===null||T.isInternal)&&e.setCurrentTime(y),f=!0,e.unblockSeeking()};if(!i||typeof t=="number"){let y=typeof t=="number"?t:t();y!==0&&y!==void 0?m(y):e.unblockSeeking(),g()}else e.listen((y,T)=>{let v=typeof t=="number"?t:t();v===void 0&&y.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||y.readyState>=1&&(T(),v!==0&&v!==void 0?m(v):e.unblockSeeking(),g())},{includeLastObservation:!1,clearSignal:a});function g(){let y=!1;e.listen((T,v)=>{if(!y&&(T.seeking!==0||T.event==="seeking"||T.event==="internal-seeking")&&(y=!0),!(f&&!y||T.readyState===0)){if(v(),Qi()&&n.duration===0){let E=new re("MEDIA_ERR_NOT_LOADED_METADATA","Cannot load automatically: your browser falsely announced having loaded the content.");o(E)}a.isCancelled()||I()}},{includeLastObservation:!1,clearSignal:a})}function I(){e.listen((y,T)=>{y.seeking===0&&y.rebuffering===null&&y.readyState>=1&&(T(),h())},{includeLastObservation:!0,clearSignal:a})}function h(){var T;if(p.info("Init","Can begin to play content"),r){if(n.ended)return p.warn("Init","autoplay is enabled but the video is ended. Skipping autoplay to prevent video to start again"),s.setValue(!0),s.finish(),l(),u({type:"skipped"})}else return n.autoplay&&p.warn("Init","autoplay is enabled on HTML media element. Media will play as soon as possible."),s.setValue(!0),s.finish(),l(),u({type:"skipped"});let y;try{y=(T=n.play())!=null?T:Promise.resolve()}catch(v){return l(),c(v)}y.then(()=>{if(!a.isCancelled())return s.setValue(!0),s.finish(),l(),u({type:"autoplay"})}).catch(v=>{if(l(),!a.isCancelled())if(v instanceof Error&&v.name==="NotAllowedError"){p.warn("Init","Media element can't play. It may be due to browser auto-play policies.");let E=new re("MEDIA_ERR_BLOCKED_AUTOPLAY","Cannot trigger auto-play automatically: your browser does not allow it.");return o(E),a.isCancelled()?void 0:u({type:"autoplay-blocked"})}else c(v)})}}),initialPlayPerformed:s}}function Fn(){let{FORCE_IS_SEEKING_APPROXIMATE:n}=O.getCurrent();return n||V.device===V.DEVICES.Tizen}var Zi=1/60,Kn=class extends se{constructor(e,t,r){super(),this._playbackObserver=e,this._manifest=t,this._speed=r,this._discontinuitiesStore=[],this._isStarted=!1,this._canceller=new D}start(){if(this._isStarted)return;this._isStarted=!0;let e=new fu(this._playbackObserver,this._speed);this._canceller.signal.register(()=>{e.dispose()}),this._playbackObserver.listen(t=>{let r=this._discontinuitiesStore,{buffered:i,position:o,readyState:a,rebuffering:s,freezing:d}=t,{BUFFER_DISCONTINUITY_THRESHOLD:u,FREEZING_STALLED_DELAY:c}=O.getCurrent();if(d!==null&&z()-d.timestamp>c){s===null?e.stopRebuffering():e.startRebuffering(),this.trigger("stalled","freezing");return}if(s===null){if(e.stopRebuffering(),a===1){let h;t.seeking!==0?h=t.seeking===1?"internal-seek":"seeking":h="not-ready",this.trigger("stalled",h);return}this.trigger("unstalled",null);return}let l=s.reason==="seeking"&&t.seeking===1?"internal-seek":s.reason;if(o.isAwaitingFuturePosition()?(e.stopRebuffering(),p.debug("Init","let rebuffering happen as we're awaiting a future position",{wantedPosition:o.getWanted(),lastPolledPosition:o.getPolled()})):e.startRebuffering(),this._manifest===null||Fn()&&z()-s.timestamp<=1e3){this.trigger("stalled",l);return}let{position:f}=s,m=t.position.isAwaitingFuturePosition()?t.position.getWanted():this._playbackObserver.getCurrentTime();if(f!=null&&this._speed.getValue()>0){let h=GI(r,this._manifest,f);if(h!==null){let y=h+.001;if(y<=m)p.info("Init","position to seek already reached, no seeking",{targetTime:m,realSeekTime:y});else{p.warn("Init","skippable discontinuity found in the stream",{lastPolledPosition:o.getPolled(),realSeekTime:y}),this._playbackObserver.setCurrentTime(y),this.trigger("warning",cu(f,y));return}}}let g=f!=null?f:o.getPolled(),I=qf(i,g);if((!Fn()||z()-s.timestamp>1e3)&&this._speed.getValue()>0&&I<u){let h=g+I+Zi;if(m<h){p.warn("Init","discontinuity encountered inferior to the threshold",{positionBlockedAt:g,seekTo:h,BUFFER_DISCONTINUITY_THRESHOLD:u}),this._playbackObserver.setCurrentTime(h),this.trigger("warning",cu(g,h));return}}for(let h=this._manifest.periods.length-2;h>=0;h--){let y=this._manifest.periods[h];if(y.end!==void 0&&y.end<=g){if(this._manifest.periods[h+1].start>g&&this._manifest.periods[h+1].start>m){let T=this._manifest.periods[h+1];this._playbackObserver.setCurrentTime(T.start),this.trigger("warning",cu(g,T.start));return}break}}this.trigger("stalled",l)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}updateDiscontinuityInfo(e){this._isStarted||this.start();let t=this._playbackObserver.getReference().getValue();jI(this._discontinuitiesStore,e,t)}onLockedStream(e,t){var s;this._isStarted||this.start();let r=this._playbackObserver.getReference().getValue();if(r.rebuffering===null||r.paused||this._speed.getValue()<=0||e!=="audio"&&e!=="video")return;let i=r.position.getWanted(),o=(s=r.rebuffering.position)!=null?s:i,a=t.start;i<a&&Math.abs(o-a)<1&&(p.warn("Init",`rebuffering because of a future locked stream.
|
|
4
|
+
Trying to unlock by seeking to the next Period`),this._playbackObserver.setCurrentTime(a+.001))}destroy(){this._canceller.cancel()}};function GI(n,e,t){if(n.length===0)return null;let r=null;for(let i of n){let{period:o}=i;if(o.start>t)return r;let a;if(o.end===void 0||o.end>t){let{discontinuity:s,position:d}=i,{start:u,end:c}=s,l=u!=null?u:d;if(t>=l-Zi)if(c===null){let f=jo(e,o);f!==null?a=f.start+Zi:p.warn("Init","discontinuity at Period's end but no next Period",{periodId:o.id})}else t<c+Zi&&(a=c+Zi);a!==void 0&&(p.info("Init","discontinuity found",{stalledPosition:t,discontinuityEnd:a}),r=r!==null&&r>a?r:a)}}return r}function lu(n){return n.discontinuity!==null}function jI(n,e,t){let r=Math.min(t.position.getPolled(),t.position.getWanted());for(;n.length>0&&n[0].period.end!==void 0&&n[0].period.end+10<r;)n.shift();let{period:i,bufferType:o}=e;if(!(o!=="audio"&&o!=="video")){for(let a=0;a<n.length;a++)if(n[a].period.id===i.id){if(n[a].bufferType===o){lu(e)?n[a]=e:n.splice(a,1);return}}else if(n[a].period.start>i.start){lu(e)&&n.splice(a,0,e);return}lu(e)&&n.push(e)}}function cu(n,e){return new re("DISCONTINUITY_ENCOUNTERED","A discontinuity has been encountered at position "+String(n)+", seeking at position "+String(e))}var fu=class{constructor(e,t){this._speedUpdateCanceller=new D,this._isRebuffering=!1,this._playbackObserver=e,this._isDisposed=!1,this._speed=t,this._updateSpeed()}startRebuffering(){this._isRebuffering||this._isDisposed||(this._isRebuffering=!0,this._speedUpdateCanceller.cancel(),p.info("Init","Pause playback to build buffer"),this._playbackObserver.setPlaybackRate(0))}stopRebuffering(){!this._isRebuffering||this._isDisposed||(this._isRebuffering=!1,this._speedUpdateCanceller=new D,this._updateSpeed())}dispose(){this._speedUpdateCanceller.cancel(),this._isDisposed=!0}_updateSpeed(){this._speed.onUpdate(e=>{p.info("Init","Resume playback speed",{newSpeed:e}),this._playbackObserver.setPlaybackRate(e)},{clearSignal:this._speedUpdateCanceller.signal,emitCurrentValue:!0})}};function YI(n,e){return n.id===e.id&&n.start===e.start&&n.end===e.end}var xm=YI;function QI(n,e){let t=[],{periods:r}=e;for(let i of r){let{streamEvents:o}=i;o.forEach(({start:a,end:s,id:d,data:u})=>{for(let f of n)if(xm(f,{id:d,start:a,end:s})){t.push(f);return}let c;if(u.value.xmlData!==void 0){let f=u.value.xmlData.namespaces.reduce((g,I)=>g+"xmlns:"+I.key+'="'+I.value+'" ',"<toremove ");f+=">";let m=new DOMParser().parseFromString(f+u.value.xmlData.data+"</toremove>","application/xml").documentElement;c=m.children.length>0?m.children[0]:m.childNodes[0]}else return;let l={type:u.type,value:me(oe({},u.value),{xmlData:void 0,element:c})};if(s===void 0){let f={start:a,id:d,data:l,publicEvent:{start:a,data:l}};t.push(f)}else{let f={start:a,end:s,id:d,data:l,publicEvent:{start:a,end:s,data:l}};t.push(f)}})}return t}var mu=QI;var Ji=class extends se{constructor(e,t){super(),this._manifest=e,this._playbackObserver=t,this._canceller=null,this._scheduledEventsRef=new W([]),this._eventsBeingPlayed=new WeakMap}start(){if(this._canceller!==null)return;this._canceller=new D;let e=this._canceller.signal,t=this._playbackObserver,r=!1,i=new D;i.linkToSignal(e),this._scheduledEventsRef.setValue(mu([],this._manifest)),this._scheduledEventsRef.onUpdate(({length:o})=>{if(o===0){r&&(i.cancel(),i=new D,i.linkToSignal(e),r=!1);return}else if(r)return;r=!0;let a=c(),s=()=>{let l=c();this._emitStreamEvents(this._scheduledEventsRef.getValue(),a,l,i.signal),a=l},{STREAM_EVENT_EMITTER_POLL_INTERVAL:d}=O.getCurrent(),u=setInterval(s,d);t.listen(s,{includeLastObservation:!1,clearSignal:i.signal}),i.signal.register(()=>{clearInterval(u)});function c(){var g;let l=t.getReference().getValue(),f=(g=t.getCurrentTime())!=null?g:t.getReference().getValue().position.getPolled(),m=l.seeking!==0;return{currentTime:f,isSeeking:m}}},{emitCurrentValue:!0,clearSignal:e})}onManifestUpdate(e){let t=this._scheduledEventsRef.getValue();this._scheduledEventsRef.setValue(mu(t,e))}stop(){this._canceller!==null&&(this._canceller.cancel(),this._canceller=null)}_emitStreamEvents(e,t,r,i){let{currentTime:o}=t,{isSeeking:a,currentTime:s}=r,d=[],u=[];for(let c=0;c<e.length;c++){let l=e[c],f=l.start,m=pu(l)?l.end:void 0;this._eventsBeingPlayed.has(l)?(f>s||m!==void 0&&s>=m)&&(pu(l)&&u.push(l.publicEvent),this._eventsBeingPlayed.delete(l)):f<=s&&m!==void 0&&s<m?(d.push({type:"stream-event",value:l.publicEvent}),this._eventsBeingPlayed.set(l,!0)):o<f&&s>=(m!=null?m:f)&&(a?d.push({type:"stream-event-skip",value:l.publicEvent}):(d.push({type:"stream-event",value:l.publicEvent}),pu(l)&&u.push(l.publicEvent)))}if(d.length>0){for(let c of d)if(c.type==="stream-event"?this.trigger("event",c.value):this.trigger("eventSkip",c.value),i.isCancelled())return}if(u.length>0){for(let c of u)if(typeof c.onExit=="function"&&c.onExit(),i.isCancelled())return}}};function pu(n){return n.end!==void 0}function eo(n,e,t){if(t.isCancelled())return;n.addEventListener("error",r),t.register(()=>{n.removeEventListener("error",r)});function r(){let i=n.error,o,a;switch(_(i)||(o=i.code,a=i.message),o){case 1:return a=a!=null?a:"The fetching of the associated resource was aborted by the user's request.",e(new re("MEDIA_ERR_ABORTED",a));case 2:return a=a!=null?a:"A network error occurred which prevented the media from being successfully fetched",e(new re("MEDIA_ERR_NETWORK",a));case 3:return a=a!=null?a:"An error occurred while trying to decode the media resource",e(new re("MEDIA_ERR_DECODE",a));case 4:return a=a!=null?a:"The media resource has been found to be unsuitable.",e(new re("MEDIA_ERR_SRC_NOT_SUPPORTED",a));default:return a=a!=null?a:"The HTMLMediaElement errored due to an unknown reason.",e(new re("MEDIA_ERR_UNKNOWN",a))}}}var $I=Fe(),Vn=class extends Ir{constructor(e){super(),this._settings=e,this._initCanceller=new D,this._currentMediaSourceCanceller=new D,this._currentMediaSourceCanceller.linkToSignal(this._initCanceller.signal),this._currentContentInfo=null,this._awaitingRequests={nextRequestId:0,pendingSinkMetrics:new Map,pendingThumbnailFetching:new Map},this._queuedCoreMessages=null}prepare(){var y,T;if(this._currentContentInfo!==null||this._initCanceller.isUsed())return;let e=$I(),{adaptiveOptions:t,transport:r,transportOptions:i,useMseInWorker:o,coreInterface:a}=this._settings,{wantedBufferAhead:s,maxVideoBufferSize:d,maxBufferAhead:u,maxBufferBehind:c}=this._settings.bufferOptions,l=t.initialBitrates.video,f=t.initialBitrates.audio;if(this._currentContentInfo={contentId:e,contentDecryptor:null,manifest:null,mediaSourceInfo:null,rebufferingController:null,streamEventsEmitter:null,initialTime:void 0,autoPlay:void 0,initialPlayPerformed:null,useMseInWorker:o},a.sendMessage({type:"prepare",value:{contentId:e,cmcd:this._settings.cmcd,enableRepresentationAvoidance:this._settings.enableRepresentationAvoidance,url:this._settings.url,hasText:this._hasTextBufferFeature(),transport:r,transportOptions:i,initialVideoBitrate:l,initialAudioBitrate:f,manifestRetryOptions:me(oe({},this._settings.manifestRequestSettings),{lowLatencyMode:this._settings.lowLatencyMode}),segmentRetryOptions:this._settings.segmentRequestOptions,useMseInWorker:o}}),this._initCanceller.signal.register(()=>{a.sendMessage({type:"stop",contentId:e,value:null})}),this._initCanceller.isUsed())return;this._queuedCoreMessages=[],p.debug("Init","addEventListener prepare buffering core messages");let m=v=>{switch(v.type!=="log"&&p.debug("Init","Core message received",v.type),v.type){case"log":{let R=v.value.logs.map(k=>{switch(typeof k){case"string":case"number":case"boolean":case"undefined":return k;case"object":return k===null?null:ZI(k);default:we(k)}});switch(v.value.logLevel){case"NONE":break;case"ERROR":p.error(v.value.namespace,...R);break;case"WARNING":p.warn(v.value.namespace,...R);break;case"INFO":p.info(v.value.namespace,...R);break;case"DEBUG":p.debug(v.value.namespace,...R);break;default:we(v.value.logLevel)}break}default:this._queuedCoreMessages!==null&&this._queuedCoreMessages.push(v);break}};this._settings.coreInterface.addMessageListener(m);let g=()=>{p.error("Init","Error when receiving message from core.")};this._settings.coreInterface.addErrorListener(g),this._initCanceller.signal.register(()=>{p.debug("Init","removeEventListener prepare for core message"),this._settings.coreInterface.removeMessageListener(m),this._settings.coreInterface.removeErrorListener(g)});let I=(y=t.throttlers.throttleBitrate.video)!=null?y:new W(1/0);XI(a,this._initCanceller.signal,[s,"wantedBufferAhead"],[d,"maxVideoBufferSize"],[u,"maxBufferAhead"],[c,"maxBufferBehind"],[I,"throttleVideoBitrate"]),((T=t.throttlers.limitResolution.video)!=null?T:new W({height:void 0,width:void 0,pixelRatio:1})).onUpdate(v=>{a.sendMessage({type:"ref-update",value:{name:"limitVideoResolution",newVal:v}})},{clearSignal:this._initCanceller.signal,emitCurrentValue:!0})}updateContentUrls(e,t){this._currentContentInfo!==null&&this._settings.coreInterface.sendMessage({type:"urls-update",contentId:this._currentContentInfo.contentId,value:{urls:e,refreshNow:t}})}start(e,t){if(this.prepare(),this._initCanceller.isUsed())return;let r=null;this._settings.textTrackOptions.textTrackMode==="html"&&pe.htmlTextDisplayer!==null?(ee(this._hasTextBufferFeature()),r=new pe.htmlTextDisplayer(e,this._settings.textTrackOptions.textTrackElement)):pe.nativeTextDisplayer!==null?(ee(this._hasTextBufferFeature()),r=new pe.nativeTextDisplayer(e)):ee(!this._hasTextBufferFeature()),this._initCanceller.signal.register(()=>{r==null||r.stop()}),eo(e,m=>this._onFatalError(m),this._initCanceller.signal);let i=new W(null),o=new W(0),{statusRef:a,contentDecryptor:s}=this._initializeContentDecryption(e,i,o,()=>c(0,void 0,void 0),this._initCanceller.signal),d=this._currentContentInfo;d!==null&&(d.contentDecryptor=s);let u={mediaElement:e,textDisplayer:r,playbackObserver:t,drmInitializationStatus:a,mediaSourceStatus:o};o.onUpdate((m,g)=>{m===2&&(g(),this._startPlaybackIfReady(u))},{clearSignal:this._initCanceller.signal,emitCurrentValue:!0}),a.onUpdate((m,g)=>{m.initializationState.type==="initialized"&&(g(),this._startPlaybackIfReady(u))},{emitCurrentValue:!0,clearSignal:this._initCanceller.signal});let c=(m,g,I)=>{let h=this._currentContentInfo;if(h===null){p.warn("Init","Asked to reload when no content is loaded.");return}if(h===null||h.mediaSourceInfo===null){p.warn("Init","Asked to reload when no MediaSource is active.");return}let y=h.mediaSourceInfo.type==="main"?h.mediaSourceInfo.mediaSource.id:h.mediaSourceInfo.mediaSourceId;this._settings.coreInterface.sendMessage({type:"ms-reload",mediaSourceId:y,value:null}),l(m,g,I)},l=(m,g,I)=>{var R;let h=this._currentContentInfo;if(h===null){p.warn("Init","Asked to reload when no content is loaded.");return}let y=t.getReference().getValue(),T=y.position.getWanted(),v=((R=h.initialPlayPerformed)==null?void 0:R.getValue())===!0||h.autoPlay===void 0?y.paused:!h.autoPlay,E=T+m;g!==void 0&&(E=Math.max(g,E)),I!==void 0&&(E=Math.min(I,E)),this._reload(e,r,t,o,E,!v)},f=m=>{var g,I,h,y,T,v,E,R,k,A,P,M,N,U,L,B,C,w,F,K,Y,ie,j,Q,ne,X,de,ue,ve,ce,ye,ct,Et,$,Be,rt,it,ot,wr,Or,Dr,Vo,At,Lr,yc,bc,Sc,Tc,_c,Ec,vc,Rc,kc;switch(m.type){case"attach-media-source":{if(((g=this._currentContentInfo)==null?void 0:g.contentId)!==m.contentId)return;this._currentContentInfo!==null&&(((I=this._currentContentInfo.mediaSourceInfo)==null?void 0:I.type)==="main"&&this._currentContentInfo.mediaSourceInfo.mediaSource.dispose(),this._currentContentInfo.mediaSourceInfo={type:"core",mediaSourceId:m.mediaSourceId});let H=m.value;o.onUpdate((ge,fe)=>{ge===1&&(fe(),p.info("media","Attaching MediaSource URL to the media element"),H.type==="handle"?(e.srcObject=H.value,this._currentMediaSourceCanceller.signal.register(()=>{e.srcObject=null})):(e.src=H.value,this._currentMediaSourceCanceller.signal.register(()=>{ou(e,H.value)})),au(e,this._currentMediaSourceCanceller.signal),o.setValue(2))},{emitCurrentValue:!0,clearSignal:this._initCanceller.signal});break}case"warning":if(((h=this._currentContentInfo)==null?void 0:h.contentId)!==m.contentId)return;this.trigger("warning",za(m.value));break;case"error":if(((y=this._currentContentInfo)==null?void 0:y.contentId)!==m.contentId)return;this._onFatalError(za(m.value));break;case"create-media-source":this._onCreateMediaSourceMessage(m,e,o,this._settings.coreInterface);break;case"add-source-buffer":{if(((v=(T=this._currentContentInfo)==null?void 0:T.mediaSourceInfo)==null?void 0:v.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo;H.addSourceBuffer(m.value.sourceBufferType,m.value.codec)}break;case"source-buffer-append":{if(((R=(E=this._currentContentInfo)==null?void 0:E.mediaSourceInfo)==null?void 0:R.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo,ge=q(H.sourceBuffers,fe=>fe.type===m.sourceBufferType);if(ge===void 0)return;ge.appendBuffer(m.value.data,m.value.params).then(fe=>{this._settings.coreInterface.sendMessage({type:"sb-success",mediaSourceId:H.id,sourceBufferType:ge.type,operationId:m.operationId,value:{buffered:fe}})}).catch(fe=>{this._settings.coreInterface.sendMessage({type:"sb-error",mediaSourceId:H.id,sourceBufferType:ge.type,operationId:m.operationId,value:fe instanceof Ee?{errorName:"CancellationError"}:wm(fe).serialize()})})}break;case"source-buffer-remove":{if(((A=(k=this._currentContentInfo)==null?void 0:k.mediaSourceInfo)==null?void 0:A.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo,ge=q(H.sourceBuffers,fe=>fe.type===m.sourceBufferType);if(ge===void 0)return;ge.remove(m.value.start,m.value.end).then(fe=>{this._settings.coreInterface.sendMessage({type:"sb-success",mediaSourceId:H.id,sourceBufferType:ge.type,operationId:m.operationId,value:{buffered:fe}})}).catch(fe=>{this._settings.coreInterface.sendMessage({type:"sb-error",mediaSourceId:H.id,sourceBufferType:ge.type,operationId:m.operationId,value:fe instanceof Ee?{errorName:"CancellationError"}:wm(fe).serialize()})})}break;case"abort-source-buffer":{if(((M=(P=this._currentContentInfo)==null?void 0:P.mediaSourceInfo)==null?void 0:M.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo,ge=q(H.sourceBuffers,fe=>fe.type===m.sourceBufferType);if(ge===void 0)return;ge.abort()}break;case"update-media-source-duration":{if(((U=(N=this._currentContentInfo)==null?void 0:N.mediaSourceInfo)==null?void 0:U.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo;if((H==null?void 0:H.id)!==m.mediaSourceId)return;H.setDuration(m.value.duration,m.value.isRealEndKnown)}break;case"stop-media-source-duration":{if(((B=(L=this._currentContentInfo)==null?void 0:L.mediaSourceInfo)==null?void 0:B.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo;if((H==null?void 0:H.id)!==m.mediaSourceId)return;H.interruptDurationSetting()}break;case"end-of-stream":{if(((w=(C=this._currentContentInfo)==null?void 0:C.mediaSourceInfo)==null?void 0:w.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo;H.maintainEndOfStream()}break;case"stop-end-of-stream":{if(((K=(F=this._currentContentInfo)==null?void 0:F.mediaSourceInfo)==null?void 0:K.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo;H.stopEndOfStream()}break;case"dispose-media-source":{if(((ie=(Y=this._currentContentInfo)==null?void 0:Y.mediaSourceInfo)==null?void 0:ie.type)!=="main"||this._currentContentInfo.mediaSourceInfo.mediaSource.id!==m.mediaSourceId)return;let{mediaSource:H}=this._currentContentInfo.mediaSourceInfo;H.dispose()}break;case"needs-buffer-flush":{if(((j=this._currentContentInfo)==null?void 0:j.contentId)!==m.contentId)return;let H=t.getReference().getValue(),ge=H.position.isAwaitingFuturePosition()?H.position.getWanted():e.currentTime,fe=(ne=(Q=m.value)==null?void 0:Q.relativeResumingPosition)!=null?ne:0,xt=!!((X=m.value)!=null&&X.relativePosHasBeenDefaulted),vt;fe===0&&xt?vt=ge+.001:vt=ge+fe,t.setCurrentTime(vt);break}case"active-period-changed":{if(((de=this._currentContentInfo)==null?void 0:de.contentId)!==m.contentId||this._currentContentInfo.manifest===null)return;let H=q(this._currentContentInfo.manifest.periods,ge=>ge.id===m.value.periodId);H!==void 0&&this.trigger("activePeriodChanged",{period:H});break}case"adaptation-changed":{if(((ue=this._currentContentInfo)==null?void 0:ue.contentId)!==m.contentId||this._currentContentInfo.manifest===null)return;let H=q(this._currentContentInfo.manifest.periods,xt=>xt.id===m.value.periodId);if(H===void 0)return;if(m.value.adaptationId===null){this.trigger("adaptationChange",{period:H,adaptation:null,type:m.value.type});return}let ge=(ve=H.adaptations[m.value.type])!=null?ve:[],fe=q(ge,xt=>xt.id===m.value.adaptationId);fe!==void 0&&this.trigger("adaptationChange",{period:H,adaptation:fe,type:m.value.type});break}case"representation-changed":{if(((ce=this._currentContentInfo)==null?void 0:ce.contentId)!==m.contentId||this._currentContentInfo.manifest===null)return;let H=q(this._currentContentInfo.manifest.periods,vt=>vt.id===m.value.periodId);if(H===void 0)return;if(m.value.representationId===null){this.trigger("representationChange",{period:H,type:m.value.type,representation:null});return}let ge=(ye=H.adaptations[m.value.type])!=null?ye:[],fe=q(ge,vt=>vt.id===m.value.adaptationId);if(fe===void 0)return;let xt=q(fe.representations,vt=>vt.id===m.value.representationId);xt!==void 0&&this.trigger("representationChange",{period:H,type:m.value.type,representation:xt});break}case"encryption-data-encountered":if(((ct=this._currentContentInfo)==null?void 0:ct.contentId)!==m.contentId)return;i.setValue(m.value);break;case"manifest-ready":{if(((Et=this._currentContentInfo)==null?void 0:Et.contentId)!==m.contentId)return;let H=m.value.manifest;this._currentContentInfo.manifest=H,this._updateCodecSupport(H,e),this._startPlaybackIfReady(u);break}case"manifest-update":{if((($=this._currentContentInfo)==null?void 0:$.contentId)!==m.contentId)return;let H=(Be=this._currentContentInfo)==null?void 0:Be.manifest;if(_(H)){p.error("Init","Manifest update but no Manifest loaded");return}Fc(H,m.value.manifest,m.value.updates),(it=(rt=this._currentContentInfo)==null?void 0:rt.streamEventsEmitter)==null||it.onManifestUpdate(H),this._updateCodecSupport(H,e),this.trigger("manifestUpdate",m.value.updates);break}case"update-playback-rate":if(((ot=this._currentContentInfo)==null?void 0:ot.contentId)!==m.contentId)return;t.setPlaybackRate(m.value);break;case"bitrate-estimate-change":if(((wr=this._currentContentInfo)==null?void 0:wr.contentId)!==m.contentId)return;this.trigger("bitrateEstimateChange",{type:m.value.bufferType,bitrate:m.value.bitrate});break;case"inband-event":if(((Or=this._currentContentInfo)==null?void 0:Or.contentId)!==m.contentId)return;this.trigger("inbandEvents",m.value);break;case"locked-stream":{if(((Dr=this._currentContentInfo)==null?void 0:Dr.contentId)!==m.contentId||this._currentContentInfo.manifest===null)return;let H=q(this._currentContentInfo.manifest.periods,ge=>ge.id===m.value.periodId);if(H===void 0)return;(Vo=this._currentContentInfo.rebufferingController)==null||Vo.onLockedStream(m.value.bufferType,H);break}case"period-stream-ready":{if(((At=this._currentContentInfo)==null?void 0:At.contentId)!==m.contentId||this._currentContentInfo.manifest===null)return;let H=q(this._currentContentInfo.manifest.periods,fe=>fe.id===m.value.periodId);if(H===void 0)return;let ge=new W(void 0);ge.onUpdate(fe=>{if(this._currentContentInfo===null){ge.finish();return}_(fe)||fe.representations.onUpdate((xt,vt)=>{if(this._currentContentInfo===null){vt();return}this._settings.coreInterface.sendMessage({type:"rep-update",contentId:this._currentContentInfo.contentId,value:{periodId:m.value.periodId,adaptationId:fe.adaptationId,bufferType:m.value.bufferType,choice:xt}})},{clearSignal:this._initCanceller.signal}),this._settings.coreInterface.sendMessage({type:"track-update",contentId:this._currentContentInfo.contentId,value:{periodId:m.value.periodId,bufferType:m.value.bufferType,choice:_(fe)?fe:{adaptationId:fe.adaptationId,switchingMode:fe.switchingMode,initialRepresentations:fe.representations.getValue(),relativeResumingPosition:fe.relativeResumingPosition}}})},{clearSignal:this._initCanceller.signal}),this.trigger("periodStreamReady",{period:H,type:m.value.bufferType,adaptationRef:ge});break}case"period-stream-cleared":{if(((Lr=this._currentContentInfo)==null?void 0:Lr.contentId)!==m.contentId||this._currentContentInfo.manifest===null)return;this.trigger("periodStreamCleared",{periodId:m.value.periodId,type:m.value.bufferType});break}case"discontinuity-update":{if(((yc=this._currentContentInfo)==null?void 0:yc.contentId)!==m.contentId||this._currentContentInfo.manifest===null)return;let H=q(this._currentContentInfo.manifest.periods,ge=>ge.id===m.value.periodId);if(H===void 0){p.warn("Init","Discontinuity's Period not found",{periodId:m.value.periodId});return}(bc=this._currentContentInfo.rebufferingController)==null||bc.updateDiscontinuityInfo({period:H,bufferType:m.value.bufferType,discontinuity:m.value.discontinuity,position:m.value.position});break}case"push-text-data":{if(((Sc=this._currentContentInfo)==null?void 0:Sc.contentId)!==m.contentId)return;if(r===null)p.warn("text","Received AddTextData message but no text displayer exists");else try{let H=r.pushTextData(m.value);this._settings.coreInterface.sendMessage({type:"add-text-success",contentId:m.contentId,value:{ranges:H}})}catch(H){let ge=H instanceof Error?H.message:"Unknown error";this._settings.coreInterface.sendMessage({type:"push-text-error",contentId:m.contentId,value:{message:ge}})}break}case"remove-text-data":{if(((Tc=this._currentContentInfo)==null?void 0:Tc.contentId)!==m.contentId)return;if(r===null)p.warn("text","Received RemoveTextData message but no text displayer exists");else try{let H=r.removeBuffer(m.value.start,m.value.end);this._settings.coreInterface.sendMessage({type:"remove-text-success",contentId:m.contentId,value:{ranges:H}})}catch(H){let ge=H instanceof Error?H.message:"Unknown error";this._settings.coreInterface.sendMessage({type:"remove-text-error",contentId:m.contentId,value:{message:ge}})}break}case"reset-text-displayer":{if(((_c=this._currentContentInfo)==null?void 0:_c.contentId)!==m.contentId)return;r===null?p.warn("text","Received ResetTextDisplayer message but no text displayer exists"):r.reset();break}case"stop-text-displayer":{if(((Ec=this._currentContentInfo)==null?void 0:Ec.contentId)!==m.contentId)return;r===null?p.warn("text","Received StopTextDisplayer message but no text displayer exists"):r.stop();break}case"reloading-media-source":{if(this._currentContentInfo===null||this._currentContentInfo.mediaSourceInfo===null||(this._currentContentInfo.mediaSourceInfo.type==="main"?this._currentContentInfo.mediaSourceInfo.mediaSource.id:this._currentContentInfo.mediaSourceInfo.mediaSourceId)!==m.mediaSourceId)return;l(m.value.timeOffset,m.value.minimumPosition,m.value.maximumPosition)}break;case"needs-decipherability-flush":{if(((vc=this._currentContentInfo)==null?void 0:vc.contentId)!==m.contentId)return;let H=ur(e);if(ru(H==null?void 0:H[0]))c(0,void 0,void 0);else{let ge=t.getReference().getValue(),fe=ge.position.getWanted();fe+.001<ge.duration?t.setCurrentTime(e.currentTime+.001):t.setCurrentTime(fe)}}break;case"segment-sink-store-update":{if(((Rc=this._currentContentInfo)==null?void 0:Rc.contentId)!==m.contentId)return;let H=this._awaitingRequests.pendingSinkMetrics.get(m.value.requestId);H!==void 0?H.resolve(m.value.segmentSinkMetrics):p.error("Init","Failed to send segment sink store update");break}case"init-success":case"init-error":break;case"log":break;case"thumbnail-response":{if(((kc=this._currentContentInfo)==null?void 0:kc.contentId)!==m.contentId)return;let H=this._awaitingRequests.pendingThumbnailFetching.get(m.value.requestId);H!==void 0?m.value.status==="error"?H.reject(za(m.value.error)):H.resolve(m.value.data):p.error("Init","Failed to send segment sink store update");break}default:we(m)}};if(p.debug("Init","addEventListener for core message"),this._queuedCoreMessages!==null){let m=this._queuedCoreMessages.slice();p.debug("Init","Processing buffered messages",{ammount:m.length});for(let g of m)f(g);this._queuedCoreMessages=null}this._settings.coreInterface.addMessageListener(f),this._initCanceller.signal.register(()=>{p.debug("Init","removeEventListener for core message"),this._settings.coreInterface.removeMessageListener(f)})}dispose(){var e;this._initCanceller.cancel(),this._currentContentInfo!==null&&(((e=this._currentContentInfo.mediaSourceInfo)==null?void 0:e.type)==="main"&&this._currentContentInfo.mediaSourceInfo.mediaSource.dispose(),this._currentContentInfo=null)}_onFatalError(e){this._initCanceller.isUsed()||(this._initCanceller.cancel(),this.trigger("error",e))}_initializeContentDecryption(e,t,r,i,o){var m;let{keySystems:a}=this._settings,s=g=>{r.setValue(1),t.onUpdate((h,y)=>{if(h===null)return;y();let T=new be("MEDIA_IS_ENCRYPTED_ERROR",g,{keyStatuses:void 0,keySystemConfiguration:void 0,keySystem:void 0});this._onFatalError(T)},{clearSignal:o});let I=new W({initializationState:{type:"initialized",value:null},contentDecryptor:null,drmSystemId:void 0});return I.finish(),{statusRef:I,contentDecryptor:null}};if(a.length===0)return s("No `keySystems` option given.");if(pe.decrypt===null)return s("EME feature not activated.");let d=(m=e.FORCED_EME_API)!=null?m:_a("auto");if(d===null)return s("EME API not available on the current page.");p.debug("Init","Creating ContentDecryptor");let u=pe.decrypt,c=new u(d,e,a),l=new W({initializationState:{type:"uninitialized",value:null},drmSystemId:void 0},o),f=g=>{var I;if(g>0){let h=(I=this._currentContentInfo)==null?void 0:I.manifest;if(_(h))return;this._updateCodecSupport(h,e),c.removeEventListener("stateChange",f)}};return c.addEventListener("stateChange",f),c.addEventListener("keyIdsCompatibilityUpdate",g=>{if(this._currentContentInfo===null||this._currentContentInfo.manifest===null)return;let I=Nc(this._currentContentInfo.manifest,g);Va()&&I.some(h=>h.representation.decipherable!==!0)?i():this._settings.coreInterface.sendMessage({type:"decipherability-update",contentId:this._currentContentInfo.contentId,value:I.map(h=>({representationUniqueId:h.representation.uniqueId,decipherable:h.representation.decipherable}))}),this.trigger("decipherabilityUpdate",I)}),c.addEventListener("blackListProtectionData",g=>{if(this._currentContentInfo===null||this._currentContentInfo.manifest===null)return;let I=Bc(this._currentContentInfo.manifest,g);Va()&&I.some(h=>h.representation.decipherable!==!0)?i():this._settings.coreInterface.sendMessage({type:"decipherability-update",contentId:this._currentContentInfo.contentId,value:I.map(h=>({representationUniqueId:h.representation.uniqueId,decipherable:h.representation.decipherable}))}),this.trigger("decipherabilityUpdate",I)}),c.addEventListener("stateChange",g=>{g===1?r.onUpdate((I,h)=>{I===0?r.setValue(1):I===2&&(h(),g===1&&c.attach())},{clearSignal:o,emitCurrentValue:!0}):g===2&&(l.setValue({initializationState:{type:"initialized",value:null},drmSystemId:c.systemId}),c.removeEventListener("stateChange"))}),c.addEventListener("error",g=>{this._onFatalError(g)}),c.addEventListener("warning",g=>{this.trigger("warning",g)}),t.onUpdate(g=>{g!==null&&c.onInitializationData(g)},{clearSignal:o}),o.register(()=>{c.dispose()}),{statusRef:l,contentDecryptor:c}}_updateCodecSupport(e,t){var r,i,o,a;try{let s=Lf(e,(i=(r=this._currentContentInfo)==null?void 0:r.contentDecryptor)!=null?i:null,t,(a=(o=this._currentContentInfo)==null?void 0:o.useMseInWorker)!=null?a:!1);s.length>0&&(this._settings.coreInterface.sendMessage({type:"codec-support-update",value:s}),this.trigger("codecSupportUpdate",null))}catch(s){this._onFatalError(s)}}_hasTextBufferFeature(){return this._settings.textTrackOptions.textTrackMode==="html"&&pe.htmlTextDisplayer!==null||pe.nativeTextDisplayer!==null}_reload(e,t,r,i,o,a){this._currentMediaSourceCanceller.cancel(),this._currentMediaSourceCanceller=new D,this._currentMediaSourceCanceller.linkToSignal(this._initCanceller.signal),i.setValue(1),this.trigger("reloadingMediaSource",{position:o,autoPlay:a}),i.onUpdate((s,d)=>{if(s!==2)return;d();let u=this._setUpModulesOnNewMediaSource({initialTime:o,autoPlay:a,mediaElement:e,textDisplayer:t,playbackObserver:r},this._currentMediaSourceCanceller.signal);if(!this._currentMediaSourceCanceller.isUsed()&&u!==null&&this._currentContentInfo!==null){let c=this._currentContentInfo.contentId;u.listen(l=>{this._settings.coreInterface.sendMessage({type:"observation",contentId:c,value:G(l,{position:l.position.serialize()})})},{includeLastObservation:!0,clearSignal:this._currentMediaSourceCanceller.signal})}},{clearSignal:this._currentMediaSourceCanceller.signal,emitCurrentValue:!0})}_setUpModulesOnNewMediaSource(e,t){if(t.isCancelled())return null;if(this._currentContentInfo===null)return p.error("Init","Setting up modules without a contentId"),null;if(this._currentContentInfo.manifest===null)return p.error("Init","Setting up modules without a loaded Manifest"),null;let{manifest:r,mediaSourceInfo:i}=this._currentContentInfo,{speed:o}=this._settings,{initialTime:a,autoPlay:s,mediaElement:d,textDisplayer:u,playbackObserver:c}=e;this._currentContentInfo.initialTime=a,this._currentContentInfo.autoPlay=s;let{autoPlayResult:l,initialPlayPerformed:f}=Xi({mediaElement:d,playbackObserver:c,startTime:a,mustAutoPlay:s,onWarning:T=>this.trigger("warning",T),isDirectfile:!1},t);this._currentContentInfo.initialPlayPerformed=f;let m=iu(c,{autoPlay:s,initialPlayPerformed:f,manifest:r,mediaSource:(i==null?void 0:i.type)==="main"?i.mediaSource:null,speed:o,textDisplayer:u},t);if(t.isCancelled())return null;let g=new Kn(c,r,o);g.addEventListener("stalled",T=>this.trigger("stalled",T)),g.addEventListener("unstalled",()=>this.trigger("unstalled",null)),g.addEventListener("warning",T=>this.trigger("warning",T)),t.register(()=>{g.destroy()}),g.start(),this._currentContentInfo.rebufferingController=g;let I=this._currentContentInfo;f.onUpdate((T,v)=>{if(T){v();let E=new Ji(r,c);I.streamEventsEmitter=E,E.addEventListener("event",R=>{this.trigger("streamEvent",R)},t),E.addEventListener("eventSkip",R=>{this.trigger("streamEventSkip",R)},t),E.start(),t.register(()=>{E.stop()})}},{clearSignal:t,emitCurrentValue:!0});let h=async()=>{this._awaitingRequests.nextRequestId++;let T=this._awaitingRequests.nextRequestId;return this._settings.coreInterface.sendMessage({type:"pull-segment-sink-store-infos",value:{requestId:T}}),new Promise((v,E)=>{let R=k=>(t.deregister(R),this._awaitingRequests.pendingSinkMetrics.delete(T),E(k));this._awaitingRequests.pendingSinkMetrics.set(T,{resolve:k=>{t.deregister(R),this._awaitingRequests.pendingSinkMetrics.delete(T),v(k)}}),t.register(R)})},y=async(T,v,E)=>{if(this._currentContentInfo===null)return Promise.reject(new Error("Cannot fetch thumbnails: No content loaded."));this._awaitingRequests.nextRequestId++;let R=this._awaitingRequests.nextRequestId;return this._settings.coreInterface.sendMessage({type:"thumbnail-request",contentId:this._currentContentInfo.contentId,value:{requestId:R,periodId:T,thumbnailTrackId:v,time:E}}),new Promise((k,A)=>{let P=N=>{M(),A(N)},M=()=>{t.deregister(P),this._awaitingRequests.pendingThumbnailFetching.delete(R)};this._awaitingRequests.pendingThumbnailFetching.set(R,{resolve:N=>{M(),k(N)},reject:N=>{M(),A(N)}}),t.register(P)})};return l.then(()=>{$i(c,!1,t).onUpdate((T,v)=>{T&&(v(),this.trigger("loaded",{getSegmentSinkMetrics:h,getThumbnailData:y}))},{emitCurrentValue:!0,clearSignal:t})}).catch(T=>{t.isCancelled()||this._onFatalError(T)}),m}_startPlaybackIfReady(e){if(this._currentContentInfo===null||this._currentContentInfo.manifest===null)return!1;let t=e.drmInitializationStatus.getValue();if(t.initializationState.type!=="initialized"||e.mediaSourceStatus.getValue()!==2)return!1;let{contentId:i,manifest:o}=this._currentContentInfo;p.debug("Init","Calculating initial time");let a=su(o,this._settings.lowLatencyMode,this._settings.startAt);p.debug("Init","Initial time calculated",{initialTime:a});let{enableFastSwitching:s,onCodecSwitch:d}=this._settings.bufferOptions,u=this._setUpModulesOnNewMediaSource({initialTime:a,autoPlay:this._settings.autoPlay,mediaElement:e.mediaElement,textDisplayer:e.textDisplayer,playbackObserver:e.playbackObserver},this._currentMediaSourceCanceller.signal);if(this._currentMediaSourceCanceller.isUsed()||u===null)return!0;let c=u.getReference().getValue(),l=G(c,{position:c.position.serialize()});return this._settings.coreInterface.sendMessage({type:"start",contentId:i,value:{initialTime:a,initialObservation:l,drmSystemId:t.drmSystemId,enableFastSwitching:s,onCodecSwitch:d}}),u.listen(f=>{this._settings.coreInterface.sendMessage({type:"observation",contentId:i,value:G(f,{position:f.position.serialize()})})},{includeLastObservation:!1,clearSignal:this._currentMediaSourceCanceller.signal}),this.trigger("manifestReady",o),!0}_onCreateMediaSourceMessage(e,t,r,i){var o;if(((o=this._currentContentInfo)==null?void 0:o.contentId)!==e.contentId)p.info("Init","Ignoring MediaSource attachment due to wrong `contentId`");else{let{mediaSourceId:a}=e;try{r.onUpdate((s,d)=>{var u;if(this._currentContentInfo===null){d();return}if(s===1){d();let c=new Bn(a,"FORCED_MEDIA_SOURCE"in t?t.FORCED_MEDIA_SOURCE:void 0);((u=this._currentContentInfo.mediaSourceInfo)==null?void 0:u.type)==="main"&&this._currentContentInfo.mediaSourceInfo.mediaSource.dispose(),this._currentContentInfo.mediaSourceInfo={type:"main",mediaSource:c},c.addEventListener("mediaSourceOpen",()=>{i.sendMessage({type:"media-source-ready-state-change",mediaSourceId:a,value:"open"})}),c.addEventListener("mediaSourceEnded",()=>{i.sendMessage({type:"media-source-ready-state-change",mediaSourceId:a,value:"ended"})}),c.addEventListener("mediaSourceClose",()=>{i.sendMessage({type:"media-source-ready-state-change",mediaSourceId:a,value:"closed"})});let l=null;c.handle.type==="handle"?t.srcObject=c.handle.value:(l=URL.createObjectURL(c.handle.value),t.src=l),this._currentMediaSourceCanceller.signal.register(()=>{c.dispose(),ou(t,l)}),r.setValue(2),au(t,this._currentMediaSourceCanceller.signal)}},{emitCurrentValue:!0,clearSignal:this._currentMediaSourceCanceller.signal})}catch(s){let d=new De("NONE","Unknown error when creating the MediaSource");this._onFatalError(d)}}}};function XI(n,e,...t){for(let r of t)r[0].onUpdate(i=>{n.sendMessage({type:"ref-update",value:{name:r[1],newVal:i}})},{clearSignal:e,emitCurrentValue:!0})}function za(n){switch(n.name){case"NetworkError":return new at(n.code,new Me(n.baseError.url,n.baseError.status,n.baseError.type));case"MediaError":return new re(n.code,n.reason,{tracks:n.tracks});case"EncryptedMediaError":return new be(n.code,n.reason,{keyStatuses:n.keyStatuses,keySystemConfiguration:n.keySystemConfiguration,keySystem:n.keySystem});case"OtherError":return new De(n.code,n.reason)}}function wm(n){return n instanceof He?n:n instanceof Error?new He(n.name,n.message,n.name==="QuotaExceededError"):new He("Error","Unknown SourceBufferError Error",!1)}function ZI(n){return typeof n!="object"?n:(n==null?void 0:n.isSerializedError)===!0?za(n):n}var JI="<",ey=60,Om=">",Wa=62,gu=45,Dm=47,ty=33,Lm=39,Nm=34,hu=91,ny=93,ry=`\r
|
|
5
|
+
>/= `;function to(n,e={}){var f,m;let t=(f=e.pos)!=null?f:0,r=e.keepComments===!0,i=e.keepWhitespace===!0,o;if(e.attrValue!==void 0)for(e.attrName=(m=e.attrName)!=null?m:"id",o=[];(t=l())!==-1;)t=n.lastIndexOf("<",t),t!==-1&&o.push(u()),n=n.substring(t),t=0;else o=a("");return e.filter!==void 0&&(o=Bm(o,e.filter)),o;function a(g){let I=[];for(;n[t]!==void 0;)if(n.charCodeAt(t)===ey){if(n.charCodeAt(t+1)===Dm){let y=t+2;if(t=n.indexOf(Om,t),n.substring(y,t).indexOf(g)===-1){let v=n.substring(0,t).split(`
|
|
6
6
|
`);throw new Error(`Unexpected close tag
|
|
7
7
|
Line: `+(v.length-1)+`
|
|
8
8
|
Column: `+(v[v.length-1].length+1)+`
|
|
9
|
-
Char: `+n[t])}return t!==-1&&(t+=1),I}else if(n.charCodeAt(t+1)===yy){if(n.charCodeAt(t+2)===qd){let b=t;for(;t!==-1&&!(n.charCodeAt(t)===ba&&n.charCodeAt(t-1)===qd&&n.charCodeAt(t-2)===qd);)t=n.indexOf(Qf,t+1);t===-1&&(t=n.length),r&&I.push(n.substring(b,t+1))}else if(n.charCodeAt(t+2)===Gd&&n.charCodeAt(t+8)===Gd&&n.substring(t+3,t+8).toLowerCase()==="cdata"){let b=n.indexOf("]]>",t);b===-1?(I.push(n.substring(t+9)),t=n.length):(I.push(n.substring(t+9,b)),t=b+3);continue}else{let b=t+1;t+=2;let T=!1;for(;(n.charCodeAt(t)!==ba||T)&&n[t]!==void 0;)n.charCodeAt(t)===Gd?T=!0:T&&n.charCodeAt(t)===Iy&&(T=!1),t++;I.push(n.substring(b,t))}t++;continue}let g=u();I.push(g),g.tagName[0]==="?"&&(I.push(...g.children),g.children=[])}else{let g=s();if(i)g.length>0&&I.push(g);else{let b=g.trim();b.length>0&&I.push(b)}t++}return I}function s(){let h=t;return t=n.indexOf(gy,t)-1,t===-2&&(t=n.length),n.slice(h,t+1)}function d(){let h=t;for(;by.indexOf(n[t])===-1&&n[t]!==void 0;)t++;return n.slice(h,t)}function u(){let h=t;t++;let I=d(),g={},b=[];for(;n.charCodeAt(t)!==ba&&n[t]!==void 0;){let T=n.charCodeAt(t);if(T>64&&T<91||T>96&&T<123){let v=d(),_=n.charCodeAt(t);for(;!isNaN(_)&&_!==Xf&&_!==Zf&&!(_>64&&_<91||_>96&&_<123)&&_!==ba;)t++,_=n.charCodeAt(t);let R;_===Xf||_===Zf?R=c():(R=null,t--),g[v]=R===null?null:em(R)}t++}return n.charCodeAt(t-1)!==$f?(t++,b=a(I)):t++,{tagName:I,attributes:g,children:b,posStart:h,posEnd:t}}function c(){let h=n[t],I=t+1;return t=n.indexOf(h,I),n.slice(I,t)}function l(){let h=new RegExp("\\s"+e.attrName+`\\s*=['"]`+e.attrValue+`['"]`).exec(n);return h!==null?h.index:-1}}function Jf(n,e,t=0,r=""){let i=[];return n.forEach(function(o,a){if(typeof o=="object"&&(e(o,a,t,r)&&i.push(o),o.children.length>0)){let s=Jf(o.children,e,t+1,(w(r)?r+".":"")+a+"."+o.tagName);i=i.concat(s)}}),i}function Sa(n){if(Array.isArray(n)){let e="";return n.forEach(function(t){e+=" "+Sa(t),e=e.trim()}),e}else return typeof n=="object"?Sa(n.children):" "+em(n)}function em(n){return n.indexOf("&")<0?n:n.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&#x([A-Fa-f0-9]+);/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&/g,"&")}function Yd(n,e,t){let{repeatCount:r}=n;if(r>=0)return r;let i;return E(e)?t!==void 0?i=t:i=Number.MAX_VALUE:i=e.start,Math.ceil((i-n.start)/n.duration)-1}function xe(n,e,t){let{start:r,duration:i}=n;if(i<=0)return r;let o=Yd(n,e,t);return r+(o+1)*i}function Ye(n,e){var t;return n*e.timescale+((t=e.indexTimeOffset)!=null?t:0)}function Mt(n,e){var t;return(n-((t=e.indexTimeOffset)!=null?t:0))/e.timescale}function tm(n,e,t){return[n*t,(n+e)*t]}function Sy(n,e){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i].start<=e?t=i+1:r=i}return t-1}function Ta(n,e,t){let{timeline:r}=n,i=Ye(e,n);if(i<0)return null;let o=Sy(r,i);if(o<0||o>=r.length-1)return null;let a=r[o];if(a.duration<=0)return null;let s=r[o+1];if(s===void 0)return null;let d=s.start,u=xe(a,s,t);return i>=u&&i<d?Mt(d,n):null}function Kt(n,e){var i;let{initialization:t}=n,r={};return e!==void 0&&(r.isEMSGWhitelisted=e),{id:"init",isInit:!0,time:0,end:0,duration:0,timescale:1,range:E(t)?void 0:t.range,indexRange:n.indexRange,url:(i=t==null?void 0:t.url)!=null?i:null,complete:!0,privateInfos:r,timestampOffset:-(n.indexTimeOffset/n.timescale)}}function Ty(n,e){let t=n.toString();return t.length>=e?t:(new Array(e+1).join("0")+t).slice(-e)}function Qd(n){return(e,t,r)=>{let i=w(r)?parseInt(r,10):1;return Ty(String(n),i)}}function pt(n,e,t){return Ey(n,e,t)}function Ey(n,e,t){return n.indexOf("$")===-1?n:n.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,String(e)).replace(/\$Bandwidth(%0(\d+)d)?\$/g,Qd(t===void 0?0:t))}function Ea(n,e){return function(r){return r.indexOf("$")===-1?r:r.replace(/\$\$/g,"$").replace(/\$Number(%0(\d+)d)?\$/g,(i,o,a)=>{if(e===void 0)throw new Error("Segment number not defined in a $Number$ scheme");return Qd(e)(i,o,a)}).replace(/\$Time(%0(\d+)d)?\$/g,(i,o,a)=>{if(n===void 0)throw new Error("Segment time not defined in a $Time$ scheme");return Qd(n)(i,o,a)})}}function _y(n,e,t){let r=t-n;return r>0?Math.floor(r/e):0}function Ui(n,e,t,r,i,o){var T;let a=r.getEstimatedMaximumPosition((T=n.availabilityTimeOffset)!=null?T:0),s=Math.min(e+t,a!=null?a:1/0),d=Ye(e,n),u=Ye(s,n),{timeline:c,timescale:l,segmentUrlTemplate:f,startNumber:p,endNumber:h}=n,I=p!=null?p:1,g=[],b=c.length;for(let v=0;v<b;v++){let _=c[v],{duration:R,start:k,range:x}=_,P;a===void 0?P=i:P=Math.min(a*l,i!=null?i:1/0);let M=Yd(_,c[v+1],P),L=n.availabilityTimeComplete!==!1||v!==b-1&&M!==0,F=_y(k,R,d),D=k+F*R;for(;D<u&&F<=M;){let B=I+F;if(h!==void 0&&B>h)break;let A=f===null?null:Ea(D,B)(f),C=D-n.indexTimeOffset,N=R;C<0&&(N=R+C,C=0);let K={id:String(D),time:C/l,end:(C+N)/l,duration:N/l,isInit:!1,range:x,timescale:1,url:A,number:B,timestampOffset:-(n.indexTimeOffset/l),complete:L,privateInfos:{isEMSGWhitelisted:o}};g.push(K),F++,D=k+F*R}if(D>=u||(I+=M+1,h!==void 0&&I>h))return g}return g}function vy(n,e){if(e.timescale!==n.timescale){let{timescale:t}=n;n.timeline.push({start:e.time/e.timescale*t,duration:e.duration/e.timescale*t,repeatCount:e.count===void 0?0:e.count,range:e.range})}else n.timeline.push({start:e.time,duration:e.duration,repeatCount:e.count===void 0?0:e.count,range:e.range});return!0}var xn=class{constructor(e,t){var h,I,g,b;let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t,d=(h=e.timescale)!=null?h:1,c=((I=e.presentationTimeOffset)!=null?I:0)-r*d,l=((g=e.initialization)==null?void 0:g.media)===void 0?null:pt(e.initialization.media,o,a),f=e.media===void 0?null:pt(e.media,o,a),p;e.initialization!==void 0?p=e.initialization.range:e.indexRange!==void 0&&(p=[0,e.indexRange[0]-1]),this._index={indexRange:e.indexRange,indexTimeOffset:c,initialization:{url:l,range:p},segmentUrlTemplate:f,startNumber:e.startNumber,endNumber:e.endNumber,timeline:(b=e.timeline)!=null?b:[],timescale:d},this._manifestBoundsCalculator=t.manifestBoundsCalculator,this._scaledPeriodStart=Ye(r,this._index),this._scaledPeriodEnd=E(i)?void 0:Ye(i,this._index),this._isInitialized=this._index.timeline.length>0,this._isEMSGWhitelisted=s}getInitSegment(){return Kt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return Ui(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){let e=this._index;return e.timeline.length===0?null:Mt(Math.max(this._scaledPeriodStart,e.timeline[0].start),e)}getLastAvailablePosition(){var i;let{timeline:e}=this._index;if(e.length===0)return null;let t=e[e.length-1],r=Math.min(xe(t,null,this._scaledPeriodEnd),(i=this._scaledPeriodEnd)!=null?i:1/0);return Mt(r,this._index)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return this._isInitialized}initialize(e){if(!this._isInitialized){for(let t=0;t<e.length;t++)vy(this._index,e[t]);this._isInitialized=!0}}addPredictedSegments(){m.warn("dash","Cannot add predicted segments to a `BaseRepresentationIndex`")}getTargetSegmentDuration(){let{timeline:e,timescale:t}=this._index,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}_replace(e){this._index=e._index,this._isInitialized=e._isInitialized,this._scaledPeriodEnd=e._scaledPeriodEnd,this._isEMSGWhitelisted=e._isEMSGWhitelisted}_update(){m.error("dash","Base RepresentationIndex: Cannot update a SegmentList")}};var wn=class{constructor(e,t){var p,h,I;if(e.duration===void 0)throw new Error("Invalid SegmentList: no duration");let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t;this._isEMSGWhitelisted=s,this._periodStart=r,this._periodEnd=i;let d=(p=e.presentationTimeOffset)!=null?p:0,u=(h=e.timescale)!=null?h:1,c=d-r*u,l=((I=e.initialization)==null?void 0:I.media)===void 0?null:pt(e.initialization.media,o,a),f=e.list.map(g=>({url:g.media===void 0?null:pt(g.media,o,a),mediaRange:g.mediaRange}));this._index={list:f,timescale:u,duration:e.duration,indexTimeOffset:c,indexRange:e.indexRange,initialization:E(e.initialization)?void 0:{url:l,range:e.initialization.range}}}getInitSegment(){let e=Kt(this._index);return e.privateInfos===void 0&&(e.privateInfos={}),e.privateInfos.isEMSGWhitelisted=this._isEMSGWhitelisted,e}getSegments(e,t){let r=this._index,{duration:i,list:o,timescale:a}=r,s=i/a,d=e-this._periodStart,[u,c]=tm(d,t,a),l=Math.min(o.length-1,Math.floor(c/i)),f=[],p=Math.floor(u/i);for(;p<=l;){let h=o[p].mediaRange,I=o[p].url,g=p*s+this._periodStart,b={id:String(p),time:g,isInit:!1,range:h,duration:s,timescale:1,end:g+s,url:I,timestampOffset:-(r.indexTimeOffset/a),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};f.push(b),p++}return f}shouldRefresh(e,t){return!1}getFirstAvailablePosition(){return this._periodStart}getLastAvailablePosition(){var i;let e=this._index,{duration:t,list:r}=e;return Math.min(r.length*t/e.timescale+this._periodStart,(i=this._periodEnd)!=null?i:1/0)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return!0}initialize(){m.error("dash","A `ListRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("dash","Cannot add predicted segments to a `ListRepresentationIndex`")}getTargetSegmentDuration(){let{duration:e,timescale:t}=this._index;return{duration:e/t,isPrecize:!0}}_replace(e){this._index=e._index}_update(){m.error("dash","A `ListRepresentationIndex` cannot be updated")}};function ar(n){return O.getCurrent().DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR*n}var On=class{constructor(e,t){var b,T,v;let{availabilityTimeOffset:r,manifestBoundsCalculator:i,isDynamic:o,periodEnd:a,periodStart:s,representationId:d,representationBitrate:u,isEMSGWhitelisted:c}=t,l=(b=e.timescale)!=null?b:1;this._availabilityTimeOffset=r,this._manifestBoundsCalculator=i;let f=(T=e.presentationTimeOffset)!=null?T:0,p=s*l,h=f-p;if(e.duration===void 0)throw new Error("Invalid SegmentTemplate: no duration");let I=((v=e.initialization)==null?void 0:v.media)===void 0?null:pt(e.initialization.media,d,u),g=e.media===void 0?null:pt(e.media,d,u);this._index={duration:e.duration,timescale:l,indexRange:e.indexRange,indexTimeOffset:h,initialization:E(e.initialization)?void 0:{url:I,range:e.initialization.range},url:g,presentationTimeOffset:f,startNumber:e.startNumber,endNumber:e.endNumber},this._isDynamic=o,this._periodStart=s,this._scaledRelativePeriodEnd=a===void 0?void 0:(a-s)*l,this._isEMSGWhitelisted=c}getInitSegment(){return Kt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){let r=this._index,{duration:i,startNumber:o,endNumber:a,timescale:s,url:d}=r,u=this._periodStart*s,c=this._scaledRelativePeriodEnd,l=e*s-u,f=(e+t)*s-u,p=this._getFirstSegmentStart(),h=this._getLastSegmentStart();if(E(p)||E(h))return[];let I=Math.max(p,l),g=Math.min(h,f);if(g+i<=I)return[];let b=[],T=o!=null?o:1,v=Math.floor(I/i);for(let _=v*i;_<=g;_+=i){let R=v+T;if(a!==void 0&&R>a)return b;let k=!E(c)&&_+i>c?c-_:i,x=_+u,P=_+this._index.presentationTimeOffset,M=d===null?null:Ea(P,R)(d),L={id:String(R),number:R,time:x/s,end:(x+k)/s,duration:k/s,timescale:1,isInit:!1,scaledDuration:k/s,url:M,timestampOffset:-(r.indexTimeOffset/s),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};b.push(L),v++}return b}getFirstAvailablePosition(){let e=this._getFirstSegmentStart();return E(e)?e:e/this._index.timescale+this._periodStart}getLastAvailablePosition(){let e=this._getLastSegmentStart();if(E(e))return e;let t=this._estimateRelativeScaledEnd();return Math.min(e+this._index.duration,t!=null?t:1/0)/this._index.timescale+this._periodStart}getEnd(){if(!this._isDynamic)return this.getLastAvailablePosition();let e=this._estimateRelativeScaledEnd();if(e===void 0)return;let{timescale:t}=this._index;return(e+this._periodStart*t)/t}awaitSegmentBetween(e,t){if(ne(e<=t),!this._isDynamic)return!1;let{timescale:r}=this._index,i=ar(r),o=this._periodStart*r,a=e*r-o,s=t*r-o,d=this._getLastSegmentStart();if(E(d)){let l=this._estimateRelativeScaledEnd();return l===void 0?s+i>=0:s+i>=0&&a<l-i}let u=d+this._index.duration,c=this._estimateRelativeScaledEnd();return c===void 0?s>u-i:s>u-i&&a<c-i}shouldRefresh(){return!1}checkDiscontinuity(){return null}isSegmentStillAvailable(e){if(e.isInit)return!0;let t=this.getSegments(e.time,.1);return t.length===0?!1:t[0].time===e.time&&t[0].end===e.end&&t[0].number===e.number}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){if(!this._isDynamic)return!1;let e=this._estimateRelativeScaledEnd();if(e===void 0)return!0;let{timescale:t}=this._index,r=this._getLastSegmentStart();if(E(r))return!0;let i=r+this._index.duration,o=ar(t);return i+o<e}isInitialized(){return!0}initialize(){m.error("dash","A `TemplateRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("dash","Cannot add predicted segments to a `TemplateRepresentationIndex`")}getTargetSegmentDuration(){return{duration:this._index.duration/this._index.timescale,isPrecize:!0}}_replace(e){this._index=e._index,this._isDynamic=e._isDynamic,this._periodStart=e._periodStart,this._scaledRelativePeriodEnd=e._scaledRelativePeriodEnd,this._manifestBoundsCalculator=e._manifestBoundsCalculator}_update(e){this._replace(e)}_getFirstSegmentStart(){var a;if(!this._isDynamic)return 0;if(this._scaledRelativePeriodEnd===0||this._scaledRelativePeriodEnd===void 0){let s=this._manifestBoundsCalculator.getEstimatedMaximumPosition((a=this._availabilityTimeOffset)!=null?a:0);if(s!==void 0&&s<this._periodStart)return null}let{duration:e,timescale:t}=this._index,r=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(e/t);if(r===void 0)return;let i=r>this._periodStart?(r-this._periodStart)*t:0;return Math.floor(i/e)*e}_getLastSegmentStart(){var o,a;let{duration:e,timescale:t,endNumber:r,startNumber:i=1}=this._index;if(this._isDynamic){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&this._scaledRelativePeriodEnd!==void 0&&this._scaledRelativePeriodEnd<s-this._periodStart*this._index.timescale){let l=Math.ceil(this._scaledRelativePeriodEnd/e);return r!==void 0&&r-i+1<l&&(l=r-i+1),(l-1)*e}let d=this._manifestBoundsCalculator.getEstimatedMaximumPosition((o=this._availabilityTimeOffset)!=null?o:0);if(d===void 0)return;let u=(d-this._periodStart)*t;if(u<0)return null;let c=Math.floor(u/e);return r!==void 0&&r-i+1<c&&(c=r-i+1),c<=0?null:(c-1)*e}else{let s=(a=this._scaledRelativePeriodEnd)!=null?a:0,d=Math.ceil(s/e);r!==void 0&&r-i+1<d&&(d=r-i+1);let u=(d-1)*e,c=O.getCurrent().MINIMUM_SEGMENT_SIZE*t;return r!==void 0||s-u>c||d<2?u:(d-2)*e}}_estimateRelativeScaledEnd(){var e,t;if(this._index.endNumber!==void 0){let r=this._index.endNumber-((e=this._index.startNumber)!=null?e:1)+1;return Math.max(Math.min(r*this._index.duration,(t=this._scaledRelativePeriodEnd)!=null?t:1/0),0)}if(this._scaledRelativePeriodEnd!==void 0)return Math.max(this._scaledRelativePeriodEnd,0)}};function Bi(n,e){let t=0;for(;n.length>0;){let r=n[0];if(r.start>=e||r.repeatCount===-1)return t;if(r.repeatCount===0)n.shift(),t+=1;else{let i=n[1];if(i!==void 0&&i.start<=e)n.shift(),t+=1;else{if(r.duration<=0)return t;let o=r.start+r.duration,a=1;for(;o<e&&a<=r.repeatCount;)o+=r.duration,a++;if(a>r.repeatCount)n.shift(),t=r.repeatCount+1;else{let s=r.repeatCount-a;return r.start=o,r.repeatCount=s,t+=a,t}}}}return t}function Fi(n,e){if(n.length===0)return n.push(...e),!0;if(e.length===0)return!1;let t=n.length,r=e[0].start,i=n[t-1];if(xe(i,e[0])<r)throw new re("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");for(let c=t-1;c>=0;c--){let l=n[c].start;if(l===r){let f=t-c;return n.splice(c,f,...e),!1}else if(l<r){let f=n[c];if(f.start+f.duration>r)return m.warn("utils","Manifest update removed all previous segments"),n.splice(0,t,...e),!0;if(f.repeatCount===void 0||f.repeatCount<=0)return f.repeatCount<0&&(f.repeatCount=Math.floor((r-f.start)/f.duration)-1),n.splice(c+1,t-(c+1),...e),!1;if(f.start+f.duration*(f.repeatCount+1)<=r)return n.splice(c+1,t-(c+1),...e),!1;let h=(r-f.start)/f.duration-1;if(h%1===0&&f.duration===e[0].duration){let I=e[0].repeatCount<0?-1:e[0].repeatCount+h+1;return n.splice(c,t-c,...e),n[c].start=f.start,n[c].repeatCount=I,!1}return m.warn("utils","Manifest update removed previous segments"),n[c].repeatCount=Math.floor(h),n.splice(c+1,t-(c+1),...e),!1}}let a=n[n.length-1],s=e[e.length-1];if(a.repeatCount!==void 0&&a.repeatCount<0)return a.start>s.start?(m.warn("utils","The new index is older than the previous one"),!1):(m.warn("utils",'The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0);let d=a.start+a.duration*(a.repeatCount+1),u=s.start+s.duration*(s.repeatCount+1);return d>=u?(m.warn("utils","The new index is older than the previous one"),!1):(m.warn("utils",'The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0)}function Ki(n,e,t){let r=n.start,i=n.duration,o=n.repeatCount;return r===void 0&&(e===null?r=0:E(e.duration)||(r=e.start+e.duration*(e.repeatCount+1))),(i===void 0||isNaN(i))&&t!==null&&t.start!==void 0&&!isNaN(t.start)&&r!==void 0&&!isNaN(r)&&(i=t.start-r),r!==void 0&&!isNaN(r)&&i!==void 0&&!isNaN(i)&&(o===void 0||!isNaN(o))?{start:r,duration:i,repeatCount:o===void 0?0:o}:(m.warn("dash",'A "S" Element could not have been parsed.'),null)}function Vi(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!E(r))switch(t){case"t":{let i=parseInt(r,10);isNaN(i)?m.warn("dash","invalid t value for <S> element",{val:r}):e.start=i;break}case"d":{let i=parseInt(r,10);isNaN(i)?m.warn("dash","invalid d value for <S> element",{val:r}):e.duration=i;break}case"r":{let i=parseInt(r,10);isNaN(i)?m.warn("dash","invalid r value for <S> element",{val:r}):e.repeatCount=i;break}}}return e}function an(n){let e=[];for(let r=0;r<n.length;r++)e.push(Vi(n[r]));let t=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[t.length-1]===void 0?null:t[t.length-1],a=e[r+1]===void 0?null:e[r+1],s=Ki(i,o,a);s!==null&&t.push(s)}return t}function $d(n,e){if(n.length===0||e.length===0)return null;let t=n[0].start,r=e[0].attributes.t,i=E(r)?null:parseInt(r,10);if(i===null||Number.isNaN(i))return null;if(t===i)return{prevSegmentsIdx:0,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(t<i){let o=n[0],a=0;for(;;){if(o.repeatCount>0){let s=i-o.start;if(s%o.duration===0&&s/o.duration<=o.repeatCount)return{repeatNumberInPrevSegments:s/o.duration,prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInNewElements:0}}if(a++,a>=n.length)return null;if(o=n[a],o.start===i)return{prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(o.start>i)return null}}else{let o=0,a=e[0],s=i;for(;;){let d=a.attributes.d,u=E(d)?null:parseInt(d,10);if(u===null||Number.isNaN(u))return null;let c=a.attributes.r,l=E(c)?null:parseInt(c,10);if(l!==null){if(Number.isNaN(l)||l<0)return null;if(l>0){let h=t-s;if(h%u===0&&h/u<=l)return{repeatNumberInPrevSegments:0,repeatNumberInNewElements:h/u,prevSegmentsIdx:0,newElementsIdx:o}}s+=u*(l+1)}else s+=u;if(o++,o>=e.length)return null;a=e[o];let f=a.attributes.t,p=E(f)?null:parseInt(f,10);if(p!==null){if(Number.isNaN(p))return null;s=p}if(s===t)return{newElementsIdx:o,prevSegmentsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(s>i)return null}}}function Xd(n,e){var I;let t=$d(e,n);if(t===null)return m.warn("dash",'Cannot perform "based" update. Common segment not found.'),an(n);let{prevSegmentsIdx:r,newElementsIdx:i,repeatNumberInPrevSegments:o,repeatNumberInNewElements:a}=t,d=e.length-r+i-1;if(d>=n.length)return m.info("dash",'Cannot perform "based" update. New timeline too short'),an(n);let u=e.slice(r);if(o>0){let g=u[0];g.start+=g.duration*o,u[0].repeatCount-=o}if(a>0&&i!==0)return m.info("dash",'Cannot perform "based" update. The new timeline has a different form.'),an(n);let c=u[u.length-1],l=Vi(n[d]),f=((I=l.repeatCount)!=null?I:0)-a;if(l.duration!==c.duration||c.repeatCount>f)return m.info("dash",'Cannot perform "based" update. The new timeline has a different form at the beginning.'),an(n);l.repeatCount!==void 0&&l.repeatCount>c.repeatCount&&(c.repeatCount=l.repeatCount);let p=[],h=[];for(let g=d+1;g<n.length;g++)h.push(Vi(n[g]));for(let g=0;g<h.length;g++){let b=h[g],T=p[p.length-1]===void 0?c:p[p.length-1],v=h[g+1]===void 0?null:h[g+1],_=Ki(b,T,v);_!==null&&p.push(_)}return u.concat(p)}var zi=class n{constructor(e,t){var _,R,k,x,P;if(!n.isTimelineIndexArgument(e))throw new Error("The given index is not compatible with a TimelineRepresentationIndex.");let{availabilityTimeComplete:r,availabilityTimeOffset:i,manifestBoundsCalculator:o,isDynamic:a,isLastPeriod:s,representationId:d,representationBitrate:u,periodStart:c,periodEnd:l,isEMSGWhitelisted:f}=t,p=(_=e.timescale)!=null?_:1,h=(R=e.presentationTimeOffset)!=null?R:0,I=c*p,g=h-I;this._manifestBoundsCalculator=o,this._isEMSGWhitelisted=f,this._isLastPeriod=s,this._lastUpdate=(k=t.receivedTime)!=null?k:z(),this._unsafelyBaseOnPreviousIndex=null,t.unsafelyBaseOnPreviousRepresentation!==null&&t.unsafelyBaseOnPreviousRepresentation.index instanceof n&&(t.unsafelyBaseOnPreviousRepresentation.index._unsafelyBaseOnPreviousIndex=null,this._unsafelyBaseOnPreviousIndex=t.unsafelyBaseOnPreviousRepresentation.index),this._isDynamic=a,this._parseTimeline=(x=e.timelineParser)!=null?x:null;let b=((P=e.initialization)==null?void 0:P.media)===void 0?null:pt(e.initialization.media,d,u),T=e.media===void 0?null:pt(e.media,d,u),v;i===void 0&&r===void 0?v=1/0:v=i!=null?i:0,this._index={availabilityTimeComplete:r!=null?r:!0,availabilityTimeOffset:v,indexRange:e.indexRange,indexTimeOffset:g,initialization:E(e.initialization)?void 0:{url:b,range:e.initialization.range},segmentUrlTemplate:T,startNumber:e.startNumber,endNumber:e.endNumber,timeline:e.timeline===void 0?null:Zd(e.timeline,e.startNumber,e.endNumber),timescale:p},this._scaledPeriodStart=Ye(c,this._index),this._scaledPeriodEnd=l===void 0?void 0:Ye(l,this._index)}getInitSegment(){return Kt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),Ui(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=this._index.timeline;return e.length===0?null:Mt(Math.max(this._scaledPeriodStart,e[0].start),this._index)}getLastAvailablePosition(){var r;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=_a(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(e===null)return null;let t=Math.min(e.end,(r=this._scaledPeriodEnd)!=null?r:1/0);return Mt(t,this._index)}getEnd(){var r;if(this._isDynamic&&!this._isLastPeriod)return;if(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),this._index.timeline.length<=0)return null;let e=this._index.timeline[this._index.timeline.length-1],t=Math.min(xe(e,null,this._scaledPeriodEnd),(r=this._scaledPeriodEnd)!=null?r:1/0);return Mt(t,this._index)}awaitSegmentBetween(e,t){var u,c;if(ne(e<=t),!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timescale:r,timeline:i}=this._index,o=ar(r),a=Ye(t,this._index),s=_a(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(s!==null&&Math.min(s.end,(u=this._scaledPeriodEnd)!=null?u:1/0)+o>=Math.min(a,(c=this._scaledPeriodEnd)!=null?c:1/0))return!1;let d=Ye(e,this._index);if(i.length>0&&s!==null&&!s.isLastOfTimeline){let l=i[i.length-1],p=xe(l,null,this._scaledPeriodEnd)+o;if(d<p+o)return!0}return this._isLastPeriod?this._scaledPeriodEnd===void 0?a+o>this._scaledPeriodStart?void 0:!1:d-o<this._scaledPeriodEnd&&a+o>this._scaledPeriodStart:!1}isSegmentStillAvailable(e){return e.isInit?!0:(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),Ry(e,this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd))}checkDiscontinuity(e){this._refreshTimeline();let t=this._index.timeline;return t===null&&(t=this._getTimeline(),this._index.timeline=t),Ta({timeline:t,timescale:this._index.timescale,indexTimeOffset:this._index.indexTimeOffset},e,this._scaledPeriodEnd)}canBeOutOfSyncError(e){return this._isDynamic?e instanceof ut&&e.isHttpError(404):!1}_replace(e){this._parseTimeline=e._parseTimeline,this._index=e._index,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._manifestBoundsCalculator=e._manifestBoundsCalculator,this._isLastPeriod=e._isLastPeriod}_update(e){this._index.timeline===null&&(this._index.timeline=this._getTimeline()),e._index.timeline===null&&(e._index.timeline=e._getTimeline()),Fi(this._index.timeline,e._index.timeline)&&(this._index.startNumber=e._index.startNumber),this._index.availabilityTimeOffset=e._index.availabilityTimeOffset,this._index.availabilityTimeComplete=e._index.availabilityTimeComplete,this._index.endNumber=e._index.endNumber,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._isLastPeriod=e._isLastPeriod}isStillAwaitingFutureSegments(){var a;if(!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timeline:e}=this._index;if(e.length===0){if(this._scaledPeriodEnd!==void 0){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&Ye(s,this._index)>this._scaledPeriodEnd)return!1}return this._isLastPeriod}let t=ar(this._index.timescale),r=_a(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(r!==null&&!r.isLastOfTimeline){let s=Math.min(r.end,(a=this._scaledPeriodEnd)!=null?a:1/0);return!(this._scaledPeriodEnd!==void 0&&s+t>=this._scaledPeriodEnd)}if(!this._isLastPeriod)return!1;if(this._scaledPeriodEnd===void 0)return!0;let i=e[e.length-1];return xe(i,null,this._scaledPeriodEnd)+t<this._scaledPeriodEnd}isInitialized(){return!0}initialize(){m.error("dash","A `TimelineRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("dash","Cannot add predicted segments to a `TimelineRepresentationIndex`")}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._index;if(e===null)return;let r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}static isTimelineIndexArgument(e){return typeof e.timelineParser=="function"||Array.isArray(e.timeline)}_refreshTimeline(){var i,o;if(this._index.timeline===null&&(this._index.timeline=this._getTimeline()),!this._isDynamic)return;let e=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(((o=(i=this._index.timeline[0])==null?void 0:i.duration)!=null?o:0)/this._index.timescale);if(E(e))return;let t=Ye(e,this._index),r=Bi(this._index.timeline,t);this._index.startNumber!==void 0?this._index.startNumber+=r:this._index.endNumber!==void 0&&(this._index.startNumber=r+1)}_getTimeline(){if(this._parseTimeline===null)return this._index.timeline!==null?this._index.timeline:(m.error("dash","Timeline already lazily parsed."),[]);let e=this._parseTimeline();this._parseTimeline=null;let{MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:t}=O.getCurrent();if(this._unsafelyBaseOnPreviousIndex===null||e.length<t)return Zd(an(e),this._index.startNumber,this._index.endNumber);let r;return this._unsafelyBaseOnPreviousIndex._index.timeline===null?(r=this._unsafelyBaseOnPreviousIndex._getTimeline(),this._unsafelyBaseOnPreviousIndex._index.timeline=r):r=this._unsafelyBaseOnPreviousIndex._index.timeline,this._unsafelyBaseOnPreviousIndex=null,Zd(Xd(e,r),this._index.startNumber,this._index.endNumber)}};function Zd(n,e,t){if(t===void 0)return n;let r=e!=null?e:1;for(let i=0;i<n.length;i++){let o=n[i];if(r+=o.repeatCount+1,r>t){if(r===t+1)return n.slice(0,i+1);{let a=n.slice(0,i),s=ae({},o),d=r-o.repeatCount-1;return s.repeatCount=Math.max(0,t-d),a.push(s),a}}}return n}function Ry(n,e,t,r){let i=_a(e,t,r);if(i===null)return!1;for(let o=0;o<e.timeline.length;o++){if(i.timelineIdx<o)return!1;let a=e.timeline[o],s=(a.start-e.indexTimeOffset)/e.timescale;if(s>n.time)return!1;if(s===n.time)return a.range===void 0?n.range===void 0:!E(n.range)&&a.range[0]===n.range[0]&&a.range[1]===n.range[1];if(a.repeatCount>=0&&a.duration!==void 0){let u=(s-a.start)/a.duration-1;return u%1===0&&u<=i.newRepeatCount}}return!1}function _a(n,e,t){if(n.timeline.length<=0)return null;if(n.availabilityTimeOffset===1/0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:xe(o,null,t)}}let r=e.getEstimatedMaximumPosition(n.availabilityTimeOffset);if(r===void 0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:xe(o,null,t)}}for(let i=n.timeline.length-1;i>=n.timeline.length;i--){let o=n.timeline[i],a=o.start+o.duration;if(Mt(a,n)<=r){let s=xe(o,n.timeline[i+1],t);if(Mt(s,n)<=r)return{isLastOfTimeline:i===n.timeline.length-1,timelineIdx:i,newRepeatCount:o.repeatCount,end:a};{let u=Ye(r,n)-o.start,c=Math.floor(u/o.duration);return ne(c>=1),{isLastOfTimeline:!1,timelineIdx:i,newRepeatCount:c-1,end:o.start+c*o.duration}}}}return null}var va=zi;var Wi=class{constructor(){this._refs=new Map,this._stored=[]}addReferences(e){for(let t of e)t.attributes.refId!==void 0&&this._refs.set(t.attributes.refId,t)}add(e,t){this._tryParsing(e,t,!1)||this._stored.push([e,t]),t.attributes.refId!==void 0&&(this._refs.set(t.attributes.refId,t),this._resolveStoredRefs(!1))}finalize(){this._resolveStoredRefs(!0)}_resolveStoredRefs(e){for(let t=this._stored.length-1;t>=0;t--){let[r,i]=this._stored[t];(this._tryParsing(r,i,e)||e)&&this._stored.splice(t,1)}return this._stored.length===0}_tryParsing(e,t,r){if(t.attributes.ref===void 0)return Jd(e,t),!0;let i=this._getReferenced(t.attributes.ref);return i===void 0?(r&&(m.warn("dash","forcing the parsing of a referencing ContentProtection"),Jd(e,t)),!1):(t.children.cencPssh.push(...i.children.cencPssh),t.attributes.keyId===void 0&&i.attributes.keyId!==void 0&&(t.attributes.keyId=i.attributes.keyId),t.attributes.schemeIdUri===void 0&&i.attributes.schemeIdUri!==void 0&&(t.attributes.schemeIdUri=i.attributes.schemeIdUri),t.attributes.value===void 0&&i.attributes.value!==void 0&&(t.attributes.value=i.attributes.value),Jd(e,t),!0)}_getReferenced(e){return this._refs.get(e)}};function Jd(n,e){let t;if(e.attributes.schemeIdUri!==void 0&&e.attributes.schemeIdUri.substring(0,9)==="urn:uuid:"&&(t=e.attributes.schemeIdUri.substring(9).replace(/-/g,"").toLowerCase()),e.attributes.keyId!==void 0&&e.attributes.keyId.length>0){let a=e.attributes.keyId;n.contentProtections===void 0?n.contentProtections={keyIds:[a],initData:[]}:n.contentProtections.keyIds===void 0?n.contentProtections.keyIds=[a]:n.contentProtections.keyIds.push(a)}if(t===void 0)return;let{cencPssh:r}=e.children,i=[];for(let a of r)i.push({systemId:t,data:a});if(i.length===0)return;if(n.contentProtections===void 0){n.contentProtections={keyIds:[],initData:[{type:"cenc",values:i}]};return}let o=Q(n.contentProtections.initData,a=>a.type==="cenc");o===void 0?n.contentProtections.initData.push({type:"cenc",values:i}):o.values.push(...i)}function Ra(n){let e=Date.parse(n)-z();if(isNaN(e)){m.warn("dash","Invalid clock received",{clock:n});return}return e}function eu(n){let e=n.children.utcTimings.filter(t=>(t.schemeIdUri==="urn:mpeg:dash:utc:http-iso:2014"||t.schemeIdUri==="urn:mpeg:dash:utc:http-xsdate:2014")&&t.value!==void 0);return e.length>0?e[0].value:void 0}function ka(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getLastAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.min(t,i))}return t===null?null:t}function tu(n){for(let e=n.length-1;e>=0;e--){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=ka(r);if(s===void 0)return{safe:void 0,unsafe:void 0};o=s}if(i!==void 0){let s=ka(i);if(s===void 0)return{safe:void 0,unsafe:void 0};a=s}if(r!==void 0&&o===null||i!==void 0&&a===null)return m.info("utils","found Period with no segment. ","Going to previous one to calculate last position"),{safe:void 0,unsafe:void 0};if(a!==null)return o!==null?{safe:Math.min(o,a),unsafe:Math.max(o,a)}:{safe:a,unsafe:a};if(o!==null)return{safe:o,unsafe:o}}}return{safe:void 0,unsafe:void 0}}function Pa(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getFirstAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.max(t,i))}return t===null?null:t}function nu(n){for(let e=0;e<=n.length-1;e++){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=Pa(r);if(s===void 0)return;o=s}if(i!==void 0){let s=Pa(i);if(s===void 0)return;a=s}if(r!==void 0&&o===null||i!==void 0&&a===null){m.info("utils","found Period with no segment. ","Going to next one to calculate first position");return}if(a!==null)return o!==null?Math.max(o,a):a;if(o!==null)return o}}}function ru(n){if(n.length===0)throw new Error("DASH Parser: no period available for a dynamic content");let e=nu(n),t=tu(n);return{minimumSafePosition:e,maximumSafePosition:t.safe,maximumUnsafePosition:t.unsafe}}var Hi=class{constructor(e){this._isDynamic=e.isDynamic,this._timeShiftBufferDepth=!e.isDynamic||e.timeShiftBufferDepth===void 0?null:e.timeShiftBufferDepth,this._serverTimestampOffset=e.serverTimestampOffset,this._availabilityStartTime=e.availabilityStartTime}setLastPosition(e,t){this._lastPosition=e,this._positionTime=t}lastPositionIsKnown(){return this._isDynamic?this._positionTime!==void 0&&this._lastPosition!==void 0:this._lastPosition!==void 0}getEstimatedMinimumSegmentTime(e){var i;if(!this._isDynamic||this._timeShiftBufferDepth===null)return 0;let t=(i=this.getEstimatedLiveEdge())!=null?i:this.getEstimatedMaximumPosition(0);return t===void 0?void 0:t-(this._timeShiftBufferDepth+e)}getEstimatedLiveEdge(){if(!(!this._isDynamic||this._serverTimestampOffset===void 0))return(z()+this._serverTimestampOffset)/1e3-this._availabilityStartTime}getEstimatedMaximumPosition(e){if(!this._isDynamic)return this._lastPosition;let t=this.getEstimatedLiveEdge();return t!==void 0&&e!==1/0?t+e:this._positionTime!==void 0&&this._lastPosition!==void 0?Math.max(this._lastPosition-this._positionTime+z()/1e3,0):this._lastPosition}};function iu(n,e){return n.type!=="dynamic"?0:E(n.availabilityStartTime)?e!=null?e:0:n.availabilityStartTime}function ou(n){if(n.length===0)return[];let e=[n[0]];for(let t=1;t<n.length;t++){let r=n[t],i=e[e.length-1];for(;(i.duration===void 0||i.start+i.duration>r.start)&&(m.warn("dash","Updating overlapping Periods.",{lastStart:i==null?void 0:i.start,newStart:r.start}),i.duration=r.start-i.start,i.end=r.start,!(i.duration>0));){if(e.pop(),e.length===0)break;i=e[e.length-1]}e.push(r)}return e}function au(n,e){let t=[];return n.forEach((r,i)=>{let o;if(!E(r.attributes.start))o=r.attributes.start;else if(i===0)o=!e.isDynamic||E(e.availabilityStartTime)?0:e.availabilityStartTime;else{let u=t[t.length-1];if(!E(u)&&!E(u.periodEnd))o=u.periodEnd;else throw new Error("Missing start time when parsing periods.")}let a,s=n[i+1];E(r.attributes.duration)?i===n.length-1?a=e.duration:E(s.attributes.start)||(a=s.attributes.start-o):a=r.attributes.duration;let d=E(a)?void 0:o+a;t.push({periodStart:o,periodDuration:a,periodEnd:d})}),t}function ky(n,e){for(let t of e){let{adaptation:r,trickModeAttachedAdaptationIds:i}=t;for(let o of i)for(let a of Jt){let s=n[a];if(s!==void 0)for(let d of s)d.id===o&&(d.trickModeTracks===void 0&&(d.trickModeTracks=[]),d.trickModeTracks.push(r))}}}var nm=ky;var Py=["subtitle","caption"];function su(n,e){var s,d,u,c;let t=(c=Q((s=n.children.essentialProperties)!=null?s:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile"))!=null?c:Q((u=(d=e!=null?e:n.children.representations[0])==null?void 0:d.children.essentialProperties)!=null?u:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile");if(t===void 0)return null;let r=/(\d+)x(\d+)/;if(t===void 0||t.value===void 0||!r.test(t.value))return m.warn("dash","Invalid thumbnails Representation, no tile-related information"),null;let i=t.value.match(r),o=parseInt(i[1],10),a=parseInt(i[2],10);return{horizontalTiles:o,verticalTiles:a}}function du(n,e){if(n.attributes.contentType==="image")return su(n)!==null?"thumbnails":void 0;let t=w(n.attributes.mimeType)?n.attributes.mimeType:null,r=w(n.attributes.codecs)?n.attributes.codecs:null,i=E(n.children.roles)?null:n.children.roles;function o(s,d){let u=s.split("/")[0];if($(Jt,u))return u;if(s==="application/ttml+xml")return"text";if(s==="application/mp4")return d!==null&&Q(d,c=>c.schemeIdUri==="urn:mpeg:dash:role:2011"&&$(Py,c.value))!==void 0?"text":void 0}function a(s){switch(s.substring(0,3)){case"avc":case"hev":case"hvc":case"vp8":case"vp9":case"av1":return"video";case"vtt":return"text"}switch(s.substring(0,4)){case"mp4a":return"audio";case"wvtt":case"stpp":return"text"}}if(t!==null){let s=o(t,i);if(s!==void 0)return s}if(r!==null){let s=a(r);if(s!==void 0)return s}for(let s=0;s<e.length;s++){let d=e[s],{mimeType:u,codecs:c}=d.attributes;if(u!==void 0){let l=o(u,i);if(l!==void 0)return l}if(c!==void 0){let l=a(c);if(l!==void 0)return l}}}var Cy=/[, ]+/g;function rm(n){return w(n)?n.trim().replace(Cy,", "):""}function im(n){let[e,t,r,i,o,a,s,d]=n.split(".");if(e!=="vp08"&&e!=="vp09"&&e!=="vp10")return;let u,c,l;if((i!==void 0&&i==="10"||i==="12")&&(u=parseInt(i,10)),s!==void 0&&(s==="16"?c="pq":s==="18"&&(c="hlg")),a!==void 0&&d!==void 0&&a==="09"&&d==="09"&&(l="rec2020"),!(u===void 0||c===void 0))return{colorDepth:u,eotf:c,colorSpace:l}}function uu(n,e){var h,I,g;let{availabilityTimeOffset:t,manifestBoundsCalculator:r,isDynamic:i,end:o,start:a,receivedTime:s,unsafelyBaseOnPreviousRepresentation:d,inbandEventStreams:u,isLastPeriod:c}=e,f={availabilityTimeComplete:void 0,availabilityTimeOffset:t,unsafelyBaseOnPreviousRepresentation:d,isEMSGWhitelisted:b=>u===void 0?!1:u.some(({schemeIdUri:T})=>T===b.schemeIdUri),isLastPeriod:c,manifestBoundsCalculator:r,isDynamic:i,periodEnd:o,periodStart:a,receivedTime:s,representationBitrate:n.attributes.bitrate,representationId:n.attributes.id},p;if(n.children.segmentBase!==void 0){let{segmentBase:b}=n.children;p=new xn(b,f)}else if(n.children.segmentList!==void 0){let{segmentList:b}=n.children;p=new wn(b,f)}else if(n.children.segmentTemplate!==void 0||e.parentSegmentTemplates.length>0){let b=e.parentSegmentTemplates.slice(),T=n.children.segmentTemplate;T!==void 0&&b.push(T);let v=Y({},...b);(v.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(f.availabilityTimeOffset=((h=v.availabilityTimeOffset)!=null?h:0)+((I=e.availabilityTimeOffset)!=null?I:0)),(v.availabilityTimeComplete!==void 0||e.availabilityTimeComplete!==void 0)&&(f.availabilityTimeComplete=(g=v.availabilityTimeComplete)!=null?g:e.availabilityTimeComplete),p=va.isTimelineIndexArgument(v)?new va(v,f):new On(v,f)}else{let b=e.adaptation.children;if(b.segmentBase!==void 0){let{segmentBase:T}=b;p=new xn(T,f)}else if(b.segmentList!==void 0){let{segmentList:T}=b;p=new wn(T,f)}else p=new On({duration:Number.MAX_VALUE,timescale:1,startNumber:0,media:""},f)}return p}function Vt(n,e){var i;if(e.length===0)return n;let t=e.map(o=>({url:o.value}));if(n.length===0)return t;let r=[];for(let o=0;o<n.length;o++){let a=n[o];for(let s=0;s<t.length;s++){let d=t[s],u=hn(a.url,d.url);r.push({url:u,serviceLocation:(i=d.serviceLocation)!=null?i:a.serviceLocation})}}return r}function Ay(n,e){let t=[];if(n.children.inbandEventStreams!==void 0&&t.push(...n.children.inbandEventStreams),e.children.inbandEventStreams!==void 0&&t.push(...e.children.inbandEventStreams),t.length!==0)return t}function My({adaptationProfiles:n,essentialProperties:e,supplementalProperties:t,manifestProfiles:r,codecs:i}){if(((n!=null?n:"")+(r!=null?r:"")).indexOf("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")!==-1&&(i==="hvc1.2.4.L153.B0"||i==="hev1.2.4.L153.B0"))return{colorDepth:10,eotf:"pq",colorSpace:"rec2020"};let a=Q([...e!=null?e:[],...t!=null?t:[]],s=>s.schemeIdUri==="urn:mpeg:mpegB:cicp:TransferCharacteristics");if(a!==void 0)switch(a.value){case"15":return;case"16":return{eotf:"pq"};case"18":return{eotf:"hlg"}}if(i!==void 0&&/^vp(08|09|10)/.test(i))return im(i)}function lu(n,e,t){var i,o,a,s,d,u,c;let r=[];for(let l of n){let f=l.attributes.id!==void 0?l.attributes.id:String(l.attributes.bitrate)+(l.attributes.height!==void 0?`-${l.attributes.height}`:"")+(l.attributes.width!==void 0?`-${l.attributes.width}`:"")+(l.attributes.mimeType!==void 0?`-${l.attributes.mimeType}`:"")+(l.attributes.codecs!==void 0?`-${l.attributes.codecs}`:"");for(;r.some(M=>M.id===f);)f+="-dup";let p=(o=(i=t.unsafelyBaseOnPreviousAdaptation)==null?void 0:i.getRepresentation(f))!=null?o:null,h=Ay(l,e),I=(a=l.attributes.availabilityTimeComplete)!=null?a:t.availabilityTimeComplete,g;(l.attributes.availabilityTimeOffset!==void 0||t.availabilityTimeOffset!==void 0)&&(g=((s=l.attributes.availabilityTimeOffset)!=null?s:0)+((d=t.availabilityTimeOffset)!=null?d:0));let b=Y({},t,{availabilityTimeOffset:g,availabilityTimeComplete:I,unsafelyBaseOnPreviousRepresentation:p,adaptation:e,inbandEventStreams:h}),T=uu(l,b),v;l.attributes.bitrate===void 0?(m.warn("dash","No usable bitrate found in the Representation."),v=0):v=l.attributes.bitrate;let _=Vt(t.baseURLs,l.children.baseURLs),R=_.length===0?[{baseUrl:"",id:void 0}]:_.map(M=>({baseUrl:M.url,id:M.serviceLocation})),k={bitrate:v,cdnMetadata:R,index:T,id:f};l.children.supplementalProperties!==void 0&&Q(l.children.supplementalProperties,M=>M.schemeIdUri==="tag:dolby.com,2018:dash:EC3_ExtensionType:2018"&&M.value==="JOC")!==void 0&&(k.isSpatialAudio=!0);let x;l.attributes.codecs!==void 0?x=l.attributes.codecs:e.attributes.codecs!==void 0&&(x=e.attributes.codecs),x!==void 0&&(x=x==="mp4a.40.02"?"mp4a.40.2":x,k.codecs=x);let P;l.attributes.supplementalCodecs!==void 0?P=l.attributes.supplementalCodecs:e.attributes.supplementalCodecs!==void 0&&(P=e.attributes.supplementalCodecs),P!==void 0&&(k.supplementalCodecs=rm(P)),l.attributes.frameRate!==void 0?k.frameRate=l.attributes.frameRate:e.attributes.frameRate!==void 0&&(k.frameRate=e.attributes.frameRate),l.attributes.height!==void 0?k.height=l.attributes.height:e.attributes.height!==void 0&&(k.height=e.attributes.height),l.attributes.mimeType!==void 0?k.mimeType=l.attributes.mimeType:e.attributes.mimeType!==void 0&&(k.mimeType=e.attributes.mimeType),l.attributes.width!==void 0?k.width=l.attributes.width:e.attributes.width!==void 0&&(k.width=e.attributes.width);{let M=[...(u=e.children.contentProtections)!=null?u:[],...(c=l.children.contentProtections)!=null?c:[]];for(let L of M)t.contentProtectionParser.add(k,L)}k.hdrInfo=My({adaptationProfiles:e.attributes.profiles,supplementalProperties:e.children.supplementalProperties,essentialProperties:e.children.essentialProperties,manifestProfiles:t.manifestProfiles,codecs:x}),r.push(k)}return r}function xy(n){if(n===void 0)return!1;let e=n.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&n.value==="1",t=n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="description";return e||t}function wy(n,e){return!!(n!==void 0&&n.some(r=>r.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&r.value==="2")||e!==void 0&&e.some(r=>r.schemeIdUri==="urn:mpeg:dash:role:2011"&&r.value==="caption"))}function Oy(n){return n===void 0?!1:n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="sign"}function Dy(n,e){if(w(n.attributes.id))return n.attributes.id;let{isClosedCaption:t,isForcedSubtitle:r,isAudioDescription:i,isSignInterpreted:o,isTrickModeTrack:a,type:s}=e,d=s;return w(n.attributes.language)&&(d+=`-${n.attributes.language}`),t===!0&&(d+="-cc"),r===!0&&(d+="-cc"),i===!0&&(d+="-ad"),o===!0&&(d+="-si"),a&&(d+="-trickMode"),w(n.attributes.contentType)&&(d+=`-${n.attributes.contentType}`),w(n.attributes.codecs)&&(d+=`-${n.attributes.codecs}`),w(n.attributes.mimeType)&&(d+=`-${n.attributes.mimeType}`),n.attributes.frameRate!==void 0&&(d+=`-${String(n.attributes.frameRate)}`),d}function Ly(n){if(!E(n.children.supplementalProperties)){let{supplementalProperties:e}=n.children;for(let t of e)if(t.schemeIdUri==="urn:mpeg:dash:adaptation-set-switching:2016"&&!E(t.value))return t.value.split(",").map(r=>r.trim()).filter(r=>w(r))}return[]}function cu(n,e){var d,u,c,l,f,p,h;let t={video:[],audio:[],text:[]},r=[],i=[],o={},a=[];for(let I=0;I<n.length;I++){let g=n[I],b=g.children,{essentialProperties:T,roles:v,label:_}=b,R=Array.isArray(v)&&v.some(he=>he.value==="main")&&v.some(he=>he.schemeIdUri==="urn:mpeg:dash:role:2011"),k=g.children.representations,x=(d=g.attributes.availabilityTimeComplete)!=null?d:e.availabilityTimeComplete,P;(g.attributes.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(P=((u=g.attributes.availabilityTimeOffset)!=null?u:0)+((c=e.availabilityTimeOffset)!=null?c:0));let M=du(g,k);if(M===void 0)continue;let L=(l=g.attributes.selectionPriority)!=null?l:1,F=g.attributes.id,D=Ly(g),B=[];e.segmentTemplate!==void 0&&B.push(e.segmentTemplate),g.children.segmentTemplate!==void 0&&B.push(g.children.segmentTemplate);let A={availabilityTimeComplete:x,availabilityTimeOffset:P,baseURLs:Vt(e.baseURLs,b.baseURLs),contentProtectionParser:e.contentProtectionParser,manifestBoundsCalculator:e.manifestBoundsCalculator,end:e.end,isDynamic:e.isDynamic,isLastPeriod:e.isLastPeriod,manifestProfiles:e.manifestProfiles,parentSegmentTemplates:B,receivedTime:e.receivedTime,start:e.start,unsafelyBaseOnPreviousAdaptation:null},C=Array.isArray(T)?Q(T,he=>he.schemeIdUri==="http://dashif.org/guidelines/trickmode"):void 0,N=(f=C==null?void 0:C.value)==null?void 0:f.split(" "),K=N!==void 0,{accessibilities:q}=b,X;v!==void 0&&v.some(he=>he.value==="dub")&&(X=!0);let W;M!=="text"?W=!1:W=wy(q,v);let H;M==="text"&&v!==void 0&&v.some(he=>he.value==="forced-subtitle"||he.value==="forced_subtitle")&&(H=!0);let G;M!=="audio"?G=!1:q!==void 0&&(G=q.some(xy));let ie;M!=="video"?ie=!1:q!==void 0&&(ie=q.some(Oy));let oe=Dy(g,{isAudioDescription:G,isForcedSubtitle:H,isClosedCaption:W,isSignInterpreted:ie,isTrickModeTrack:K,type:M});for(;$(a,oe);)oe+="-dup";let fe=oe;a.push(oe),A.unsafelyBaseOnPreviousAdaptation=(h=(p=e.unsafelyBaseOnPreviousPeriod)==null?void 0:p.getAdaptation(oe))!=null?h:null;let Re=lu(k,g,A);if(M==="thumbnails"){let he=Ny(g,Re);he!==null&&r.push(...he);continue}let ge={id:oe,representations:Re,type:M,isTrickModeTrack:K};if(E(g.attributes.language)||(ge.language=g.attributes.language),E(W)||(ge.closedCaption=W),E(G)||(ge.audioDescription=G),X===!0&&(ge.isDub=!0),H!==void 0&&(ge.forcedSubtitles=H),ie===!0&&(ge.isSignInterpreted=!0),_!==void 0&&(ge.label=_),N!==void 0)i.push({adaptation:ge,trickModeAttachedAdaptationIds:N});else{let he=-1;for(let _t of D){let ee=o[_t];if(ee!==void 0&&ee.newID!==fe&&$(ee.adaptationSetSwitchingIDs,F)){he=Ie(t[M],ot=>ot[0].id===_t);let ye=t[M][he];if(ye!==void 0&&ye[0].audioDescription===ge.audioDescription&&ye[0].closedCaption===ge.closedCaption&&ye[0].language===ge.language){m.info("dash",'merging "switchable" AdaptationSets',{originalID:F,id:_t}),ye[0].representations.push(...ge.representations),ye[1]={priority:Math.max(L,ye[1].priority),isMainAdaptation:R||ye[1].isMainAdaptation,indexInMpd:Math.min(I,ye[1].indexInMpd)};break}}}he<0&&t[M].push([ge,{priority:L,isMainAdaptation:R,indexInMpd:I}])}!E(F)&&E(o[F])&&(o[F]={newID:fe,adaptationSetSwitchingIDs:D})}let s=Jt.reduce((I,g)=>{let b=t[g];return b.length>0&&(b.sort(om),I[g]=b.map(([T])=>T)),I},{});return t.video.sort(om),nm(s,i),{adaptations:s,thumbnailTracks:r}}function Ny(n,e){var r,i;let t=[];for(let o=0;o<e.length;o++){let a=e[o];if(a!==void 0){if(a.mimeType===void 0){m.warn("dash","Invalid thumbnails Representation, no mime-type");continue}let s=su(n,n.children.representations[o]);if(s===null)continue;if(a.height===void 0){m.warn("dash","Invalid thumbnails Representation, no height information");continue}if(a.width===void 0){m.warn("dash","Invalid thumbnails Representation, no width information");continue}let d=(r=a.index.getFirstAvailablePosition())!=null?r:void 0,u=(i=a.index.getEnd())!=null?i:void 0,c,l=a.index.getTargetSegmentDuration();l!==void 0&&l.isPrecize?c=l.duration:m.warn("dash","Cannot produce duration estimate for thumbnail track"),t.push({id:a.id,cdnMetadata:a.cdnMetadata,index:a.index,mimeType:a.mimeType,height:a.height,width:a.width,horizontalTiles:s.horizontalTiles,verticalTiles:s.verticalTiles,start:d,end:u,tileDuration:c===void 0?void 0:c/(s.horizontalTiles*s.verticalTiles)})}}return t}function om(n,e){let t=e[1].priority-n[1].priority;return t!==0?t:n[1].isMainAdaptation!==e[1].isMainAdaptation?n[1].isMainAdaptation?-1:1:n[1].indexInMpd-e[1].indexInMpd}var Uy=rt();function fu(n,e){var a,s,d,u,c;let t=[],r=au(n,e);if(r.length!==n.length)throw new Error("MPD parsing error: the time information are incoherent.");let{isDynamic:i,manifestBoundsCalculator:o}=e;!i&&!E(e.duration)&&o.setLastPosition(e.duration);for(let l=n.length-1;l>=0;l--){let f=l===n.length-1,p=n[l],h=e.xlinkInfos.get(p),I=Vt(e.baseURLs,p.children.baseURLs),{periodStart:g,periodDuration:b,periodEnd:T}=r[l],v;for(E(p.attributes.id)?(v="gen-dash-period-"+Uy(),m.warn("dash","No usable id found in the Period. Generating one.",{periodId:v})):v=p.attributes.id;t.some(K=>K.id===v);)v+="-dup";let _=h!==void 0?h.receivedTime:e.receivedTime,R=(s=(a=e.unsafelyBaseOnPreviousManifest)==null?void 0:a.getPeriod(v))!=null?s:null,k=p.attributes.availabilityTimeComplete,x=p.attributes.availabilityTimeOffset,{manifestProfiles:P,contentProtectionParser:M}=e,{segmentTemplate:L}=p.children;M.addReferences((d=p.children.contentProtections)!=null?d:[]);let F={availabilityTimeComplete:k,availabilityTimeOffset:x,baseURLs:I,contentProtectionParser:M,manifestBoundsCalculator:o,end:T,isDynamic:i,isLastPeriod:f,manifestProfiles:P,receivedTime:_,segmentTemplate:L,start:g,unsafelyBaseOnPreviousPeriod:R},{adaptations:D,thumbnailTracks:B}=cu(p.children.adaptations,F),A=((u=e.xmlNamespaces)!=null?u:[]).concat((c=p.attributes.namespaces)!=null?c:[]),C=Fy(p.children.eventStreams,g,A),N={id:v,start:g,end:T,duration:b,thumbnailTracks:B,adaptations:D,streamEvents:C};if(t.unshift(N),!o.lastPositionIsKnown()){let K=By(D);if(!i)typeof K=="number"&&o.setLastPosition(K);else if(typeof K=="number"){let q=z()/1e3;o.setLastPosition(K,q)}else{let q=am(e,g);if(q!==void 0){let[X,W]=q;o.setLastPosition(X,W)}}}}if(e.isDynamic&&!o.lastPositionIsKnown()){let l=am(e,0);if(l!==void 0){let[f,p]=l;o.setLastPosition(f,p)}}return ou(t)}function am(n,e){if(E(n.clockOffset)){let t=Date.now()/1e3;if(t>=e){m.warn("dash","no clock synchronization mechanism found. Using the system clock instead.");let r=t-n.availabilityStartTime,i=z()/1e3;return[r,i]}}else{let t=n.clockOffset/1e3-n.availabilityStartTime,r=z()/1e3,i=r+t;if(i>=e)return[i,r]}}function By(n){let e=null,t=!0,r=zn(n).filter(o=>!E(o)),i=jn(r,o=>o);for(let o of i){let a=o.representations;for(let s of a){let d=s.index.getLastAvailablePosition();d!==null&&(t=!1,typeof d=="number"&&(e=E(e)?d:Math.max(e,d)))}}if(E(e)){if(t)return null}else return e}function Fy(n,e,t){var i,o;let r=[];for(let a of n){let{schemeIdUri:s="",timescale:d=1}=a.attributes,u=t.concat((i=a.attributes.namespaces)!=null?i:[]);for(let c of a.children.events)if(c.eventStreamData!==void 0){let l=((o=c.presentationTime)!=null?o:0)/d+e,f=c.duration===void 0?void 0:l+c.duration/d,p,h;try{h={namespaces:u,data:typeof c.eventStreamData=="string"?c.eventStreamData:ce(new Uint8Array(c.eventStreamData))}}catch(I){m.error("dash","Error while parsing event-stream:",I instanceof Error?I.message:"Unknown error")}r.push({start:l,end:f,id:c.id,data:{type:"dash-event-stream",value:{schemeIdUri:s,timescale:d,element:p,xmlData:h}}})}}return r}function sr(n,e,t,r,i=new WeakMap){let{children:o,attributes:a}=n;if(E(e.externalClockOffset)){let d=a.type==="dynamic",u=Q(o.utcTimings,f=>f.schemeIdUri==="urn:mpeg:dash:utc:direct:2014"&&!E(f.value)),c=!E(u)&&!E(u.value)?Ra(u.value):void 0,l=!E(c)&&!isNaN(c)?c:void 0;if(!E(l)&&r!==!0)e.externalClockOffset=l;else if(d&&r!==!0){let f=eu(n);if(!E(f)&&f.length>0)return{type:"needs-clock",value:{url:f,continue:function(h){return h.success?(e.externalClockOffset=Ra(h.data),sr(n,e,t,!0)):(t.push(h.error),m.warn("dash","Error on fetching the clock ressource",h.error),sr(n,e,t,!0))}}}}}let s=[];for(let d=0;d<o.periods.length;d++){let{xlinkHref:u,xlinkActuate:c}=o.periods[d].attributes;!E(u)&&c==="onLoad"&&s.push({index:d,ressource:u})}return s.length===0?Ky(n,e,t,i):{type:"needs-xlinks",value:{xlinksUrls:s.map(({ressource:d})=>d),continue:function(u){if(u.length!==s.length)throw new Error("DASH parser: wrong number of loaded ressources.");for(let c=u.length-1;c>=0;c--){let l=s[c].index,{parsed:f,warnings:p,receivedTime:h,sendingTime:I,url:g}=u[c];p.length>0&&t.push(...p);for(let b of f)i.set(b,{receivedTime:h,sendingTime:I,url:g});o.periods.splice(l,1,...f)}return sr(n,e,t,r,i)}}}}function Ky(n,e,t,r){var A,C,N,K,q;let{children:i,attributes:o}=n,a=o.type==="dynamic",s=e.url!==void 0?[{url:e.url.substring(0,wr(e.url))}]:[],d=Vt(s,i.baseURLs),u=iu(o,e.referenceDateTime),c=o.timeShiftBufferDepth,l=o.maxSegmentDuration,{externalClockOffset:f,unsafelyBaseOnPreviousManifest:p}=e,{externalClockOffset:h}=e,I=new Hi({availabilityStartTime:u,isDynamic:a,timeShiftBufferDepth:c,serverTimestampOffset:h}),g=new Wi;g.addReferences((A=i.contentProtections)!=null?A:[]);let b={availabilityStartTime:u,baseURLs:d,clockOffset:f,contentProtectionParser:g,duration:o.duration,isDynamic:a,manifestBoundsCalculator:I,manifestProfiles:n.attributes.profiles,receivedTime:e.manifestReceivedTime,unsafelyBaseOnPreviousManifest:p,xlinkInfos:r,xmlNamespaces:n.attributes.namespaces},T=fu(i.periods,b);g.finalize();let v=o.duration,_,R,k=null,x;o.minimumUpdatePeriod!==void 0&&o.minimumUpdatePeriod>=0&&(_=o.minimumUpdatePeriod===0?O.getCurrent().DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:o.minimumUpdatePeriod);let{minimumSafePosition:P,maximumSafePosition:M,maximumUnsafePosition:L}=ru(T),F=z();if(a){let X;M!==void 0?X=M:h===void 0?(m.warn("dash","use system clock to define maximum position"),X=Date.now()/1e3-u):X=(z()+h)/1e3-u;let W=I.getEstimatedLiveEdge();W===void 0&&(L!==void 0?W=L:W=X),x={isLinear:!0,maximumSafePosition:X,livePosition:W,time:F},R=P,k=c!=null?c:null,k!==null&&(k+=l!=null?l:0),k!==null&&R!==void 0&&W-R>k&&(k=W-R)}else{R=P,R===void 0&&(R=(N=(C=T[0])==null?void 0:C.start)!=null?N:0);let X=v!=null?v:1/0;if(T[T.length-1]!==void 0){let W=T[T.length-1],H=(K=W.end)!=null?K:W.duration!==void 0?W.start+W.duration:void 0;H!==void 0&&H<X&&(X=H)}M!==void 0&&M<X&&(X=M),x={isLinear:!1,maximumSafePosition:X,livePosition:void 0,time:F}}let D=!a||n.attributes.minimumUpdatePeriod===void 0&&(((q=T[T.length-1])==null?void 0:q.end)!==void 0||n.attributes.duration!==void 0);return{type:"done",value:{parsed:{availabilityStartTime:u,clockOffset:e.externalClockOffset,isDynamic:a,isLive:a,isLastPeriodKnown:D,periods:T,publishTime:o.publishTime,suggestedPresentationDelay:o.suggestedPresentationDelay,transportType:"dash",timeBounds:{minimumSafePosition:R,timeshiftDepth:k,maximumTimeData:x},lifetime:_,uris:E(e.url)?i.locations:[e.url,...i.locations]},warnings:t}}}var sm=sr;var Vy=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,zy=/([0-9]+)-([0-9]+)/;function Qe(n,e){return n==="true"?[!0,null]:n==="false"?[!1,null]:[!1,new it(`\`${e}\` property is not a boolean value but "${n}"`)]}function ve(n,e){let t=parseInt(n,10);return isNaN(t)?[null,new it(`\`${e}\` property is not an integer value but "${n}"`)]:[t,null]}function Je(n,e){if(n==="INF")return[1/0,null];let t=parseFloat(n);return isNaN(t)?[null,new it(`\`${e}\` property is invalid: "${n}"`)]:[t,null]}function mu(n,e){if(n==="true")return[!0,null];if(n==="false")return[!1,null];let t=parseInt(n,10);return isNaN(t)?[null,new it(`\`${e}\` property is not a boolean nor an integer but "${n}"`)]:[t,null]}function Ca(n,e){let t=Date.parse(n);return isNaN(t)?[null,new it(`\`${e}\` is in an invalid date format: "${n}"`)]:[new Date(Date.parse(n)).getTime()/1e3,null]}function Tt(n,e){if(!w(n))return[0,new it(`\`${e}\` property is empty`)];let t=Vy.exec(n);return t===null?[null,new it(`\`${e}\` property has an unrecognized format "${n}"`)]:[parseFloat(w(t[2])?t[2]:"0")*365*24*60*60+parseFloat(w(t[4])?t[4]:"0")*30*24*60*60+parseFloat(w(t[6])?t[6]:"0")*24*60*60+parseFloat(w(t[8])?t[8]:"0")*60*60+parseFloat(w(t[10])?t[10]:"0")*60+parseFloat(w(t[12])?t[12]:"0"),null]}function Dn(n,e){let t=zy.exec(n);return t===null?[null,new it(`\`${e}\` property has an unrecognized format "${n}"`)]:[[+t[1],+t[2]],null]}function dm(n,e){try{return[St(n),null]}catch(t){return[null,new it(`\`${e}\` is not a valid base64 string: "${n}"`)]}}function dr(n,e){let t=/^(\d+)\/(\d+)$/.exec(n);return t!==null?[+t[1]/+t[2],null]:Je(n,e)}function Ke(n){let e,t;for(let r of Object.keys(n.attributes)){let i=n.attributes[r];if(!E(i))switch(r){case"schemeIdUri":e=i;break;case"value":t=i;break}}return{schemeIdUri:e,value:t}}function Ve(n,e){return function(t,{asKey:r,parser:i,dashName:o}){let[a,s]=i(t,o);s!==null&&(m.warn("dash","failed to parse DASH value:",s.message,{dashName:o}),e.push(s)),a!==null&&(n[r]=a)}}var it=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="MPDError"}};function sn(n){return Sa(n)}function zt(n){let e=typeof n=="string"?n:sn(n.children),t=[];return e===null||e.length===0?[void 0,t]:[{value:e},t]}function Wy(n){let e=[],t=[];for(let r=0;r<n.length;r++){let i=n[r];if(typeof i!="string"&&i.tagName==="cenc:pssh"){let o=sn(i.children);if(o!==null&&o.length>0){let[a,s]=dm(o,"cenc:pssh");s!==null&&(m.warn("dash","Content protection parsing failure",s.message),e.push(s)),a!==null&&t.push(a)}}}return[{cencPssh:t},e]}function Hy(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!E(r))switch(t){case"schemeIdUri":e.schemeIdUri=r;break;case"value":e.value=r;break;case"cenc:default_KID":e.keyId=Xe(r.replace(/-/g,""));break;case"ref":e.ref=r;break;case"refId":e.refId=r;break}}return e}function Wt(n){let[e,t]=Wy(n.children),r=Hy(n);return[{children:e,attributes:r},t]}function pu(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!E(r))switch(t){case"id":e.id=r;break;case"lang":e.language=r;break;case"contentType":e.contentType=r;break;case"par":e.par=r;break}}return e}function gu(n){let e={},t=[],r=Ve(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!E(o))switch(i){case"range":r(o,{asKey:"range",parser:Dn,dashName:"range"});break;case"sourceURL":e.media=o;break}}return[e,t]}function Ht(n){let e={},t=[],r=Ve(e,t),i=n.children;for(let o=0;o<i.length;o++){let a=i[o];if(typeof a!="string"&&a.tagName==="Initialization"){let[s,d]=gu(a);e.initialization=s,t=t.concat(d)}}for(let o of Object.keys(n.attributes)){let a=n.attributes[o];if(!E(a))switch(o){case"timescale":r(a,{asKey:"timescale",parser:ve,dashName:"timescale"});break;case"presentationTimeOffset":r(a,{asKey:"presentationTimeOffset",parser:Je,dashName:"presentationTimeOffset"});break;case"indexRange":r(a,{asKey:"indexRange",parser:Dn,dashName:"indexRange"});break;case"indexRangeExact":r(a,{asKey:"indexRangeExact",parser:Qe,dashName:"indexRangeExact"});break;case"availabilityTimeOffset":r(a,{asKey:"availabilityTimeOffset",parser:Je,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(a,{asKey:"availabilityTimeComplete",parser:Qe,dashName:"availabilityTimeComplete"});break;case"duration":r(a,{asKey:"duration",parser:ve,dashName:"duration"});break;case"startNumber":r(a,{asKey:"startNumber",parser:ve,dashName:"startNumber"});break;case"endNumber":r(a,{asKey:"endNumber",parser:ve,dashName:"endNumber"});break}}return[e,t]}function hu(n){let e={},t=[],r=Ve(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!E(o))switch(i){case"media":e.media=o;break;case"indexRange":r(o,{asKey:"indexRange",parser:Dn,dashName:"indexRange"});break;case"index":e.index=o;break;case"mediaRange":r(o,{asKey:"mediaRange",parser:Dn,dashName:"mediaRange"});break}}return[e,t]}function qi(n){let[e,t]=Ht(n),r=t,i=[],o=n.children;for(let s=0;s<o.length;s++){let d=o[s];if(typeof d!="string"&&d.tagName==="SegmentURL"){let[u,c]=hu(d);i.push(u),r=r.concat(c)}}return[Y(e,{list:i}),r]}function yu(n){let e=n.children;return function(){for(let t=e.length-1;t>=0;t--){let r=e[t];(typeof r=="string"||r.tagName!=="S")&&e.splice(t,1)}return e}}function Ln(n){let[e,t]=Ht(n),r=t,i;for(let s=0;s<n.children.length;s++){let d=n.children[s];typeof d!="string"&&d.tagName==="SegmentTimeline"&&(i=yu(d))}let o=Y({},e,{duration:e.duration,timelineParser:i}),a=Ve(o,r);for(let s of Object.keys(n.attributes)){let d=n.attributes[s];if(!E(d))switch(s){case"initialization":E(o.initialization)&&(o.initialization={media:d});break;case"index":o.index=d;break;case"availabilityTimeOffset":a(d,{asKey:"availabilityTimeOffset",parser:Je,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":a(d,{asKey:"availabilityTimeComplete",parser:Qe,dashName:"availabilityTimeComplete"});break;case"media":o.media=d;break;case"bitstreamSwitching":a(d,{asKey:"bitstreamSwitching",parser:Qe,dashName:"bitstreamSwitching"});break}}return[o,r]}function qy(n){let e={baseURLs:[]},t=[],r=[];for(let i=0;i<n.length;i++){let o=n[i];if(typeof o!="string")switch(o.tagName){case"BaseURL":{let[a,s]=zt(o);a!==void 0&&e.baseURLs.push(a),r=r.concat(s);break}case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(Ke(o));break;case"SegmentBase":{let[a,s]=Ht(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=qi(o);r=r.concat(s),e.segmentList=a;break}case"SegmentTemplate":{let[a,s]=Ln(o);r=r.concat(s),e.segmentTemplate=a;break}case"ContentProtection":{let[a,s]=Wt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}case"EssentialProperty":E(e.essentialProperties)?e.essentialProperties=[Ke(o)]:e.essentialProperties.push(Ke(o));break;case"SupplementalProperty":E(e.supplementalProperties)?e.supplementalProperties=[Ke(o)]:e.supplementalProperties.push(Ke(o));break}}return t.length>0&&(e.contentProtections=t),[e,r]}function Gy(n){let e={},t=[],r=Ve(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!E(o))switch(i){case"audioSamplingRate":e.audioSamplingRate=o;break;case"bandwidth":r(o,{asKey:"bitrate",parser:ve,dashName:"bandwidth"});break;case"codecs":e.codecs=o;break;case"codingDependency":r(o,{asKey:"codingDependency",parser:Qe,dashName:"codingDependency"});break;case"frameRate":r(o,{asKey:"frameRate",parser:dr,dashName:"frameRate"});break;case"height":r(o,{asKey:"height",parser:ve,dashName:"height"});break;case"id":e.id=o;break;case"maxPlayoutRate":r(o,{asKey:"maxPlayoutRate",parser:Je,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o,{asKey:"maximumSAPPeriod",parser:Je,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o;break;case"profiles":e.profiles=o;break;case"qualityRanking":r(o,{asKey:"qualityRanking",parser:ve,dashName:"qualityRanking"});break;case"scte214:supplementalCodecs":e.supplementalCodecs=o;break;case"segmentProfiles":e.segmentProfiles=o;break;case"width":r(o,{asKey:"width",parser:ve,dashName:"width"});break;case"availabilityTimeOffset":r(o,{asKey:"availabilityTimeOffset",parser:Je,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o,{asKey:"availabilityTimeComplete",parser:Qe,dashName:"availabilityTimeComplete"});break}}return e.bitrate===void 0&&t.push(new it("No bitrate found on a Representation")),[e,t]}function um(n){let[e,t]=qy(n.children),[r,i]=Gy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function jy(n){let e={baseURLs:[],representations:[]},t=[],r=[];for(let i=0;i<n.length;i++){let o=n[i];if(typeof o!="string")switch(o.tagName){case"Accessibility":e.accessibilities===void 0?e.accessibilities=[Ke(o)]:e.accessibilities.push(Ke(o));break;case"BaseURL":{let[a,s]=zt(o);a!==void 0&&e.baseURLs.push(a),s.length>0&&(r=r.concat(s));break}case"ContentComponent":e.contentComponent=pu(o);break;case"EssentialProperty":E(e.essentialProperties)?e.essentialProperties=[Ke(o)]:e.essentialProperties.push(Ke(o));break;case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(Ke(o));break;case"Label":{let a=sn(o.children);a!=null&&(e.label=a);break}case"Representation":{let[a,s]=um(o);e.representations.push(a),s.length>0&&(r=r.concat(s));break}case"Role":E(e.roles)?e.roles=[Ke(o)]:e.roles.push(Ke(o));break;case"SupplementalProperty":E(e.supplementalProperties)?e.supplementalProperties=[Ke(o)]:e.supplementalProperties.push(Ke(o));break;case"SegmentBase":{let[a,s]=Ht(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=qi(o);e.segmentList=a,s.length>0&&(r=r.concat(s));break}case"SegmentTemplate":{let[a,s]=Ln(o);e.segmentTemplate=a,s.length>0&&(r=r.concat(s));break}case"ContentProtection":{let[a,s]=Wt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}}}return t.length>0&&(e.contentProtections=t),[e,r]}function Yy(n){let e={},t=[],r=Ve(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!E(o))switch(i){case"id":e.id=o;break;case"group":r(o,{asKey:"group",parser:ve,dashName:"group"});break;case"lang":e.language=o;break;case"contentType":e.contentType=o;break;case"par":e.par=o;break;case"minBandwidth":r(o,{asKey:"minBitrate",parser:ve,dashName:"minBandwidth"});break;case"maxBandwidth":r(o,{asKey:"maxBitrate",parser:ve,dashName:"maxBandwidth"});break;case"minWidth":r(o,{asKey:"minWidth",parser:ve,dashName:"minWidth"});break;case"maxWidth":r(o,{asKey:"maxWidth",parser:ve,dashName:"maxWidth"});break;case"minHeight":r(o,{asKey:"minHeight",parser:ve,dashName:"minHeight"});break;case"maxHeight":r(o,{asKey:"maxHeight",parser:ve,dashName:"maxHeight"});break;case"minFrameRate":r(o,{asKey:"minFrameRate",parser:dr,dashName:"minFrameRate"});break;case"maxFrameRate":r(o,{asKey:"maxFrameRate",parser:dr,dashName:"maxFrameRate"});break;case"selectionPriority":r(o,{asKey:"selectionPriority",parser:ve,dashName:"selectionPriority"});break;case"segmentAlignment":r(o,{asKey:"segmentAlignment",parser:mu,dashName:"segmentAlignment"});break;case"subsegmentAlignment":r(o,{asKey:"subsegmentAlignment",parser:mu,dashName:"subsegmentAlignment"});break;case"bitstreamSwitching":r(o,{asKey:"bitstreamSwitching",parser:Qe,dashName:"bitstreamSwitching"});break;case"audioSamplingRate":e.audioSamplingRate=o;break;case"codecs":e.codecs=o;break;case"scte214:supplementalCodecs":e.supplementalCodecs=o;break;case"codingDependency":r(o,{asKey:"codingDependency",parser:Qe,dashName:"codingDependency"});break;case"frameRate":r(o,{asKey:"frameRate",parser:dr,dashName:"frameRate"});break;case"height":r(o,{asKey:"height",parser:ve,dashName:"height"});break;case"maxPlayoutRate":r(o,{asKey:"maxPlayoutRate",parser:Je,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o,{asKey:"maximumSAPPeriod",parser:Je,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o;break;case"profiles":e.profiles=o;break;case"segmentProfiles":e.segmentProfiles=o;break;case"width":r(o,{asKey:"width",parser:ve,dashName:"width"});break;case"availabilityTimeOffset":r(o,{asKey:"availabilityTimeOffset",parser:Je,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o,{asKey:"availabilityTimeComplete",parser:Qe,dashName:"availabilityTimeComplete"});break}}return[e,t]}function lm(n){let e=n.children,[t,r]=jy(e),[i,o]=Yy(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Qy(n){let e={},t=[],r=Ve(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!E(o))switch(i){case"schemeIdUri":e.schemeIdUri=o;break;case"value":e.value=o;break;case"timescale":r(o,{asKey:"timescale",parser:ve,dashName:"timescale"});break;default:Ce(i,"xmlns:")&&(e.namespaces===void 0&&(e.namespaces=[]),e.namespaces.push({key:i.substring(6),value:o}));break}}return[e,t]}function cm(n,e){let[t,r]=Qy(n),i=[];for(let o of n.children)if(typeof o!="string"&&o.tagName==="Event"){let a={};if(E(o.attributes.id)||(a.id=o.attributes.id),!E(o.attributes.presentationTime)){let[s,d]=ve(o.attributes.presentationTime,"presentationTime");d!==null&&r.push(d),s!==null&&(a.presentationTime=s)}if(!E(o.attributes.duration)){let[s,d]=ve(o.attributes.duration,"duration");d!==null&&r.push(d),s!==null&&(a.duration=s)}if(o.posStart<o.posEnd){let s=e.substring(o.posStart,o.posEnd);a.eventStreamData=s}i.push(a)}return[{children:{events:i},attributes:t},r]}function $y(n,e){let t=[],r=[],i,o=[],a=[],s=[];for(let d=0;d<n.length;d++){let u=n[d];if(typeof u!="string")switch(u.tagName){case"BaseURL":{let[c,l]=zt(u);c!==void 0&&t.push(c),a=a.concat(l);break}case"AdaptationSet":{let[c,l]=lm(u);r.push(c),a=a.concat(l);break}case"EventStream":{let[c,l]=cm(u,e);s.push(c),a=a.concat(l);break}case"SegmentTemplate":{let[c,l]=Ln(u);i=c,l.length>0&&(a=a.concat(l));break}case"ContentProtection":{let[c,l]=Wt(u);l.length>0&&(a=a.concat(l)),c!==void 0&&o.push(c);break}}}return[{baseURLs:t,adaptations:r,eventStreams:s,segmentTemplate:i,contentProtections:o},a]}function Xy(n){let e={},t=[],r=Ve(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!E(o))switch(i){case"id":e.id=o;break;case"start":r(o,{asKey:"start",parser:Tt,dashName:"start"});break;case"duration":r(o,{asKey:"duration",parser:Tt,dashName:"duration"});break;case"bitstreamSwitching":r(o,{asKey:"bitstreamSwitching",parser:Qe,dashName:"bitstreamSwitching"});break;case"xlink:href":e.xlinkHref=o;break;case"xlink:actuate":e.xlinkActuate=o;break;default:Ce(i,"xmlns:")&&(e.namespaces===void 0&&(e.namespaces=[]),e.namespaces.push({key:i.substring(6),value:o}));break}}return[e,t]}function Aa(n,e){let[t,r]=$y(n.children,e),[i,o]=Xy(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Zy(n,e){let t=[],r=[],i=[],o=[],a=[],s=[];for(let d=0;d<n.length;d++){let u=n[d];if(typeof u!="string")switch(u.tagName){case"BaseURL":{let[c,l]=zt(u);c!==void 0&&t.push(c),s=s.concat(l);break}case"Location":r.push(sn(u.children));break;case"Period":{let[c,l]=Aa(u,e);i.push(c),s=s.concat(l);break}case"UTCTiming":{let c=Ke(u);o.push(c);break}case"ContentProtection":{let[c,l]=Wt(u);l.length>0&&(s=s.concat(l)),c!==void 0&&a.push(c);break}}}return[{baseURLs:t,locations:r,periods:i,utcTimings:o,contentProtections:a},s]}function Jy(n){let e={},t=[],r=Ve(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!E(o))switch(i){case"id":e.id=o;break;case"profiles":e.profiles=o;break;case"type":e.type=o;break;case"availabilityStartTime":r(o,{asKey:"availabilityStartTime",parser:Ca,dashName:"availabilityStartTime"});break;case"availabilityEndTime":r(o,{asKey:"availabilityEndTime",parser:Ca,dashName:"availabilityEndTime"});break;case"publishTime":r(o,{asKey:"publishTime",parser:Ca,dashName:"publishTime"});break;case"mediaPresentationDuration":r(o,{asKey:"duration",parser:Tt,dashName:"mediaPresentationDuration"});break;case"minimumUpdatePeriod":r(o,{asKey:"minimumUpdatePeriod",parser:Tt,dashName:"minimumUpdatePeriod"});break;case"minBufferTime":r(o,{asKey:"minBufferTime",parser:Tt,dashName:"minBufferTime"});break;case"timeShiftBufferDepth":r(o,{asKey:"timeShiftBufferDepth",parser:Tt,dashName:"timeShiftBufferDepth"});break;case"suggestedPresentationDelay":r(o,{asKey:"suggestedPresentationDelay",parser:Tt,dashName:"suggestedPresentationDelay"});break;case"maxSegmentDuration":r(o,{asKey:"maxSegmentDuration",parser:Tt,dashName:"maxSegmentDuration"});break;case"maxSubsegmentDuration":r(o,{asKey:"maxSubsegmentDuration",parser:Tt,dashName:"maxSubsegmentDuration"});break;default:Ce(i,"xmlns:")&&(e.namespaces===void 0&&(e.namespaces=[]),e.namespaces.push({key:i.substring(6),value:o}));break}}return[e,t]}function fm(n,e){let[t,r]=Zy(n.children,e),[i,o]=Jy(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Iu(n,e){let t=jd(n),r=t[t.length-1];if(r===void 0||typeof r=="string"||r.tagName!=="MPD")throw new Error("DASH Parser: document root should be MPD");let[i,o]=fm(r,n),a=sm(i,e,o);return s(a);function s(d){if(d.type==="done")return d;if(d.type==="needs-clock")return{type:"needs-resources",value:{urls:[d.value.url],format:"string",continue(u){if(u.length!==1)throw new Error("DASH parser: wrong number of loaded ressources.");let c=d.value.continue(u[0].responseData);return s(c)}}};if(d.type==="needs-xlinks")return{type:"needs-resources",value:{urls:d.value.xlinksUrls,format:"string",continue(u){let c=[];for(let f=0;f<u.length;f++){let{responseData:p,receivedTime:h,sendingTime:I,url:g}=u[f];if(!p.success)throw p.error;let b="<root>"+p.data+"</root>",T=jd(b),v=T[T.length-1];if(v===void 0||typeof v=="string")throw new Error("DASH parser: Invalid external ressources");let _=v.children,R=[],k=[];for(let x=0;x<_.length;x++){let P=_[x];if(typeof P=="string"||P.tagName!=="Period")continue;let[M,L]=Aa(P,b);k.push(...L),R.push(M)}c.push({url:g,receivedTime:h,sendingTime:I,parsed:R,warnings:k})}let l=d.value.continue(c);return s(l)}}};ze(d)}}var mm=Iu;function je(n,e){if(e.length===0)return n;let t,r="",i=n.indexOf("#"),o=n;i>=0&&(r=n.substring(i),o=n.substring(0,i));let a=o.indexOf("?");a===-1?t="?":a+1===o.length?t="":t="&";let s=o+t;for(let d=0;d<e.length;d++){let u=e[d];u[1]===null?s+=u[0]:s+=`${u[0]}=${u[1]}`,d<e.length-1&&(s+="&")}return r.length>0&&(s+=r),s}function bu(n,e){return(t,r,i)=>new Promise((o,a)=>{let s=Date.now()-z(),d=!1,f={reject:I=>{var v,_;if(d||i.isCancelled())return;d=!0,i.deregister(h);let g=I,b=(v=g==null?void 0:g.message)!=null?v:"Unknown error when fetching the Manifest through a custom manifestLoader.",T=new dt(b,(_=g==null?void 0:g.canRetry)!=null?_:!1,g==null?void 0:g.xhr);a(T)},resolve:I=>{if(d||i.isCancelled())return;d=!0,i.deregister(h);let g=I.receivingTime!==void 0?I.receivingTime-s:void 0,b=I.sendingTime!==void 0?I.sendingTime-s:void 0;o({responseData:I.data,size:I.size,requestDuration:I.duration,url:I.url,receivedTime:g,sendingTime:b})},fallback:()=>{d||i.isCancelled()||(d=!0,i.deregister(h),e(t,r,i).then(o,a))}},p=n({url:t,timeout:r.timeout,cmcdPayload:r.cmcdPayload},f);i.register(h);function h(I){d||(d=!0,typeof p=="function"&&p(),a(I))}})}function eI(n){return function(t,r,i){var s,d;if(t===void 0)throw new Error("Cannot perform HTTP(s) request. URL not known");let o=((s=r.cmcdPayload)==null?void 0:s.type)==="query"?je(t,r.cmcdPayload.value):t,a=((d=r.cmcdPayload)==null?void 0:d.type)==="headers"?r.cmcdPayload.value:void 0;switch(n){case"arraybuffer":return ke({url:o,headers:a,responseType:"arraybuffer",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"text":return ke({url:o,headers:a,responseType:"text",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"document":return ke({url:o,headers:a,responseType:"document",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});default:ze(n)}}}function Gi({customManifestLoader:n},e,t){let r=eI(e),i=typeof n!="function"?r:bu(n,r);return t!==null?t(i):i}function dn(n,e){if(e){if(At(n,1718909296)<0)throw new We("INTEGRITY_ERROR","Incomplete `ftyp` box");if(At(n,1836019574)<0)throw new We("INTEGRITY_ERROR","Incomplete `moov` box")}else{if(At(n,1836019558)<0)throw new We("INTEGRITY_ERROR","Incomplete `moof` box");if(At(n,1835295092)<0)throw new We("INTEGRITY_ERROR","Incomplete `mdat` box")}}function Et(n,e){if(n==="audio"||n==="video")return e==="video/mp4"||e==="audio/mp4"?"mp4":e==="video/webm"||e==="audio/webm"?"webm":void 0;if(n==="text")return e==="application/mp4"?"mp4":void 0}function Ma(n){return(e,t,r,i,o)=>{return new Promise((s,d)=>{let u=new U,c=u.linkToSignal(i);u.signal.register(d),n(e,t,r,u.signal,ue(ae({},o),{onNewChunk(f){try{a(f),o.onNewChunk(f)}catch(p){l(),u.cancel(),d(p)}}})).then(f=>{if(l(),!u.isUsed()){if(f.resultType==="segment-loaded")try{a(f.resultData.responseData)}catch(p){d(p);return}s(f)}},f=>{l(),d(f)});function l(){u.signal.deregister(d),c()}});function a(s){!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)||Et(t.type,t.mimeType)!=="mp4"||dn(new Uint8Array(s),t.segment.isInit)}}}function pm(n){return async(e,t,r)=>{let i=await n(e,t,r);return o(i.responseData),i;function o(a){if(typeof a=="string"){let s=a.length-1,d=["</","MPD",">"];for(let u=d.length-1;u>=0;u--){let c=d[u];for(;tI(a[s]);)s--;for(let l=c.length-1;l>=0;l--){if(a[s]!==c[l])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(a instanceof ArrayBuffer){let s=a.byteLength-1,d=new DataView(a),u=[[60,47],[77,80,68],[62]];for(let c=u.length-1;c>=0;c--){let l=u[c];for(;nI(d.getUint8(s));)s--;for(let f=l.length-1;f>=0;f--){if(d.getUint8(s)!==l[f])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(!E(Z.Document)&&a instanceof Z.Document&&a.documentElement.nodeName!=="MPD")throw new We("INTEGRITY_ERROR","MPD does not end with </MPD>")}}}function tI(n){return n===" "||n===" "||n==="\r"||n===`
|
|
10
|
-
`}function nI(n){return n===32||n===9||n===13||n===10}function Su(n){let{referenceDateTime:e}=n,t=n.serverSyncInfos!==void 0?n.serverSyncInfos.serverTimestamp-n.serverSyncInfos.clientTime:void 0;return function(i,o,a,s,d){var T;let{responseData:u}=i,c=o.externalClockOffset,l=(T=i.url)!=null?T:o.originalUrl,f=t!=null?t:c,h={unsafelyBaseOnPreviousManifest:o.unsafeMode?o.previousManifest:null,url:l,referenceDateTime:e,externalClockOffset:f},I=pe.dashParsers;if(I.wasm===null||I.wasm.status==="uninitialized"||I.wasm.status==="failure")return m.debug("dash","WASM MPD Parser not initialized. Running JS one."),g();{let v=aI(u);if(!sI(v))return m.info("dash","MPD doesn't seem to be UTF-8-encoded. Running JS parser instead of the WASM one."),g();if(I.wasm.status==="initialized"){m.debug("dash","Running WASM MPD Parser.");let _=I.wasm.runWasmParser(v,h);return b(_)}else return m.debug("dash","Awaiting WASM initialization before parsing the MPD."),I.wasm.waitForInitialization().catch(()=>{}).then(()=>{if(I.wasm===null||I.wasm.status!=="initialized")return m.warn("dash","WASM MPD parser initialization failed. Running JS parser instead"),g();m.debug("dash","Running WASM MPD Parser.");let R=I.wasm.runWasmParser(v,h);return b(R)})}function g(){if(I.js!==null){let v=oI(u),_=I.js(v,h);return b(_)}else throw new Error("No MPD parser is imported")}function b(v){if(v.type==="done")return v.value.warnings.length>0&&a(v.value.warnings),s.isCancelled()?Promise.reject(s.cancellationError):{manifest:new Jn(v.value.parsed,n),url:l};let{value:_}=v,R=_.urls.map(k=>d(()=>{let x=O.getCurrent().DEFAULT_REQUEST_TIMEOUT,P=O.getCurrent().DEFAULT_CONNECTION_TIMEOUT;return _.format==="string"?ke({url:k,responseType:"text",timeout:x,connectionTimeout:P,cancelSignal:s}):ke({url:k,responseType:"arraybuffer",timeout:x,connectionTimeout:P,cancelSignal:s})}).then(x=>{if(_.format==="string"){if(typeof x.responseData!="string")throw new Error("External DASH resources should have been a string");return Y(x,{responseData:{success:!0,data:x.responseData}})}else{if(!(x.responseData instanceof ArrayBuffer))throw new Error("External DASH resources should have been ArrayBuffers");return Y(x,{responseData:{success:!0,data:x.responseData}})}},x=>{let P=Me(x,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"An unknown error occured when parsing ressources."});return Y({},{size:void 0,requestDuration:void 0,responseData:{success:!1,error:P}})}));return Promise.all(R).then(k=>_.format==="string"?(rI(k),b(_.continue(k))):(iI(k),b(_.continue(k))))}}}function rI(n){y.CURRENT_ENV!==y.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&typeof t.data=="string")&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function iI(n){y.CURRENT_ENV!==y.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&t.data instanceof ArrayBuffer)&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function oI(n){if(n instanceof ArrayBuffer)return ce(new Uint8Array(n));if(typeof n=="string")return n;if(!E(Z.Document)&&n instanceof Z.Document)return n.documentElement.outerHTML;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function aI(n){if(n instanceof ArrayBuffer)return n;if(typeof n=="string")return Te(n).buffer;if(!E(Z.Document)&&n instanceof Z.Document)return Te(n.documentElement.innerHTML).buffer;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function sI(n){let e=new DataView(n);return e.getUint16(0)===61371&&e.getUint8(2)===191?!0:!(e.getUint16(0)===65279||e.getUint16(0)===65534)}function et([n,e]){return e===1/0?`bytes=${n}-`:`bytes=${n}-${e}`}function Nn(n,e){return n===null?null:e.url===null?n.baseUrl:hn(n.baseUrl,e.url)}function ji(n,e,t,r,i){var u,c;let o=n;((u=t.cmcdPayload)==null?void 0:u.type)==="query"&&(o=je(o,t.cmcdPayload.value));let a=((c=t.cmcdPayload)==null?void 0:c.type)==="headers"?t.cmcdPayload.value:void 0;if(e.range===void 0)return ke({url:o,responseType:"arraybuffer",headers:a,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.indexRange===void 0)return ke({url:o,headers:ue(ae({},a),{Range:et(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.range[1]+1===e.indexRange[0])return ke({url:o,headers:ue(ae({},a),{Range:et([e.range[0],e.indexRange[1]])}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));let s=ke({url:o,headers:ue(ae({},a),{Range:et(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}),d=ke({url:o,headers:ue(ae({},a),{Range:et(e.indexRange)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress});return Promise.all([s,d]).then(([l,f])=>{let p=de(new Uint8Array(l.responseData),new Uint8Array(f.responseData)),h=Math.min(l.sendingTime,f.sendingTime),I=Math.max(l.receivedTime,f.receivedTime);return{resultType:"segment-loaded",resultData:{url:o,responseData:p,size:l.size+f.size,requestDuration:I-h,sendingTime:h,receivedTime:I}}})}async function Yi(n,e,t,r){let i=null;function o(s){let d=new Uint8Array(s.chunk),u=i!==null?de(i,d):d,c=na(u),l=c[0];i=c[1],!(l!==null&&(l.forEach(f=>{t.onNewChunk(f)}),r.isCancelled()))&&(t.onProgress({duration:s.duration,size:s.size,totalSize:s.totalSize}),r.isCancelled())}return{resultType:"chunk-complete",resultData:await Oo({url:n,headers:e.headers,onData:o,timeout:e.timeout,connectionTimeout:e.connectionTimeout,cancelSignal:r})}}async function gm(n,e,t,r,i,o){var f,p;if(e.segment.isInit)return ji(n,e.segment,r,o,i);let a=((f=r.cmcdPayload)==null?void 0:f.type)==="query"?je(n,r.cmcdPayload.value):n,s=((p=r.cmcdPayload)==null?void 0:p.type)==="headers"?r.cmcdPayload.value:void 0,{segment:d}=e,u;d.range!==void 0?u=ue(ae({},s),{Range:et(d.range)}):s!==void 0&&(u=s);let c=Et(e.type,e.mimeType);if(t&&(c==="mp4"||c===void 0)){if(Dr())return Yi(a,{headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout},i,o);Ft("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}return{resultType:"segment-loaded",resultData:await ke({url:a,responseType:"arraybuffer",headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:o,onProgress:i.onProgress})}}function Tu({lowLatencyMode:n,segmentLoader:e,checkMediaSegmentIntegrity:t}){return t!==!0?r:Ma(r);function r(i,o,a,s,d){let u=Nn(i,o.segment);return u===null?Promise.resolve({resultType:"segment-created",resultData:null}):n||e===void 0?gm(u,o,n,a,d,s):new Promise((c,l)=>{let f=!1,b={reject:k=>{var L,F;if(f||s.isCancelled())return;f=!0,s.deregister(R);let x=k,P=(L=x==null?void 0:x.message)!=null?L:"Unknown error when fetching a DASH segment through a custom segmentLoader.",M=new dt(P,(F=x==null?void 0:x.canRetry)!=null?F:!1,x==null?void 0:x.xhr);l(M)},resolve:k=>{if(f||s.isCancelled())return;f=!0,s.deregister(R);let x;k.data instanceof Uint8Array?k.data.buffer instanceof ArrayBuffer?x=k.data:x=k.data.slice():x=k.data,c({resultType:"segment-loaded",resultData:{responseData:x,size:k.size,requestDuration:k.duration}})},progress:k=>{f||s.isCancelled()||d.onProgress({duration:k.duration,size:k.size,totalSize:k.totalSize})},fallback:()=>{f||s.isCancelled()||(f=!0,s.deregister(R),gm(u,o,n,a,d,s).then(c,l))}},T;o.segment.range!==void 0&&(T=[o.segment.range],o.segment.indexRange!==void 0&&T.push(o.segment.indexRange));let v={isInit:o.segment.isInit,timeout:a.timeout,byteRanges:T,trackType:o.type,url:u,cmcdPayload:a.cmcdPayload},_=e(v,b);s.register(R);function R(k){f||(f=!0,typeof _=="function"&&_(),l(k))}})}}var _u=408125543,hm=357149030,dI=2807729,uI=17545,lI=475249515,cI=187,fI=179,mI=183,pI=241;function un(n,e,t,[r,i]){let o=r;for(;o<i;){let a=hI(t,o);if(a===null)return null;let{value:s,length:d}=a,u=o+d,c=yI(t,u);if(c===null)return null;let{length:l,value:f}=c,p=u+l,h=p+f;if(s===n)return[p,h];if(e.length>0){for(let I=0;I<e.length;I++)if(s===e[I]){let g=e.slice(I+1,e.length);return un(n,g,t,[p,h])}}o=h}return null}function xa(n,e){let t=un(dI,[_u,hm],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return 1e9/Eu(n,t[0],r)}function gI(n,e){let t=un(uI,[_u,hm],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return r===4?II(n,t[0]):r===8?bI(n,t[0]):null}function vu(n,e){let t=un(_u,[],n,[e,n.length]);if(t===null)return null;let[r,i]=t,o=xa(n,r);if(o===null)return null;let a=gI(n,r);if(a===null)return null;let s=un(lI,[],n,[r,i]);if(s===null)return null;let d=[],u=s[0];for(;u<s[1];){let l=un(cI,[],n,[u,s[1]]);if(l===null)break;let f=un(fI,[],n,[l[0],l[1]]);if(f===null)return null;let p=Eu(n,f[0],f[1]-f[0]),h=un(pI,[mI],n,[l[0],l[1]]);if(h===null)return null;let I=Eu(n,h[0],h[1]-h[0])+r;d.push({time:p,rangeStart:I}),u=l[1]}let c=[];for(let l=0;l<d.length;l++){let f=d[l];l===d.length-1?c.push({time:f.time,timescale:o,duration:l===0?a:a-f.time,range:[f.rangeStart,1/0]}):c.push({time:f.time,timescale:o,duration:d[l+1].time-f.time,range:[f.rangeStart,d[l+1].rangeStart-1]})}return c}function ym(n,e){for(let t=1;t<=8;t++)if(n[e]>=Math.pow(2,8-t))return t}function hI(n,e){let t=ym(n,e);if(t===void 0)return m.warn("webm","unrepresentable length"),null;if(e+t>n.length)return m.warn("webm","impossible length",{offset:e,length:t,bufferLength:n.length}),null;let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function yI(n,e){let t=ym(n,e);if(t===void 0)return m.warn("webm","unrepresentable length"),null;if(e+t>n.length)return m.warn("webm","impossible length",{offset:e,length:t,bufferLength:n.length}),null;let r=(n[e]&(1<<8-t)-1)*Math.pow(2,(t-1)*8);for(let i=1;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function II(n,e){return new DataView(n.buffer).getFloat32(e)}function bI(n,e){return new DataView(n.buffer).getFloat64(e)}function Eu(n,e,t){let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return r}function Qi(n,e,t,r){let i=Gr(n);if(i===void 0||r===void 0)return null;let o=t.timestampOffset!==void 0?i+t.timestampOffset*r:i,a=jr(n);if(o<0&&(a!==void 0&&(a+=o),o=0),e||!t.complete)return a===void 0&&m.warn("dash","Chunked segments should indicate a duration through their trun boxes"),{time:o/r,duration:a!==void 0?a/r:void 0};let s,d=t.duration*r,u=Math.min(r*.9,d/4);return a!==void 0&&Math.abs(a-d)<=u&&(s=a),{time:o/r,duration:s!==void 0?s/r:s}}function SI(n,e){if(n.length<=0)return!1;let t=n.length;for(let r=0;r<t;r++){let i=n[r],o=e,{messageData:a}=i,s=ce(a),d=Date.parse(s);if(o===void 0||d===void 0||isNaN(d)||d>=o)return!0}return!1}function Ru(n,e){if(n.length===0)return;let{manifestRefreshEventsFromEMSGs:t,EMSGs:r}=n.reduce((a,s)=>(s.schemeIdUri==="urn:mpeg:dash:event:2012"&&s.value==="1"?(a.manifestRefreshEventsFromEMSGs===void 0&&(a.manifestRefreshEventsFromEMSGs=[]),a.manifestRefreshEventsFromEMSGs.push(s)):(a.EMSGs===void 0&&(a.EMSGs=[]),a.EMSGs.push(s)),a),{manifestRefreshEventsFromEMSGs:void 0,EMSGs:void 0}),i=r==null?void 0:r.map(a=>({type:"emsg",value:a})),o=e===void 0||t===void 0?!1:SI(t,e);return{inbandEvents:i,needsManifestRefresh:o}}function ku({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var v,_;let{segment:o,periodStart:a,periodEnd:s}=r,{data:d,isChunked:u}=t,c=[a,s];if(d===null)return o.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:0,protectionData:[],appendWindow:c};let l=Bt(d),f=Et(r.type,r.mimeType),p=f==="mp4"||f===void 0,h=[];if(p){let R=ra(l),k;o.isInit&&(k=(v=af(l))!=null?v:void 0),(R.length>0||k!==void 0)&&h.push({initDataType:"cenc",keyId:k,initData:R})}if(!o.isInit){let R=p?Qi(l,u,o,i):null,k=(_=o.timestampOffset)!=null?_:0;if(p){let x=of(l);if(x!==void 0){let P=x.filter(L=>o.privateInfos===void 0||o.privateInfos.isEMSGWhitelisted===void 0?!1:o.privateInfos.isEMSGWhitelisted(L)),M=Ru(P,r.manifestPublishTime);if(M!==void 0){let{needsManifestRefresh:L,inbandEvents:F}=M;return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:R,chunkOffset:k,appendWindow:c,inbandEvents:F,protectionData:h,needsManifestRefresh:L}}}}return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:R,chunkOffset:k,protectionData:h,appendWindow:c}}let{indexRange:I}=o,g;if(f==="webm")g=vu(l,0);else if(p&&(g=qr(l,Array.isArray(I)?I[0]:0),n===!0&&g!==null&&g.length>0)){let R=g[g.length-1];Array.isArray(R.range)&&(R.range[1]=1/0)}let b;p?b=Yr(l):f==="webm"&&(b=xa(l,0));let T=E(b)?void 0:b;return{segmentType:"init",initializationData:l,initializationDataSize:l.length,protectionData:h,initTimescale:T,segmentList:g!=null?g:void 0}}}function Pu({lowLatencyMode:n,checkMediaSegmentIntegrity:e}){return e!==!0?t:Ma(t);async function t(r,i,o,a,s){var g,b;let{segment:d}=i,u=Nn(r,d);if(u===null)return Promise.resolve({resultType:"segment-created",resultData:null});if(d.isInit)return ji(u,d,o,a,s);let c=((g=o.cmcdPayload)==null?void 0:g.type)==="query"?je(u,o.cmcdPayload.value):u,l=((b=o.cmcdPayload)==null?void 0:b.type)==="headers"?o.cmcdPayload.value:void 0,f;d.range!==void 0?f=ue(ae({},l),{Range:et(d.range)}):l!==void 0&&(f=l);let p=Et(i.type,i.mimeType),h=p==="mp4"||p===void 0;if(n&&h){if(Dr())return Yi(c,{headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout},s,a);Ft("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}let I;return h?I=await ke({url:c,responseType:"arraybuffer",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}):I=await ke({url:c,responseType:"text",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}),{resultType:"segment-loaded",resultData:I}}}function TI(n){if(n===void 0)throw new Error("Cannot parse subtitles: unknown format");switch(n.toLowerCase()){case"stpp":case"stpp.ttml":case"stpp.ttml.im1t":return"ttml";case"wvtt":return"vtt"}throw new Error(`The codec used for the subtitles "${n}" is not managed yet.`)}function EI(n,e){switch(e){case"application/ttml+xml":return"ttml";case"application/x-sami":case"application/smil":return"sami";case"text/vtt":return"vtt"}if(n!==void 0&&n.toLowerCase()==="srt")return"srt";throw new Error(`could not find a text-track parser for the type ${e!=null?e:""}`)}function Im({segment:n,language:e,codecs:t},r,i,o,a){if(n.isInit)return null;let s,d;o===null?a?(s=n.time,d=n.end):m.warn("utils","Unavailable time data for current text track."):(s=o.time,o.duration!==void 0?d=s+o.duration:!a&&n.complete&&(d=s+n.duration));let u=TI(t),c=Rn(r),l=c!==null?ce(c):"";return t==="wvtt"&&!Ce(l,"WEBVTT")&&!Ce(l,"\xFE\xFFWEBVTT")?{data:r,type:"mp4vtt",language:e,start:s,end:d,initTimescale:i!=null?i:null}:{data:l,type:u,language:e,start:s,end:d,initTimescale:i!=null?i:null}}function bm(n,e,t,r){let{segment:i}=n;if(i.isInit)return null;let o,a;r?m.warn("utils","Unavailable time data for current text track."):(o=i.time,i.complete&&(a=i.time+i.duration));let s=EI(n.codecs,n.mimeType);return{data:e,type:s,language:n.language,start:o,end:a,initTimescale:t!=null?t:null}}function _I(n,e,t,r,i){var f;let{segment:o}=t,{isInit:a,indexRange:s}=o,d;if(typeof n=="string"?d=Te(n):n instanceof Uint8Array?d=n:d=new Uint8Array(n),a){let p=qr(d,Array.isArray(s)?s[0]:0);if(i===!0&&p!==null&&p.length>0){let I=p[p.length-1];Array.isArray(I.range)&&(I.range[1]=1/0)}let h=Yr(d);return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:h,segmentList:p!=null?p:void 0}}let u=Qi(d,e,o,r),c=Im(t,d,r,u,e),l=(f=o.timestampOffset)!=null?f:0;return{segmentType:"media",chunkData:c,chunkSize:d.length,chunkInfos:u,chunkOffset:l,protectionData:[],appendWindow:[t.periodStart,t.periodEnd]}}function vI(n,e,t,r){let{periodStart:i,periodEnd:o,segment:a}=r,{timestampOffset:s=0}=a;if(a.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};let d,u;if(typeof n!="string"){let l=n instanceof Uint8Array?n:new Uint8Array(n);d=ce(l),u=l.length}else d=n;return{segmentType:"media",chunkData:bm(r,d,e,t),chunkSize:u,chunkInfos:null,chunkOffset:s,protectionData:[],appendWindow:[i,o]}}function Cu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var l;let{periodStart:o,periodEnd:a,segment:s}=r,{data:d,isChunked:u}=t;if(d===null)return s.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:(l=s.timestampOffset)!=null?l:0,protectionData:[],appendWindow:[o,a]};let c=Et(r.type,r.mimeType);if(c==="webm")throw new Error("Text tracks with a WEBM container are not yet handled.");return c==="mp4"?_I(d,u,r,i,n):vI(d,i,u,r)}}async function Sm(n,e,t,r){var d,u;let i=Nn(n,e);if(i===null)return Promise.reject(new Error("Cannot load thumbnail: no URL"));let o=((d=t.cmcdPayload)==null?void 0:d.type)==="query"?je(i,t.cmcdPayload.value):i,a=((u=t.cmcdPayload)==null?void 0:u.type)==="headers"?t.cmcdPayload.value:void 0,s;return e.range!==void 0?s=ue(ae({},a),{Range:et(e.range)}):a!==void 0&&(s=a),Lr({url:o,responseType:"arraybuffer",headers:s,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r})}function Tm(n,e){var u;let{thumbnailTrack:t,thumbnail:r}=e,i=t.height/t.verticalTiles,o=t.width/t.horizontalTiles,a=[],s=(u=t.tileDuration)!=null?u:(r.end-r.time)/(t.horizontalTiles*t.verticalTiles),d=r.time;for(let c=0;c<t.verticalTiles;c++)for(let l=0;l<t.horizontalTiles;l++)a.push({start:d,end:d+s,offsetX:Math.round(l*o),offsetY:Math.round(c*i),height:Math.floor(i),width:Math.floor(o)}),d+=s;return{mimeType:t.mimeType,data:n,thumbnails:a}}function Em(n){let e=Gi({customManifestLoader:n.manifestLoader},RI()?"text":"arraybuffer",n.checkManifestIntegrity===!0?pm:null),t=Su(n),r=Tu(n),i=ku(n),o=Pu(n),a=Cu(n);return{transportName:"dash",manifest:{loadManifest:e,parseManifest:t},audio:{loadSegment:r,parseSegment:i},video:{loadSegment:r,parseSegment:i},text:{loadSegment:o,parseSegment:a},thumbnails:{loadThumbnail:Sm,parseThumbnail:Tm}}}function RI(){return pe.dashParsers.wasm!==null&&(pe.dashParsers.wasm.status==="initialized"||pe.dashParsers.wasm.status==="initializing")}var _m=Em;function Au(n){n.transports.dash===void 0&&(n.transports.dash=_m),n.dashParsers.js=mm,n.mainThreadMediaSourceInit=Mn}var kI=typeof MediaSource=="function"&&MediaSource.canConstructInDedicatedWorker===!0,vm=kI;var $i=class extends rr{constructor(e){super(),this._settings=e,this._initCanceller=new U}prepare(){}start(e,t){let r=this._initCanceller.signal,{keySystems:i,speed:o,url:a}=this._settings;ir(e),PI(e,this._settings.autoPlay,r);let{statusRef:s}=wi(e,i,{onError:u=>this._onFatalError(u),onWarning:u=>this.trigger("warning",u),onBlackListProtectionData:te,onKeyIdsCompatibilityUpdate:te},r);Ni(e,u=>this._onFatalError(u),r);let d=new An(t,null,o);d.addEventListener("stalled",u=>this.trigger("stalled",u)),d.addEventListener("unstalled",()=>this.trigger("unstalled",null)),d.addEventListener("warning",u=>this.trigger("warning",u)),r.register(()=>{d.destroy()}),d.start(),s.onUpdate((u,c)=>{u.initializationState.type!=="uninitialized"&&(c(),m.info("Init","Setting URL to HTMLMediaElement",{url:a}),e.src=a,r.register(()=>{m.info("Init","Removing directfile src from media element",{src:e.src}),ir(e)}),u.initializationState.type==="awaiting-media-link"?(u.initializationState.value.isMediaLinked.setValue(!0),s.onUpdate((l,f)=>{l.initializationState.type==="initialized"&&(f(),this._seekAndPlay(e,t))},{emitCurrentValue:!0,clearSignal:r})):(ne(u.initializationState.type==="initialized"),this._seekAndPlay(e,t)))},{emitCurrentValue:!0,clearSignal:r})}updateContentUrls(e,t){throw new Error("Cannot update content URL of directfile contents")}dispose(){this._initCanceller.cancel()}_onFatalError(e){this._initCanceller.cancel(),this.trigger("error",e)}_seekAndPlay(e,t){let r=this._initCanceller.signal,{autoPlay:i,startAt:o}=this._settings;xi({mediaElement:e,playbackObserver:t,startTime:()=>{m.debug("Init","Calculating initial time");let s=CI(e,o);return m.debug("Init","Initial time calculated",{initialTime:s}),s},mustAutoPlay:i,onWarning:s=>this.trigger("warning",s),isDirectfile:!0},r).autoPlayResult.then(()=>Mi(t,!0,r).onUpdate((s,d)=>{s&&(d(),this.trigger("loaded",{getSegmentSinkMetrics:null,getThumbnailData:()=>Promise.reject(new Error("Thumbnail data not available with directfile contents"))}))},{emitCurrentValue:!0,clearSignal:r})).catch(s=>{r.isCancelled()||this._onFatalError(s)})}};function PI(n,e,t){if(!e)return;let r=n.autoplay;n.autoplay=e,t.register(()=>{n.autoplay=r})}function CI(n,e){if(E(e))return 0;if(E(e.position))if(E(e.wallClockTime)){if(!E(e.fromFirstPosition))return e.fromFirstPosition}else return e.wallClockTime;else return e.position;let t=n.duration;if(typeof e.fromLastPosition=="number"){if(!E(t)&&isFinite(t))return Math.max(0,t+e.fromLastPosition);if(n.seekable.length>0){let r=n.seekable.end(n.seekable.length-1);if(isFinite(r))return Math.max(0,r+e.fromLastPosition)}m.warn("Init","startAt.fromLastPosition set but duration is not known, it may be too soon to seek");return}else if(typeof e.fromLivePosition=="number"){let r=n.seekable.length>0?n.seekable.end(0):t;return E(r)?(m.warn("Init","startAt.fromLivePosition set but live position is not known, beginning at 0."),0):Math.max(0,r+e.fromLivePosition)}else if(!E(e.percentage)){if(E(t)||!isFinite(t))return m.warn("Init","startAt.percentage set but duration is not known, beginning at 0."),0;let{percentage:r}=e;if(r>=100)return t;if(r<=0)return 0;let i=+r/100;return t*i}return 0}function Mu(n,e){for(let t=0;t<n.length;t++)(V.device!==V.DEVICES.Tizen||t!==e)&&(n[t].enabled=!1);return e<0||e>=n.length?!1:(n[e].enabled=!0,!0)}function ur(n,e){var t;if(e.length!==n.length)return!0;for(let r=0;r<e.length;r++)if(e[r].nativeTrack!==((t=n[r])==null?void 0:t.nativeTrack))return!0;return!1}function xu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_audio_"+a+"_"+s.toString();t[a]=s+1;let u={language:o.language,id:d,normalized:Nr(o.language),audioDescription:o.kind==="descriptions"||o.kind==="description",representations:[]};e.push({track:u,nativeTrack:o})}return e}function wu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_text_"+a+"_"+s.toString();t[a]=s+1;let u=o.kind==="forced"?!0:void 0,c={language:o.language,forced:u,label:o.label,id:d,normalized:Nr(o.language),closedCaption:o.kind==="captions"};e.push({track:c,nativeTrack:o})}return e}function Ou(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_video_"+a+"_"+s.toString();t[a]=s+1,e.push({track:{id:d,representations:[]},nativeTrack:o})}return e}var Xi=class extends se{constructor(e){var t,r,i;super(),this._nativeAudioTracks=e.audioTracks,this._nativeVideoTracks=e.videoTracks,this._nativeTextTracks=e.textTracks,this._audioTracks=this._nativeAudioTracks!==void 0?xu(this._nativeAudioTracks):[],this._videoTracks=this._nativeVideoTracks!==void 0?Ou(this._nativeVideoTracks):[],this._textTracks=this._nativeTextTracks!==void 0?wu(this._nativeTextTracks):[],this._lastEmittedNativeAudioTrack=(t=this._getCurrentAudioTrack())==null?void 0:t.nativeTrack,this._lastEmittedNativeVideoTrack=(r=this._getCurrentVideoTrack())==null?void 0:r.nativeTrack,this._lastEmittedNativeTextTrack=(i=this._getCurrentTextTrack())==null?void 0:i.nativeTrack,this._handleNativeTracksCallbacks()}setAudioTrackById(e){for(let t=0;t<this._audioTracks.length;t++){let{track:r,nativeTrack:i}=this._audioTracks[t];if(r.id===e){this._enableAudioTrackFromIndex(t),this._audioTrackLockedOn=i;return}}throw new Error("Audio track not found.")}disableTextTrack(){Rm(this._textTracks),this._textTrackLockedOn=null}setTextTrackById(e){let t=!1;for(let r=0;r<this._textTracks.length;r++){let{track:i,nativeTrack:o}=this._textTracks[r];i.id===e?(o.mode="showing",t=!0,this._textTrackLockedOn=o):(o.mode==="showing"||o.mode==="hidden")&&(o.mode="disabled")}if(!t)throw new Error("Text track not found.")}disableVideoTrack(){km(this._videoTracks),this._videoTrackLockedOn=null}disableAudioTrack(){MI(this._audioTracks),this._audioTrackLockedOn=null}setVideoTrackById(e){for(let t=0;t<this._videoTracks.length;t++){let{track:r,nativeTrack:i}=this._videoTracks[t];if(r.id===e){i.selected=!0,this._videoTrackLockedOn=i;return}}throw new Error("Video track not found.")}getChosenAudioTrack(){let e=this._getCurrentAudioTrack();return E(e)?e:e.track}getChosenTextTrack(){let e=this._getCurrentTextTrack();return E(e)?e:e.track}getChosenVideoTrack(){let e=this._getCurrentVideoTrack();return E(e)?e:e.track}getAvailableAudioTracks(){return this._audioTracks.map(({track:e,nativeTrack:t})=>({id:e.id,language:e.language,normalized:e.normalized,audioDescription:e.audioDescription,active:t.enabled,representations:e.representations}))}getAvailableTextTracks(){return this._textTracks.map(({track:e,nativeTrack:t})=>({id:e.id,label:e.label,forced:e.forced,language:e.language,normalized:e.normalized,closedCaption:e.closedCaption,active:t.mode==="showing"}))}getAvailableVideoTracks(){return this._videoTracks.map(({track:e,nativeTrack:t})=>({id:e.id,representations:e.representations,active:t.selected}))}dispose(){this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onchange=null,this._nativeVideoTracks.onaddtrack=null,this._nativeVideoTracks.onremovetrack=null),this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onchange=null,this._nativeAudioTracks.onaddtrack=null,this._nativeAudioTracks.onremovetrack=null),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onchange=null,this._nativeTextTracks.onaddtrack=null,this._nativeTextTracks.onremovetrack=null),this.removeEventListener()}_getCurrentAudioTrack(){if(this._nativeAudioTracks!==void 0){for(let e=0;e<this._audioTracks.length;e++){let t=this._audioTracks[e];if(t.nativeTrack.enabled)return t}return null}}_getCurrentVideoTrack(){if(this._nativeVideoTracks!==void 0){for(let e=0;e<this._videoTracks.length;e++){let t=this._videoTracks[e];if(t.nativeTrack.selected)return t}return null}}_getCurrentTextTrack(){if(this._nativeTextTracks!==void 0){for(let e=0;e<this._textTracks.length;e++){let t=this._textTracks[e];if(t.nativeTrack.mode==="showing")return t}return null}}_setPreviouslyLockedAudioTrack(){if(this._audioTrackLockedOn!==void 0)if(this._audioTrackLockedOn===null)for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];t.enabled=!1}else for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];if(t===this._audioTrackLockedOn){this._enableAudioTrackFromIndex(e);return}}}_setPreviouslyLockedTextTrack(){if(this._textTrackLockedOn!==void 0)if(this._textTrackLockedOn===null){Rm(this._textTracks);return}else for(let e=0;e<this._textTracks.length;e++){let{nativeTrack:t}=this._textTracks[e];if(t===this._textTrackLockedOn){AI(this._textTracks,t),t.mode!=="showing"&&(t.mode="showing");return}}}_setPreviouslyLockedVideoTrack(){if(this._videoTrackLockedOn!==void 0)if(this._videoTrackLockedOn===null){km(this._videoTracks);return}else for(let e=0;e<this._videoTracks.length;e++){let{nativeTrack:t}=this._videoTracks[e];if(t===this._videoTrackLockedOn){t.selected=!0;return}}}_handleNativeTracksCallbacks(){this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onaddtrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=xu(this._nativeAudioTracks);if(ur(this._audioTracks,r)){this._audioTracks=r,this._setPreviouslyLockedAudioTrack(),this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onremovetrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=xu(this._nativeAudioTracks);if(ur(this._audioTracks,r)){this._audioTracks=r,this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onchange=()=>{if(this._audioTracks!==void 0)for(let e=0;e<this._audioTracks.length;e++){let{track:t,nativeTrack:r}=this._audioTracks[e];if(r.enabled){r!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",t),this._lastEmittedNativeAudioTrack=r);return}}this._lastEmittedNativeAudioTrack!==null&&(this.trigger("audioTrackChange",null),this._lastEmittedNativeAudioTrack=null)}),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onaddtrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=wu(this._nativeTextTracks);if(ur(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onremovetrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=wu(this._nativeTextTracks);if(ur(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onchange=()=>{if(this._textTracks!==void 0)for(let e=0;e<this._textTracks.length;e++){let{track:t,nativeTrack:r}=this._textTracks[e];if(r.mode==="showing"){r!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",t),this._lastEmittedNativeTextTrack=r);return}}this._lastEmittedNativeTextTrack!==null&&(this.trigger("textTrackChange",null),this._lastEmittedNativeTextTrack=null)}),this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onaddtrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=Ou(this._nativeVideoTracks);if(ur(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onremovetrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=Ou(this._nativeVideoTracks);if(ur(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onchange=()=>{if(this._videoTracks!==void 0)for(let e=0;e<this._videoTracks.length;e++){let{track:t,nativeTrack:r}=this._videoTracks[e];if(r.selected){r!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",t),this._lastEmittedNativeVideoTrack=r);return}}this._lastEmittedNativeVideoTrack!==null&&(this.trigger("videoTrackChange",null),this._lastEmittedNativeVideoTrack=null)})}_enableAudioTrackFromIndex(e){Mu(this._audioTracks.map(({nativeTrack:t})=>t),e)}};function Rm(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.mode="disabled"}}function AI(n,e){for(let t=0;t<n.length;t++){let{nativeTrack:r}=n[t];r!==e&&(r.mode==="showing"||r.mode==="hidden")&&(r.mode="disabled")}}function km(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.selected=!1}}function MI(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.enabled=!1}}function Du(n){n.directfile={initDirectFile:$i,mediaElementTracksStore:Xi}}function Lu(n){n.decrypt=If}var Pm=Z.ResizeObserver;function Nu(n,e,t){let{height:r,width:i}=n.getBoundingClientRect(),o=new j({height:r,width:i},t),a=r,s=i;if(Pm!==void 0){let d=new Pm(u=>{if(u.length===0){m.error("utils","Resized but no observed element.");return}let c=u[0],{height:l,width:f}=c.contentRect;(l!==a||f!==s)&&(a=l,s=f,o.setValue({height:l,width:f}))});d.observe(n),t.register(()=>{d.disconnect()})}else{let d=setInterval(()=>{let{height:u,width:c}=n.getBoundingClientRect();(u!==a||c!==s)&&(a=u,s=c,o.setValue({height:u,width:c}))},e);t.register(()=>{clearInterval(d)})}return o}var Un=class{constructor(){this._ranges=[],this.length=0}insert(e,t){ne(e>=0),ne(t-e>0),vt(this._ranges,{start:e,end:t}),this.length=this._ranges.length}remove(e,t){ne(e>=0),ne(t-e>0);let r=[];e>0&&r.push({start:0,end:e}),t<1/0&&r.push({start:t,end:1/0}),this._ranges=hc(this._ranges,r),this.length=this._ranges.length}start(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].start}end(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].end}};function Uu(n,e,t,r){m.debug("text","Finding parser for html text tracks:",{type:n});let i=pe.htmlTextTracksParsers[n];if(typeof i!="function")throw new Error("no parser found for the given text track");m.debug("text","Parser found, parsing...",{type:n});let o=i(e,t,r);return m.debug("text","Parsed successfully!",{length:o.length}),o}function qt(n,e,t=.2){return Math.abs(n-e)<=Math.min(t,.2)}var xI=.05;function Cm(n,e){let t=n.end-n.start,r=e.end-e.start,i=Math.abs(n.start-e.start),o=Math.min(t,r,.2);return i/o<=xI}function Zi(n,e){for(let t=n.length-1;t>=0;t--)if(n[t].start<e)return n.slice(0,t+1);return[]}function lr(n,e){for(let t=0;t<n.length;t++)if(n[t].end>e)return n.slice(t,n.length);return[]}function Bu(n,e,t){let r=Math.max(n.start,e),i=Zi(n.cues,e),o={start:n.start,end:r,cues:i},a=Math.min(t,n.end),s=lr(n.cues,t),d={start:a,end:n.end,cues:s};return[o,d]}var Am=.001,wI=5,Ji=class{constructor(){this._cuesBuffer=[]}isEmpty(){return this._cuesBuffer.length===0}get(e){let t=this._cuesBuffer,r=[];for(let i=t.length-1;i>=0;i--){let o=t[i];if(e<o.end&&e>=o.start){let a=o.cues;for(let s of a)e>=s.start&&e<s.end&&r.push(s.element);if(r.length===0&&a.length>0)for(let s of a)(qt(e,s.start,Am)||qt(e,s.end,Am))&&r.push(s.element);return r}}return[]}remove(e,t){ne(e>=0),ne(t>=0),ne(t>e);let r=Math.max(e,t),i=this._cuesBuffer;for(let o=0;o<i.length;o++)if(i[o].end>e){let a=i[o];if(a.start>=r)return;if(a.end>=r){if(e<=a.start)a.cues=lr(a.cues,r),a.start=r;else{let[s,d]=Bu(a,e,r);this._cuesBuffer[o]=s,i.splice(o+1,0,d)}return}a.start>=e?(i.splice(o,1),o--):(a.cues=Zi(a.cues,e),a.end=Math.max(e,a.start))}}insert(e,t,r){let i=this._cuesBuffer,o={start:t,end:r,cues:e},a=Math.abs(t-r)/wI;function s(d){let u=i[d];u===void 0||qt(o.end,u.end,a)?i[d]=o:(u.start>=o.end||(u.cues=lr(u.cues,o.end),u.start=o.end),i.splice(d,0,o))}for(let d=0;d<i.length;d++){let u=i[d];if(t<u.end){if(Cm(o,u)){if(qt(r,u.end,a)){i[d]=o;return}else if(r<u.end){u.cues=lr(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}else if(t<u.start){if(r<u.start){i.splice(d,0,o);return}else if(qt(r,u.start,a)){u.start=r,i.splice(d,0,o);return}else if(qt(r,u.end,a)){i.splice(d,1,o);return}else if(r<u.end){u.cues=lr(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}if(qt(u.end,r,a)){u.cues=Zi(u.cues,t),u.end=t,i.splice(d+1,0,o);return}else if(u.end>r){let[c,l]=Bu(u,t,r);this._cuesBuffer[d]=c,i.splice(d+1,0,o),i.splice(d+2,0,l);return}else{u.cues=Zi(u.cues,t),u.end=t;let c=d+1;for(u=i[c];u!==void 0&&r>u.end;)i.splice(c,1),u=i[c];s(c);return}}}if(i.length>0){let d=i[i.length-1];qt(d.end,t,a)&&(d.end=t)}i.push(o)}};function Fu(n,e,t,r){let i=[e/t.columns,n/t.rows],o=r.getElementsByClassName("proportional-style");for(let a=0;a<o.length;a++){let s=o[a];if(s instanceof HTMLElement){let d=s.getAttribute("data-proportional-font-size");d!==null&&!isNaN(+d)&&(s.style.fontSize=String(+d*i[1])+"px");let u=s.getAttribute("data-proportional-width");u!==null&&!isNaN(+u)&&(s.style.width=String(+u*i[0])+"px");let c=s.getAttribute("data-proportional-height");c!==null&&!isNaN(+c)&&(s.style.height=String(+c*i[1])+"px");let l=s.getAttribute("data-proportional-line-height");l!==null&&!isNaN(+l)&&(s.style.lineHeight=String(+l*i[1])+"px");let f=s.getAttribute("data-proportional-left");f!==null&&!isNaN(+f)&&(s.style.left=String(+f*i[0])+"px");let p=s.getAttribute("data-proportional-top");p!==null&&!isNaN(+p)&&(s.style.top=String(+p*i[1])+"px");let h=s.getAttribute("data-proportional-padding-top");h!==null&&!isNaN(+h)&&(s.style.paddingTop=String(+h*i[1])+"px");let I=s.getAttribute("data-proportional-padding-bottom");I!==null&&!isNaN(+I)&&(s.style.paddingBottom=String(+I*i[1])+"px");let g=s.getAttribute("data-proportional-padding-left");g!==null&&!isNaN(+g)&&(s.style.paddingLeft=String(+g*i[0])+"px");let b=s.getAttribute("data-proportional-padding-right");b!==null&&!isNaN(+b)&&(s.style.paddingRight=String(+b*i[0])+"px")}}return o.length>0}function Mm(n,e){try{n.removeChild(e)}catch(t){m.warn("text","Can't remove text track: not in the element.")}}function OI(n){let e=n.getAttribute("data-resolution-rows"),t=n.getAttribute("data-resolution-columns");if(e===null||t===null)return null;let r=parseInt(e,10),i=parseInt(t,10);return r===null||i===null?null:{rows:r,columns:i}}var eo=class{constructor(e,t){m.debug("text","Creating HTMLTextDisplayer"),this._buffered=new Un,this._videoElement=e,this._textTrackElement=t,this._sizeUpdateCanceller=new U,this._subtitlesIntervalCanceller=new U,this._buffer=new Ji,this._currentCues=[],this._isAutoRefreshing=!1}pushTextData(e){var g,b;m.debug("text","Appending new html text tracks");let{timestampOffset:t,appendWindow:r,chunk:i}=e;if(i===null)return Le(this._buffered);let{start:o,end:a,data:s,type:d,language:u,initTimescale:c}=i,l=(g=r[0])!=null?g:0,f=(b=r[1])!=null?b:1/0,p=Uu(d,s,{initTimescale:c,language:u},t);if(l!==0&&f!==1/0){let T=0;for(;T<p.length&&p[T].end<=l;)T++;for(p.splice(0,T),T=0;T<p.length&&p[T].start<l;)p[T].start=l,T++;for(T=p.length-1;T>=0&&p[T].start>=f;)T--;for(p.splice(T+1,p.length),T=p.length-1;T>=0&&p[T].end>f;)p[T].end=f,T--}let h;if(o!==void 0)h=Math.max(l,o);else{if(p.length<=0)return m.warn("text","Current text tracks have no cues nor start time. Aborting"),Le(this._buffered);m.warn("text","No start time given. Guessing from cues."),h=p[0].start}let I;if(a!==void 0)I=Math.min(f,a);else{if(p.length<=0)return m.warn("text","Current text tracks have no cues nor end time. Aborting"),Le(this._buffered);m.warn("text","No end time given. Guessing from cues."),I=p[p.length-1].end}return I<=h?(m.warn("text","Invalid text track appended: ","the start time is inferior or equal to the end time."),Le(this._buffered)):(this._buffer.insert(p,h,I),this._buffered.insert(h,I),!this._isAutoRefreshing&&!this._buffer.isEmpty()&&this.autoRefreshSubtitles(this._subtitlesIntervalCanceller.signal),Le(this._buffered))}removeBuffer(e,t){return m.debug("text","Removing html text track data",{start:e,end:t}),this._buffer.remove(e,t),this._buffered.remove(e,t),this._isAutoRefreshing&&this._buffer.isEmpty()&&(this.refreshSubtitles(),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel(),this._subtitlesIntervalCanceller=new U),Le(this._buffered)}getBufferedRanges(){return Le(this._buffered)}reset(){m.debug("text","Resetting HTMLTextDisplayer"),this.stop(),this._subtitlesIntervalCanceller=new U}stop(){this._subtitlesIntervalCanceller.isUsed()||(m.debug("text","Stopping HTMLTextDisplayer"),this._disableCurrentCues(),this._buffer.remove(0,1/0),this._buffered.remove(0,1/0),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel())}_disableCurrentCues(){if(this._sizeUpdateCanceller.cancel(),this._currentCues.length>0){for(let e of this._currentCues)Mm(this._textTrackElement,e.element);this._currentCues=[]}}_displayCues(e){if(this._currentCues.length===e.length&&this._currentCues.every((i,o)=>i.element===e[o]))return;this._sizeUpdateCanceller.cancel();for(let i of this._currentCues)Mm(this._textTrackElement,i.element);this._currentCues=[];for(let i of e){let o=OI(i);this._currentCues.push({element:i,resolution:o}),this._textTrackElement.appendChild(i)}let r=this._currentCues.filter(i=>i.resolution!==null);if(r.length>0){this._sizeUpdateCanceller=new U,this._sizeUpdateCanceller.linkToSignal(this._subtitlesIntervalCanceller.signal);let{TEXT_TRACK_SIZE_CHECKS_INTERVAL:i}=O.getCurrent();Nu(this._textTrackElement,i,this._sizeUpdateCanceller.signal).onUpdate(({height:a,width:s})=>{for(let d of r){let{resolution:u,element:c}=d;Fu(a,s,u,c)}},{clearSignal:this._sizeUpdateCanceller.signal,emitCurrentValue:!0})}}autoRefreshSubtitles(e){if(this._isAutoRefreshing||e.isCancelled())return;let t=null,{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:r}=O.getCurrent(),i=()=>{this._isAutoRefreshing=!1,t!==null&&(t.cancel(),t=null)},o=()=>{i(),this._isAutoRefreshing=!0,t=new U,t.linkToSignal(e);let a=setInterval(()=>this.refreshSubtitles(),r);t.signal.register(()=>{clearInterval(a)}),this.refreshSubtitles()};Wc(this._videoElement,()=>{i(),this._disableCurrentCues()},e),Hc(this._videoElement,o,e),qc(this._videoElement,o,e),o()}refreshSubtitles(){let{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:e}=O.getCurrent(),t;this._videoElement.paused||this._videoElement.playbackRate<=0?t=this._videoElement.currentTime:t=Math.max(this._videoElement.currentTime+e/1e3/2,0);let r=this._buffer.get(t);r.length===0?this._disableCurrentCues():this._displayCues(r)}};y.CURRENT_ENV===y.DEV&&(DI=function(e){function t(r){}});var DI;var ln=eo;function Oe(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer)}var LI=/&#([0-9]+);/g,NI=/<br>/gi,UI=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,BI=/\s*<p (?:class=([^>]+))?>(.*)/i,FI=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function KI(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;r!==null;){let i=r[1],o=zI(r[2],"lang");!E(i)&&!E(o)&&(t[o]=i),r=e.exec(n)}return t}function VI(n){let t=/p\s*{([^}]*)}/gi.exec(n);return t===null?"":t[1]}function zI(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function WI(n){return n.replace(LI,(e,t)=>String.fromCharCode(Number(t)))}function HI(n,{language:e},t){let r;typeof n!="string"?r=ce(Oe(n)):r=n;let i=/<sync[ >]/gi,o=/<sync[ >]|<\/body>/gi,a=[],s=UI.exec(r),d=Array.isArray(s)?s[1]:"",u,c;o.exec(r);let l=KI(d),f=VI(d),p;if(w(e)&&(p=l[e],p===void 0))throw new Error(`sami: could not find lang ${e} in CSS`);for(;u=i.exec(r),c=o.exec(r),!(u===null&&c===null);){if(u===null||c===null||u.index>=c.index)throw new Error("parse error");let I=r.slice(u.index,c.index),g=FI.exec(I);if(!Array.isArray(g))throw new Error("parse error (sync time attribute)");let b=+g[1];if(isNaN(b))throw new Error("parse error (sync time attribute NaN)");h(I.split(`
|
|
11
|
-
`),
|
|
12
|
-
`);for(let u=0;u<d.length;u++)if(u!==0&&o.appendChild(document.createElement("br")),d[u].length>0){let c=document.createTextNode(d[u]);o.appendChild(c)}}else if(s.nodeName==="B"){let d=t(s);d.style.fontWeight="bold",o.appendChild(d)}else if(s.nodeName==="I"){let d=t(s);d.style.fontStyle="italic",o.appendChild(d)}else if(s.nodeName==="U"){let d=t(s);d.style.textDecoration="underline",o.appendChild(d)}else if(jI(s)&&typeof s.color=="string"){let d=t(s);d.style.color=s.color,o.appendChild(d)}else{let d=t(s);o.appendChild(d)}}return o};return t(e)}function jI(n){return n.nodeName==="FONT"&&"color"in n}function Wu(n){n.htmlTextTracksParsers.srt=zu,n.htmlTextDisplayer=ln}var YI=/(\d+) (\d+)/;function Hu(n){let e=n.getAttribute("ttp:frameRate"),t=n.getAttribute("ttp:subFramRate"),r=n.getAttribute("ttp:tickRate"),i=n.getAttribute("ttp:frameRateMultiplier"),o=n.getAttribute("xml:space"),a=n.getAttribute("ttp:cellResolution"),s={columns:32,rows:15};if(a!==null){let I=YI.exec(a);if(I===null||I.length<3)m.warn("ttml","Invalid cellResolution",{cellResolution:a});else{let g=parseInt(I[1],10),b=parseInt(I[2],10);isNaN(g)||isNaN(b)?m.warn("ttml","Invalid cellResolution",{cellResolution:a}):s={columns:g,rows:b}}}if(w(o)&&o!=="default"&&o!=="preserve")throw new Error("Invalid spacing style");let d=Number(e);(isNaN(d)||d<=0)&&(d=30);let u=Number(t);(isNaN(u)||u<=0)&&(u=1);let c=Number(r);(isNaN(c)||c<=0)&&(c=void 0);let l=d,f=u!=null?u:1,p=o!=null?o:"default",h=c!=null?c:d*u;if(i!==null){let I=/^(\d+) (\d+)$/g.exec(i);if(I!==null){let g=Number(I[1]),b=Number(I[2]),T=g/b;l=d*T}}return{cellResolution:s,tickRate:h,frameRate:l,subFrameRate:f,spaceStyle:p}}function Bn(n,e,t,r){let i={},o=n.slice();for(let a=0;a<=e.length-1;a++){let s=e[a];if(s!==void 0){let d,u;if(s.nodeType===Node.ELEMENT_NODE){let c=s;for(let l=0;l<=c.attributes.length-1;l++){let f=c.attributes[l],p=f.name;if(p==="style")d=f.value;else if(p==="region")u=f.value;else{let h=p.substring(4);if($(o,h)&&(i[h]=f.value,o.splice(l,1),o.length===0))return i}}}if(w(d)){let c=Q(t,l=>l.id===d);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!w(i[f])&&w(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}if(w(u)){let c=Q(r,l=>l.id===u);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!w(i[f])&&w(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}}}return i}function qu(n){if(n.nodeType!==Node.ELEMENT_NODE)return{};let e=n,t={};for(let r=0;r<=e.attributes.length-1;r++){let i=e.attributes[r];if(Ce(i.name,"tts")){let o=i.name.substring(4);t[o]=i.value}}return t}function Gu(n){let e=[];function t(r,i){e.push(i);for(let o of r.extendsStyles){let a=Ie(n,s=>s.id===o);if(a<0)m.warn("ttml","unknown style inheritance",{id:o});else{let s=n[a];$(e,a)?m.warn("ttml","infinite style inheritance loop avoided"):t(s,a),r.style=Y({},s.style,r.style)}}r.extendsStyles.length=0}for(let r=0;r<n.length;r++)t(n[r],r),e.length=0}function wm(n,e){if(!(n.parentNode instanceof Element))return[];function t(r){let i=[];r.tagName.toLowerCase()===e.toLowerCase()&&i.push(r);let o=r.parentNode;return o instanceof Element&&i.push(...t(o)),i}return t(n.parentNode)}function Oa(n){let e=wm(n,"div");if(e.length===0){let t=wm(n,"tt:div");t.length>0&&(e=t)}return e}function Om(n){let e=n.getElementsByTagName("body");if(e.length>0)return e[0];let t=n.getElementsByTagName("tt:body");return t.length>0?t[0]:null}function Dm(n){let e=n.getElementsByTagName("style");if(e.length>0)return e;let t=n.getElementsByTagName("tt:style");return t.length>0?t:e}function Lm(n){let e=n.getElementsByTagName("region");if(e.length>0)return e;let t=n.getElementsByTagName("tt:region");return t.length>0?t:e}function Nm(n){let e=n.getElementsByTagName("p");if(e.length>0)return e;let t=n.getElementsByTagName("tt:p");return t.length>0?t:e}function Da(n){return n.nodeName==="br"||n.nodeName==="tt:br"}function La(n){return n.nodeName==="span"||n.nodeName==="tt:span"}var Um=["align","backgroundColor","color","direction","display","displayAlign","extent","fontFamily","fontSize","fontStyle","fontWeight","lineHeight","opacity","origin","overflow","padding","textAlign","textDecoration","textOutline","unicodeBidi","visibility","wrapOption","writingMode"];function ro(n,e){let t=[],r=new DOMParser().parseFromString(n,"text/xml");if(r!=null){let o=r.getElementsByTagName("tt")[0];if(o===void 0&&(o=r.getElementsByTagNameNS("*","tt")[0],o===void 0))throw new Error("invalid XML");let a=Om(o),s=Dm(o),d=Lm(o),u=Nm(o),c=Hu(o),l=[];for(let g=0;g<=s.length-1;g++){let b=s[g];if(b instanceof Element){let T=b.getAttribute("xml:id");if(T!==null){let v=b.getAttribute("style"),_=v===null?[]:v.split(" ");l.push({id:T,style:qu(b),extendsStyles:_})}}}Gu(l);let f=[];for(let g=0;g<=d.length-1;g++){let b=d[g];if(b instanceof Element){let T=b.getAttribute("xml:id");if(T!==null){let v=qu(b),_=b.getAttribute("style");if(w(_)){let R=Q(l,k=>k.id===_);R!==void 0&&(v=Y({},R.style,v))}f.push({id:T,style:v,extendsStyles:[]})}}}let p=Bn(Um,a!==null?[a]:[],l,f),I=(a!==null?a.getAttribute("xml:space"):void 0)==="default"||c.spaceStyle==="default";for(let g=0;g<u.length;g++){let b=u[g];if(b instanceof Element){let T=Oa(b),v=Y({},p,Bn(Um,[b,...T],l,f)),_=b.getAttribute("xml:space"),R=w(_)?_==="default":I,k={paragraph:b,timeOffset:e,idStyles:l,regionStyles:f,body:a,paragraphStyle:v,ttParams:c,shouldTrimWhiteSpace:R};k!==null&&t.push(k)}}}return t}function Bm(n){return n.extent===void 0&&n.origin===void 0&&n.displayAlign===void 0&&n.display===void 0&&n.textAlign===void 0&&n.fontSize===void 0}function Fm(n){n.extent="70% 20%",n.fontSize="1c",n.origin="15% 80%",n.displayAlign="before",n.textAlign="center"}var ju=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Yu=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/,Qu=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d{2,})$/,$u=/^(\d*\.?\d*)f$/,Xu=/^(\d*\.?\d*)t$/,Zu=/^(?:(\d*\.?\d*)h)?(?:(\d*\.?\d*)m)?(?:(\d*\.?\d*)s)?(?:(\d*\.?\d*)ms)?$/,Ju=/^(\d{1,2}|100)% (\d{1,2}|100)%$/,$e=/^((?:\+|-)?\d*(?:\.\d+)?)(px|em|c|%|rh|rw)$/,Km=/^#([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})$/,Vm=/^#([0-9A-f])([0-9A-f])([0-9A-f])([0-9A-f])$/,zm=/^rgb\( *(\d+) *, *(\d+) *, *(\d+) *\)/,Wm=/^rgba\( *(\d+) *, *(\d+) *, *(\d+) *, *(\d+) *\)/;function QI(n,e){if(ju.test(n))return ZI(e,n);if(Yu.test(n))return el(Yu,n);if(Qu.test(n))return el(Qu,n);if($u.test(n))return $I(e,n);if(Xu.test(n))return XI(e,n);if(Zu.test(n))return el(Zu,n)}function $I(n,e){let t=$u.exec(e);return Number(t[1])/n.frameRate}function XI(n,e){let t=Xu.exec(e);return Number(t[1])/n.tickRate}function ZI(n,e){let t=ju.exec(e),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]),a=Number(t[4]),s=Number(t[5]);return isNaN(s)&&(s=0),a+=s/n.subFrameRate,o+=a/n.frameRate,o+i*60+r*3600}function el(n,e){let t=n.exec(e);if(t===null||t[0]==="")return null;let r=Number(t[1]);isNaN(r)&&(r=0);let i=Number(t[2]);isNaN(i)&&(i=0);let o=Number(t[3]);isNaN(o)&&(o=0);let a=Number(t[4]);return isNaN(a)&&(a=0),a/1e3+o+i*60+r*3600}var Na=QI;function io(n,e){let t=n.getAttribute("begin"),r=n.getAttribute("dur"),i=n.getAttribute("end"),o=w(t)?Na(t,e):null,a=w(r)?Na(r,e):null,s=w(i)?Na(i,e):null;if(E(o)||E(s)&&E(a))throw new Error("Invalid text cue");let d=E(s)?o+a:s;return{start:o,end:d}}var tl;function De(n,e){tl===void 0&&(tl=n.classList!==void 0&&typeof n.classList.add=="function"),tl?n.classList.add(e):(" "+n.className+" ").indexOf(" "+e+" ")<0&&(n.className+=" "+e)}function nl(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=$e.exec(r[0]),o=$e.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.width=i[1]+i[2]:i[2]==="c"?(De(n,"proportional-style"),n.setAttribute("data-proportional-width",i[1])):m.warn("ttml","unhandled extent unit",{unit:i[2]}),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.height=o[1]+o[2]:o[2]==="c"?(De(n,"proportional-style"),n.setAttribute("data-proportional-height",o[1])):m.warn("ttml","unhandled extent unit",{unit:o[2]}))}function rl(n,e){let r=e.trim().split(" ");if(r.length===0)return;let i=$e.exec(r[0]);if(i!==null)if(i[2]==="px"||i[2]==="em")n.style.fontSize=i[1]+i[2];else if(i[2]==="c")n.style.position="relative",De(n,"proportional-style"),n.setAttribute("data-proportional-font-size",i[1]);else if(i[2]==="%"){let o=Number(i[1]);isNaN(o)?m.warn("ttml",'could not parse fontSize value "'+i[1]+'" into a number'):(n.style.position="relative",De(n,"proportional-style"),n.setAttribute("data-proportional-font-size",String(o/100)))}else m.warn("ttml","unhandled fontSize unit",{unit:i[2]})}function il(n,e){let t=e.trim(),r=t.split(" ");if(t==="auto")return;let i=$e.exec(r[0]);i!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.lineHeight=i[1]+i[2]:i[2]==="c"?(De(n,"proportional-style"),n.setAttribute("data-proportional-line-height",i[1])):m.warn("ttml","unhandled lineHeight unit",{unit:i[2]}))}function ol(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=$e.exec(r[0]),o=$e.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.left=i[1]+i[2]:i[2]==="c"?(De(n,"proportional-style"),n.setAttribute("data-proportional-left",i[1])):m.warn("ttml","unhandled origin unit",{unit:i[2]}),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.top=o[1]+o[2]:o[2]==="c"?(De(n,"proportional-style"),n.setAttribute("data-proportional-top",o[1])):m.warn("ttml","unhandled origin unit",{unit:o[2]}))}function al(n,e){let r=e.trim().split(" ");if(r.length<1)return;let i=$e.exec(r[0]);if(i===null)return;if(i[2]==="px"||i[2]==="%"||i[2]==="em"){let d=i[1]+i[2];r.length===1?n.style.padding=d:r.length===2?(n.style.paddingTop=d,n.style.paddingBottom=d):n.style.paddingTop=d}else i[2]==="c"?(De(n,"proportional-style"),r.length===1?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1]),n.setAttribute("data-proportional-padding-left",i[1]),n.setAttribute("data-proportional-padding-right",i[1])):r.length===2?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1])):n.setAttribute("data-proportional-padding-top",i[1])):m.warn("ttml","unhandled padding unit",{unit:i[2]});if(r.length===1)return;let o=$e.exec(r[1]);if(o===null)return;if(o[2]==="px"||o[2]==="%"||o[2]==="em"){let d=o[1]+o[2];r.length<4&&(n.style.paddingLeft=d),n.style.paddingRight=d}else o[2]==="c"?(De(n,"proportional-style"),r.length<4&&n.setAttribute("data-proportional-padding-left",o[1]),n.setAttribute("data-proportional-padding-right",o[1])):m.warn("ttml","unhandled padding unit",{unit:o[2]});if(r.length===2)return;let a=$e.exec(r[2]);if(a===null)return;if(a[2]==="px"||a[2]==="%"||a[2]==="em"){let d=a[1]+a[2];n.style.paddingBottom=d}else a[2]==="c"?(De(n,"proportional-style"),n.setAttribute("data-proportional-padding-bottom",a[1])):m.warn("ttml","unhandled padding unit",{unit:a[2]});if(r.length===3)return;let s=$e.exec(r[3]);if(s!==null)if(s[2]==="px"||s[2]==="%"||s[2]==="em"){let d=s[1]+s[2];n.style.paddingLeft=d}else s[2]==="c"?(De(n,"proportional-style"),n.setAttribute("data-proportional-padding-left",s[1])):m.warn("ttml","unhandled padding unit",{unit:s[2]})}function cr(n,e){let t=e;return w(e)&&e.trim().endsWith("%")&&(t=e.trim().slice(0,-1),t=(parseInt(t,10)/100).toString()+"em"),`-1px -1px ${t} ${n},1px -1px ${t} ${n},-1px 1px ${t} ${n},1px 1px ${t} ${n}`}function cn(n){let e;return e=Km.exec(n),E(e)?(e=Vm.exec(n),E(e)?(e=zm.exec(n),E(e)?(e=Wm.exec(n),E(e)?n:"rgba("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+","+String(+e[4]/255)+")"):"rgb("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+")"):"rgba("+String(parseInt(e[1]+e[1],16))+","+String(parseInt(e[2]+e[2],16))+","+String(parseInt(e[3]+e[3],16))+","+String(parseInt(e[4]+e[4],16)/255)+")"):"rgba("+String(parseInt(e[1],16))+","+String(parseInt(e[2],16))+","+String(parseInt(e[3],16))+","+String(parseInt(e[4],16)/255)+")"}var JI=["color","direction","display","fontFamily","fontSize","fontStyle","fontWeight","textDecoration","textOutline","unicodeBidi","visibility","wrapOption"];function eb(n,e,t){let r=e.color;w(r)&&(n.style.color=cn(r));let i=e.backgroundColor;w(i)&&(n.style.backgroundColor=cn(i));let o=e.textOutline;if(w(o)){let g=o.trim().replace(/\s+/g," ").split(" "),b=g.length;if(b===3){let T=cn(g[0]),v=g[1];n.style.textShadow=cr(T,v)}else if(w(r)&&b===1){let T=g[0];n.style.textShadow=cr(r,T)}else if(b===2){let T=/^[#A-Z]/i.test(g[0]),v=/^[0-9]/.test(g[0]);if(T!==v){if(T){let _=cn(g[0]),R=g[1];n.style.textShadow=cr(_,R)}else if(w(r)){let _=g[0];n.style.textShadow=cr(r,_)}}}}let a=e.textDecoration;if(w(a))switch(a){case"noUnderline":case"noLineThrough":case"noOverline":n.style.textDecoration="none";break;case"lineThrough":n.style.textDecoration="line-through";break;default:n.style.textDecoration=a;break}let s=e.fontFamily;if(w(s))switch(s){case"proportionalSansSerif":n.style.fontFamily="Arial, Helvetica, Liberation Sans, sans-serif";break;case"monospaceSansSerif":case"sansSerif":n.style.fontFamily="sans-serif";break;case"monospaceSerif":case"default":n.style.fontFamily="Courier New, Liberation Mono, monospace";break;case"proportionalSerif":n.style.fontFamily="serif";break;default:n.style.fontFamily=s}let d=e.fontStyle;w(d)&&(n.style.fontStyle=d);let u=e.fontWeight;w(u)&&(n.style.fontWeight=u);let c=e.fontSize;w(c)?rl(n,c):(De(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1"));let l=e.direction;w(l)&&(n.style.direction=l);let f=e.unicodeBidi;if(w(f))switch(f){case"bidiOverride":n.style.unicodeBidi="bidi-override";break;case"embed":n.style.unicodeBidi="embed";break;default:n.style.unicodeBidi="normal"}let p=e.visibility;w(p)&&(n.style.visibility=p),e.display==="none"&&(n.style.display="none"),e.wrapOption==="noWrap"?t?n.style.whiteSpace="nowrap":n.style.whiteSpace="pre":t?n.style.whiteSpace="normal":n.style.whiteSpace="pre-wrap"}function tb(n,e){n.style.color="white",n.style.position="absolute";let t=e.extent;w(t)&&nl(n,t);let r=e.writingMode;w(r);let i=e.overflow;n.style.overflow=w(i)?i:"hidden";let o=e.padding;w(o)&&al(n,o);let a=e.origin;w(a)&&ol(n,a);let s=e.displayAlign;if(w(s))switch(n.style.display="flex",n.style.flexDirection="column",s){case"before":n.style.justifyContent="flex-start";break;case"center":n.style.justifyContent="center";break;case"after":n.style.justifyContent="flex-end";break}let d=e.opacity;w(d)&&(n.style.opacity=d);let u=e.visibility;w(u)&&(n.style.visibility=u),e.display==="none"&&(n.style.display="none")}function nb(n,e){n.style.margin="0px",De(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1");let t=e.backgroundColor;w(t)&&(n.style.backgroundColor=cn(t));let r=e.lineHeight;w(r)&&il(n,r);let i=e.textAlign;if(w(i))switch(i){case"center":n.style.textAlign="center";break;case"left":case"start":n.style.textAlign="left";break;case"right":case"end":n.style.textAlign="right";break}}function rb(n,e,t){let r=document.createElement("span"),i=n.textContent===null?"":n.textContent;if(t){let a=i.trim();a=a.replace(/\s+/g," "),i=a}let o=document.createTextNode(i);return r.appendChild(o),r.className="rxp-texttrack-span",eb(r,e,t),r}function ib(n,e,t,r,i){function o(a,s,d,u){let c=a.childNodes,l=[];for(let f=0;f<c.length;f++){let p=c[f];if(p.nodeName==="#text"){let{backgroundColor:h}=Bn(["backgroundColor"],d,t,e);w(h)?s.backgroundColor=h:s.backgroundColor="";let I=rb(p,s,u);l.push(I)}else if(Da(p)){let h=document.createElement("BR");l.push(h)}else if(La(p)&&p.nodeType===Node.ELEMENT_NODE&&p.childNodes.length>0){let h=p.getAttribute("xml:space"),I=w(h)?h==="default":u,g=Y({},s,Bn(JI,[p],t,e));l.push(...o(p,g,[p,...d],I))}}return l}return o(n,Y({},r),[],i)}function sl(n,e,t,r,i,{cellResolution:o,shouldTrimWhiteSpace:a}){let s=Oa(n),d=document.createElement("DIV");if(d.className="rxp-texttrack-region",d.setAttribute("data-resolution-columns",String(o.columns)),d.setAttribute("data-resolution-rows",String(o.rows)),tb(d,i),e!==null){let{bodyBackgroundColor:l}=Bn(["backgroundColor"],[...s,e],r,t);w(l)&&(d.style.backgroundColor=cn(l))}let u=document.createElement("p");u.className="rxp-texttrack-p",nb(u,i);let c=ib(n,t,r,i,a);for(let l=0;l<c.length;l++)u.appendChild(c[l]);return d.appendChild(u),d}function dl(n){let{paragraph:e,ttParams:t,body:r,regionStyles:i,idStyles:o,paragraphStyle:a,timeOffset:s,shouldTrimWhiteSpace:d}=n;if(!e.hasAttribute("begin")&&!e.hasAttribute("end")&&/^\s*$/.test(e.textContent===null?"":e.textContent))return null;let{cellResolution:u}=t,{start:c,end:l}=io(e,t),f=sl(e,r,i,o,a,{cellResolution:u,shouldTrimWhiteSpace:d});return{start:c+s,end:l+s,element:f}}function ul(n,e,t){let r;typeof n!="string"?r=ce(Oe(n)):r=n;let i=ro(r,t),o=[];for(let a of i){let{paragraphStyle:s}=a;Bm(s)&&Fm(s);let d=dl(a);d!==null&&o.push(d)}return o}var Hm=ul;function ll(n){n.htmlTextTracksParsers.ttml=Hm,n.htmlTextDisplayer=ln}function Ua(n){let e=n.split(":").reverse();if(w(e[2])||w(e[1])){let t=w(e[2])?parseInt(e[2],10):0,r=parseInt(e[1],10),i=parseFloat(e[0].replace(",","."));return isNaN(t)||isNaN(r)||isNaN(i)?void 0:t*60*60+r*60+i}}function cl(n){return n.split(/ |\t/).reduce((t,r)=>{let i=r.split(":");return i.length===2&&(t[i[0]]=i[1]),t},{})}function ob(n){let t=/^([\d:.]+)[ |\t]+-->[ |\t]+([\d:.]+)[ |\t]*(.*)$/.exec(n);if(t===null)return null;let r=Ua(t[1]),i=Ua(t[2]);if(r===void 0||i===void 0)return null;let o=cl(t[3]);return{start:r,end:i,settings:o}}function oo(n,e){let t=/-->/,r,i,o;if(t.test(n[0]))r=n[0],i=n.slice(1,n.length);else{if(!t.test(n[1]))return null;o=n[0],r=n[1],i=n.slice(2,n.length)}let a=ob(r);if(a===null)return null;let{start:s,end:d,settings:u}=a;return{start:s+e,end:d+e,settings:u,payload:i,header:o}}function Fn(n,e,t,r){var c,l;let i=[],o=Gr(n);if(o===void 0)return[];let a=rf(n),s=Rn(n);if(s===null)return[];let d=0,u=o;for(let f of a){let p=(c=f.duration)!=null?c:0,h=f.compositionTimeOffset!==void 0?u+f.compositionTimeOffset:u;u=h+p;let I=0;for(;I<((l=f.size)!=null?l:0);){let g=J(s,d);d+=4,I+=g;let b=ce(s.slice(d,d+4));d+=4;let T=null;if(b==="vttc"?g>8&&(T=s.slice(d,d+(g-8)),d+=g-8):b==="vtte"?g>8&&(d+=g-8):(m.error("vtt","encountered unknown fragmented vtt box",{box:b}),d+=Math.min(g-8,1)),p>0){if(T!==null){let v=ab(T,t+h/e,t+u/e,r);v!==null&&i.push(v)}}else m.error("vtt","cue duration missing")}}return d!==s.length&&m.error("vtt","end offset is not equal to mdat length",{mdataOffset:d,mdatLength:s.length}),i}function ab(n,e,t,r){let i=sb(n),o=db(n);return i===null?null:r({start:e,end:t,settings:o!==null?cl(ce(o)):{},header:void 0,payload:[ce(i)]},{classes:{},global:void 0})}function sb(n){return Ee(n,1885436268)}function db(n){return Ee(n,1937011815)}function ao(n,e){let t=["u","i","b"],r=["u","i","b","c","#text"],i=n.nodeName.toLowerCase().split(".")[0],o;if($(r,i))if(i==="#text"){let a=n.wholeText.split(`
|
|
13
|
-
`);o=document.createElement("span");for(let s=0;s<a.length;s++)if(s>0&&o.appendChild(document.createElement("br")),a[s].length>0){let d=document.createTextNode(a[s]);o.appendChild(d)}}else{let a=n.nodeName.toLowerCase().split("."),s=[];if(a.forEach(d=>{
|
|
14
|
-
`),
|
|
15
|
-
`).replace(
|
|
16
|
-
`),
|
|
17
|
-
`);return
|
|
18
|
-
`;else if(
|
|
19
|
-
`);return Gt(t,r,o)}function Va(n,e,t){let r;typeof n=="string"?r=n:r=ce(Oe(n));let i=r.split(/\r\n|\n|\r/);if(!/^WEBVTT($| |\t)/.test(i[0]))throw new Error("Can't parse WebVTT: Invalid file.");let o=Fa(i),a=so(i,o),s=uo(i,o),d=lo(s),u=[];for(let c of a){let l=oo(c,t);if(l!==null){let f=mr(l,d);f!==null&&(fo(f)&&Al(l.settings,f),u.push(f))}}return u}function za(n,{initTimescale:e},t){return typeof n=="string"?Fn(Te(n),e!=null?e:1,t,mr):Fn(Oe(n),e!=null?e:1,t,mr)}function Ml(n){n.nativeTextTracksParsers.vtt=Va,n.nativeTextTracksParsers.mp4vtt=za,n.nativeTextDisplayer=fn}function pr(n){let e=[];n.periods.forEach(t=>{let r=t.id;if($(e,r)){m.warn("utils","Two periods with the same ID found. Updating.",{periodID:r});let a=r+"-dup";t.id=a,pr(n),e.push(a)}else e.push(r);let{adaptations:i}=t,o=[];Object.keys(i).forEach(a=>{let s=i[a];s!==void 0&&s.forEach(d=>{let u=d.id;if($(o,u)){m.warn("utils","Two adaptations with the same ID found. Updating.",{adaptationID:u});let l=u+"-dup";d.id=l,pr(n),o.push(l)}else o.push(u);let c=[];d.representations.forEach(l=>{let f=l.id;if($(c,f)){m.warn("utils","Two representations with the same ID found. Updating.",{representationID:f});let p=`${f}-dup`;l.id=p,pr(n),c.push(p)}else c.push(f)})})})})}function Qm(n,e){let t;return e==="AACH"?t=5:t=w(n)?(parseInt(n.substring(0,2),16)&248)>>3:2,t===0?"mp4a.40.2":`mp4a.40.${t}`}function $m(n){let e=/00000001\d7([0-9a-fA-F]{6})/.exec(n);return e===null||!w(e[1])?"avc1.4D401E":"avc1."+e[1]}function xl(n){return n.reduce((e,t,r)=>{let i=t.getAttribute("d"),o=t.getAttribute("t"),a=t.getAttribute("r"),s=a!==null?+a-1:0,d=o!==null?+o:void 0,u=i!==null?+i:void 0;if(r===0)d=d===void 0||isNaN(d)?0:d;else{let c=e[r-1];if(d===void 0||isNaN(d)){if(c.duration===void 0||isNaN(c.duration))throw new Error("Smooth: Invalid CNodes. Missing timestamp.");d=c.start+c.duration*(c.repeatCount+1)}}if(u===void 0||isNaN(u)){let c=n[r+1];if(c!==void 0){let l=c.getAttribute("t"),f=w(l)?+l:null;if(f===null)throw new Error("Can't build index timeline from Smooth Manifest.");u=f-d}else return e}return e.push({duration:u,start:d,repeatCount:s}),e},[])}function Nb(n){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:de([8,1,18,16],n)}]}function wl(n,e=Nb){if(n.firstElementChild===null||n.firstElementChild.nodeName!=="ProtectionHeader")throw new Error("Protection should have ProtectionHeader child");let t=n.firstElementChild,r=St(t.textContent===null?"":t.textContent),i=Hr(r),o=Xe(i),a=t.getAttribute("SystemID"),s=(a!==null?a:"").toLowerCase().replace(/\{|\}/g,""),d=e(o);return{keyId:o,keySystems:[{systemId:s,privateData:r}].concat(d)}}function Xm(n,e,t){return n.replace(/\{bitrate\}/g,String(e)).replace(/{CustomAttributes}/g,t.length>0?t[0]:"")}function Zm(n,e){return n.replace(/\{start time\}/g,String(e))}function Ub(n,e,t){let r=e-n;return r>0?Math.floor(r/t):0}function Bb(n,e,t){let r=n===void 0||n===0?1:n;return{up:e*r,to:(e+t)*r}}function Fb(n,e){let t=n.repeatCount;if(n.duration!==void 0&&t<0){let r=e!==void 0?e.start:1/0;t=Math.ceil((r-n.start)/n.duration)-1}return t}var mo=class{constructor(e){let{isLive:t,segmentPrivateInfos:r,media:i,sharedSmoothTimeline:o}=e;if(this._sharedSmoothTimeline=o,this._initSegmentInfos={bitsPerSample:r.bitsPerSample,channels:r.channels,codecPrivateData:r.codecPrivateData,packetSize:r.packetSize,samplingRate:r.samplingRate,timescale:o.timescale,height:r.height,width:r.width,protection:r.protection},this._isLive=t,this._media=i,o.timeline.length!==0&&t){let{timeline:a,validityTime:s}=o,d=a[a.length-1],u=xe(d,null),c=s/1e3*o.timescale;this._scaledLiveGap=c-u}}getInitSegment(){return{id:"init",isInit:!0,privateInfos:{smoothInitSegment:this._initSegmentInfos},url:null,time:0,end:0,duration:0,timescale:1,complete:!0}}getSegments(e,t){this._refreshTimeline();let{timescale:r,timeline:i}=this._sharedSmoothTimeline,{up:o,to:a}=Bb(r,e,t),s=this._media,d,u=[],c=i.length,l=this._scaledLiveGap===void 0?void 0:z()/1e3*r-this._scaledLiveGap;for(let f=0;f<c;f++){let p=i[f],{duration:h,start:I}=p,g=Fb(p,i[f+1]),b=Ub(I,o,h),T=I+b*h,v=h;for(;T<a&&b<=g&&(l===void 0||T+v<=l);){let _=T,R=d!==void 0?d+b:void 0,k={id:String(T),isInit:!1,time:_/r,end:(_+h)/r,duration:h/r,timescale:1,number:R,url:Zm(s,_),complete:!0,privateInfos:{smoothMediaSegment:{time:_,duration:h}}};u.push(k),b++,T=I+b*h}if(T>=a)return u;d!==void 0&&(d+=g+1)}return u}shouldRefresh(e,t){if(this._refreshTimeline(),!this._isLive)return!1;let{timeline:r,timescale:i}=this._sharedSmoothTimeline,o=r[r.length-1];if(o===void 0)return!1;let a=o.repeatCount,s=o.start+(a+1)*o.duration;if(t*i<s)return!1;if(e*i>=s)return!0;let d=o.start+a*o.duration;return e*i>d}getFirstAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;return e.length===0?null:e[0].start/t}getLastAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;if(this._scaledLiveGap===void 0){let r=e[e.length-1];return xe(r,null)/t}for(let r=e.length-1;r>=0;r--){let i=e[r],o=z()/1e3*t,{start:a,duration:s,repeatCount:d}=i;for(let u=d;u>=0;u--){let c=a+s*(u+1);if(c<=o-this._scaledLiveGap)return c/t}}}getEnd(){if(!this._isLive)return this.getLastAvailablePosition()}awaitSegmentBetween(e,t){var i;if(ne(e<=t),this.isStillAwaitingFutureSegments())return!1;let r=this.getLastAvailablePosition();return r!==void 0&&t<r?!1:t>((i=this.getFirstAvailablePosition())!=null?i:0)?void 0:!1}checkDiscontinuity(e){return this._refreshTimeline(),Ta(this._sharedSmoothTimeline,e,void 0)}isSegmentStillAvailable(e){if(e.isInit)return!0;this._refreshTimeline();let{timeline:t,timescale:r}=this._sharedSmoothTimeline;for(let i=0;i<t.length;i++){let o=t[i],a=o.start/r;if(a>e.time)return!1;if(a===e.time)return!0;if(o.repeatCount>=0&&o.duration!==void 0){let d=(a-o.start)/o.duration-1;return d%1===0&&d<=o.repeatCount}}return!1}canBeOutOfSyncError(e){return this._isLive?e instanceof ut&&(e.isHttpError(404)||e.isHttpError(412)):!1}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}_replace(e){this._initialScaledLastPosition=e._initialScaledLastPosition,this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.replace(e._sharedSmoothTimeline)}_update(e){this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.update(e._sharedSmoothTimeline)}isStillAwaitingFutureSegments(){return this._isLive}isInitialized(){return!0}initialize(){m.error("smooth","A `SmoothRepresentationIndex` does not need to be initialized")}addPredictedSegments(e,t){this._sharedSmoothTimeline.addPredictedSegments(e,t)}_refreshTimeline(){this._sharedSmoothTimeline.refresh()}};function Ol(n,e,t,r){let i=n.length,o=n[i-1],a=t.timescale===e?{time:t.time,duration:t.duration}:{time:t.time/t.timescale*e,duration:t.duration/t.timescale*e};return r.time===a.time?!1:a.time>=xe(o,null)?(o.duration===a.duration?o.repeatCount++:n.push({duration:a.duration,start:a.time,repeatCount:0}),!0):!1}var po=class{constructor(e){let{timeline:t,timescale:r,timeShiftBufferDepth:i,manifestReceivedTime:o}=e;this.timeline=t,this.timescale=r;let a=o!=null?o:z();if(this.validityTime=a,this._timeShiftBufferDepth=i,t.length!==0){let s=t[t.length-1],d=xe(s,null);this._initialScaledLastPosition=d}}refresh(){if(this._initialScaledLastPosition===void 0)return;let e=this._timeShiftBufferDepth,r=(z()-this.validityTime)/1e3+this._initialScaledLastPosition/this.timescale;if(e!==void 0){let i=(r-e)*this.timescale;Bi(this.timeline,i)}}replace(e){let t=this.timeline,r=e.timeline,i=this.timescale,o=e.timescale;if(this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime,t.length===0||r.length===0||i!==o)return;let a=t[t.length-1],s=r[r.length-1],d=xe(s,null);if(!(xe(a,null)<=d))for(let u=0;u<t.length;u++){let c=t[u],l=xe(c,null);if(l===d){this.timeline=this.timeline.concat(t.slice(u+1));return}if(l>d){if(c.duration!==s.duration)return;let f=d-c.start;if(f===0){m.warn("smooth","a discontinuity detected in the previous manifest has been resolved."),this.timeline=this.timeline.concat(t.slice(u));return}if(f<0||f%c.duration!==0)return;let p=f/c.duration-1,h=c.repeatCount-p;if(h<0)return;s.repeatCount+=h;let I=t.slice(u+1);this.timeline=this.timeline.concat(I);return}}}update(e){Fi(this.timeline,e.timeline),this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime}addPredictedSegments(e,t){var r;if(((r=t.privateInfos)==null?void 0:r.smoothMediaSegment)===void 0){m.warn("smooth","should only encounter SmoothRepresentationIndex");return}this.refresh();for(let i of e)Ol(this.timeline,this.timescale,i,t.privateInfos.smoothMediaSegment)}};function Dl(n){return typeof n=="boolean"?n:typeof n=="string"?n.toUpperCase()==="TRUE":!1}function gr(n,e,t){let r=n.firstElementChild,i=t;for(;r!==null;)i=e(i,r.nodeName,r),r=r.nextElementSibling;return i}var Kb={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},go={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4",DFXP:"application/ttml+xml+mp4"};function Vb(n={}){let e=n.referenceDateTime===void 0?Date.UTC(1970,0,1,0,0,0,0)/1e3:n.referenceDateTime,t=n.minRepresentationBitrate===void 0?0:n.minRepresentationBitrate,{serverSyncInfos:r}=n,i=r!==void 0?r.serverTimestamp-r.clientTime:void 0;function o(d,u){let c=gr(d,(f,p,h)=>(p==="CustomAttributes"&&f.push(...gr(h,(I,g,b)=>{if(g==="Attribute"){let T=b.getAttribute("Name"),v=b.getAttribute("Value");T!==null&&v!==null&&I.push(T+"="+v)}return I},[])),f),[]);function l(f){let p=d.getAttribute(f);return p===null?void 0:p}switch(u){case"audio":{let f=l("AudioTag"),p=l("BitsPerSample"),h=l("Channels"),I=l("CodecPrivateData"),g=l("FourCC"),b=l("PacketSize"),T=l("SamplingRate"),v=l("Bitrate"),_=v===void 0?0:parseInt(v,10);if(_=isNaN(_)?0:_,g!==void 0&&go[g]===void 0||I===void 0)return m.warn("smooth","Unsupported audio codec. Ignoring quality level.",{fourCC:g}),null;let R=Qm(I,g);return{audiotag:f!==void 0?parseInt(f,10):f,bitrate:_,bitsPerSample:p!==void 0?parseInt(p,10):p,channels:h!==void 0?parseInt(h,10):h,codecPrivateData:I,codecs:R,customAttributes:c,mimeType:g!==void 0?go[g]:g,packetSize:b!==void 0?parseInt(b,10):b,samplingRate:T!==void 0?parseInt(T,10):T}}case"video":{let f=l("CodecPrivateData"),p=l("FourCC"),h=l("MaxWidth"),I=l("MaxHeight"),g=l("Bitrate"),b=g===void 0?0:parseInt(g,10);if(b=isNaN(b)?0:b,p!==void 0&&go[p]===void 0||f===void 0)return m.warn("smooth","Unsupported video codec. Ignoring quality level.",{fourCC:p}),null;let T=$m(f);return{bitrate:b,customAttributes:c,mimeType:p!==void 0?go[p]:p,codecPrivateData:f,codecs:T,width:h!==void 0?parseInt(h,10):void 0,height:I!==void 0?parseInt(I,10):void 0}}case"text":{let f=l("CodecPrivateData"),p=l("FourCC"),h=l("Bitrate"),I=h===void 0?0:parseInt(h,10);return I=isNaN(I)?0:I,{bitrate:I,customAttributes:c,mimeType:p!==void 0?go[p]:p,codecPrivateData:f!=null?f:""}}default:return m.error("smooth","Unrecognized StreamIndex type: "+u),null}}function a(d){let{root:u,timescale:c,baseUrl:l,protections:f,timeShiftBufferDepth:p,manifestReceivedTime:h,isLive:I}=d,g=u.getAttribute("Timescale"),b=g===null?c:+g;isNaN(b)&&(b=c);let T=u.getAttribute("Type");if(T===null)throw new Error("StreamIndex without type.");$(Jt,T)||m.warn("smooth","Unrecognized adaptation type:",T);let v=T,_=u.getAttribute("Subtype"),R=u.getAttribute("Language"),k=u.getAttribute("Url"),x=k===null?"":k;ne(x!=="");let{qualityLevels:P,cNodes:M}=gr(u,(A,C,N)=>{switch(C){case"QualityLevel":{let K=o(N,v);if(K===null)return A;(v!=="video"||K.bitrate>t)&&A.qualityLevels.push(K);break}case"c":A.cNodes.push(N);break}return A},{qualityLevels:[],cNodes:[]}),L=new po({timeline:xl(M),timescale:b,timeShiftBufferDepth:p,manifestReceivedTime:h});ne(P.length!==0,"Adaptation should have at least one playable representation.");let F=v+(w(R)?"_"+R:""),D=P.map(A=>{let C=Xm(x,A.bitrate,A.customAttributes),N=w(A.mimeType)?A.mimeType:Kb[v],K=A.codecs,q=F+"_"+(E(v)?"":v+"-")+(E(N)?"":N+"-")+(E(K)?"":K+"-")+String(A.bitrate),X=[],W;f.length>0&&(W=f[0],f.forEach(oe=>{X.push(oe.keyId)}));let H={bitsPerSample:A.bitsPerSample,channels:A.channels,codecPrivateData:A.codecPrivateData,packetSize:A.packetSize,samplingRate:A.samplingRate,height:A.height,width:A.width,protection:E(W)?void 0:{keyId:W.keyId}},G=new mo({isLive:I,sharedSmoothTimeline:L,media:C,segmentPrivateInfos:H}),ie=Y({},A,{index:G,cdnMetadata:[{baseUrl:l}],mimeType:N,codecs:K,id:q});if(X.length>0||W!==void 0){let oe=W===void 0?[]:W.keySystems.map(fe=>{let{systemId:Re,privateData:ge}=fe,he=Re.replace(/-/g,""),_t=zb(he,ge);return{systemId:he,data:_t}});if(oe.length>0){let fe=[{type:"cenc",values:oe}];ie.contentProtections={keyIds:X,initData:fe}}else ie.contentProtections={keyIds:X,initData:[]}}return ie});if(_==="ADVT")return null;let B={id:F,type:v,representations:D,language:R===null?void 0:R};return v==="text"&&_==="DESC"&&(B.closedCaption=!0),B}function s(d,u,c){let l="";if(u!==void 0){let G=wr(u);l=u.substring(0,G)}let f=d.documentElement;if(E(f)||f.nodeName!=="SmoothStreamingMedia")throw new Error("document root should be SmoothStreamingMedia");let p=f.getAttribute("MajorVersion"),h=f.getAttribute("MinorVersion");if(p===null||h===null||!/^[2]-[0-2]$/.test(p+"-"+h))throw new Error("Version should be 2.0, 2.1 or 2.2");let I=f.getAttribute("Timescale"),g=w(I)?+I:1e7;isNaN(g)&&(g=1e7);let{protections:b,adaptationNodes:T}=gr(f,(G,ie,oe)=>{switch(ie){case"Protection":{G.protections.push(wl(oe,n.keySystems));break}case"StreamIndex":G.adaptationNodes.push(oe);break}return G},{adaptationNodes:[],protections:[]}),v={},_=Dl(f.getAttribute("IsLive")),R;if(_){let G=f.getAttribute("DVRWindowLength");G!==null&&!isNaN(+G)&&+G!=0&&(R=+G/g)}let k=T.reduce((G,ie)=>{let oe=a({root:ie,baseUrl:l,timescale:g,protections:b,isLive:_,timeShiftBufferDepth:R,manifestReceivedTime:c});if(oe===null)return G;let fe=oe.type,Re=G[fe];return Re===void 0?G[fe]=[oe]:Re.push(oe),G},v),x,P,M,L=null,F,D=k.video!==void 0?k.video[0]:void 0,B=k.audio!==void 0?k.audio[0]:void 0,A,C,N;if(D!==void 0||B!==void 0){let G=[],ie=[];if(D!==void 0){let oe=D.representations[0];if(oe!==void 0){let fe=oe.index.getFirstAvailablePosition(),Re=oe.index.getLastAvailablePosition();E(fe)||G.push(fe),E(Re)||ie.push(Re)}}if(B!==void 0){let oe=B.representations[0];if(oe!==void 0){let fe=oe.index.getFirstAvailablePosition(),Re=oe.index.getLastAvailablePosition();E(fe)||G.push(fe),E(Re)||ie.push(Re)}}G.length>0&&(A=Math.max(...G)),ie.length>0&&(C=Math.min(...ie),N=Math.max(...ie))}let K=f.getAttribute("Duration"),q=K!==null&&+K!=0?+K/g:void 0;if(_){x=n.suggestedPresentationDelay,P=e,M=A!=null?A:P;let G=N;G===void 0&&(G=Date.now()/1e3-P);let ie=C;ie===void 0&&(ie=G),F={isLinear:!0,maximumSafePosition:ie,livePosition:G,time:z()},L=R!=null?R:null}else{M=A!=null?A:0;let G=C;G===void 0&&(G=q!==void 0?M+q:1/0),F={isLinear:!1,maximumSafePosition:G,livePosition:void 0,time:z()}}let X=_?0:M,W=_?void 0:F.maximumSafePosition,H={availabilityStartTime:P===void 0?0:P,clockOffset:i,isLive:_,isDynamic:_,isLastPeriodKnown:!0,timeBounds:{minimumSafePosition:M,timeshiftDepth:L,maximumTimeData:F},periods:[{adaptations:k,duration:W!==void 0?W-X:q,end:W,id:"gen-smooth-period-0",start:X,thumbnailTracks:[]}],suggestedPresentationDelay:x,transportType:"smooth",uris:E(u)?[]:[u]};return pr(H),H}return s}function zb(n,e){if(n.length!==32)throw new Error("HSS: wrong system id length");return le("pssh",de([0,0,0,0],Xe(n),_e(e.length),e))}var Jm=Vb;var ep=Jm;function tp(n,e,t,r,i,o,a){return le("avc1",de(6,me(1),16,me(n),me(e),me(t),2,me(r),6,[0,1,i.length],Te(i),31-i.length,me(o),[255,255],a))}function np(n,e,t,r,i,o,a,s){return le("encv",de(6,me(1),16,me(n),me(e),me(t),2,me(r),6,[0,1,i.length],Te(i),31-i.length,me(o),[255,255],a,s))}function rp(n,e,t,r,i,o){return le("mp4a",de(6,me(n),8,me(e),me(t),2,me(r),me(i),2,o))}function ip(n,e,t,r,i,o,a){return le("enca",de(6,me(n),8,me(e),me(t),2,me(r),me(i),2,o,a))}function op(n){return le("dref",de(7,[1],n))}function ap(n,e){let t=de(...[Te(n),[0,0,0,1]].concat(e.map(Te)));return le("ftyp",t)}function Wa(n,e){return le("schm",de(4,Te(n),_e(e)))}function sp(n){return le("tfdt",de([1,0,0,0],nn(n)))}function dp(){let n=new Uint8Array(12);return n[3]=1,le("vmhd",n)}function up(n){return le("trex",de(4,_e(n),[0,0,0,1],12))}function lp(n){return le("free",new Uint8Array(n-8))}function cp(n,e){return le("esds",de(4,[3,25],me(n),[0,4,17,64,21],11,[5,2],Xe(e),[6,1,2]))}function Ha(n){return le("frma",Te(n))}function fp(n,e,t){let r;t===2?r=1:t===4?r=3:r=0;let i=n[1],o=n[2],a=n[3];return le("avcC",de([1,i,o,a,252|r,225],me(n.length),n,[1],me(e.length),e))}function mp(n){let e,t;switch(n){case"video":e="vide",t="VideoHandler";break;case"audio":e="soun",t="SoundHandler";break;default:e="hint",t="";break}return le("hdlr",de(8,Te(e),12,Te(t),1))}function pp(n){return le("mdhd",de(12,_e(n),8))}function gp(n,e){return le("mvhd",de(12,_e(n),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,me(e+1)))}function hp(n,e,t,r){return le("saio",de(4,[0,0,0,1],_e(n.length+e.length+t.length+r.length+8+8+8+8)))}function yp(n){if(n.length===0)return le("saiz",new Uint8Array(0));let e=J(n,0),t=J(n,4),r=new Uint8Array(t+9);r.set(_e(t),5);let i=9,o=8,a,s;for(;o<n.length;)o+=8,(e&2)===2?(s=2,a=Xo(n,o),o+=a*6+2):(a=0,s=0),r[i]=a*6+8+s,i++;return le("saiz",r)}function Ip(){return le("smhd",new Uint8Array(8))}function hr(n){let e=[7,[n.length]];return le("stsd",de(...e.concat(n)))}function bp(n,e,t){return le("tkhd",de(_e(7),8,_e(t),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],me(n),2,me(e),2))}function qa(n,e,t){return le("tenc",de(6,[n,e],t))}function Wb(n,e,t){return Ue("moov",[n,e,t])}function ho(n,e,t,r,i,o){let a=Ue("stbl",[t,le("stts",new Uint8Array(8)),le("stsc",new Uint8Array(8)),le("stsz",new Uint8Array(12)),le("stco",new Uint8Array(8))]),s=le("url ",new Uint8Array([0,0,0,1])),d=op(s),u=Ue("dinf",[d]),c=Ue("minf",[r,u,a]),l=mp(e),f=pp(n),p=Ue("mdia",[f,l,c]),h=bp(i,o,1),I=Ue("trak",[h,p]),g=up(1),b=Ue("mvex",[g]),T=gp(n,1),v=Wb(T,b,I),_=ap("isom",["isom","iso2","iso6","avc1","dash"]);return de(_,v)}var Hb=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];function Ll(n,e,t){let r=Hb.indexOf(e),i;return i=(n&63)<<4,i=(i|r&31)<<4,i=(i|t&31)<<3,Ne(me(i))}function Ga(n,e,t,r,i,o,a){let s=o.length===0?Ll(2,i,e):o,d=cp(1,s),u=(()=>{if(a===void 0){let g=rp(1,e,t,r,i,d);return hr([g])}let c=qa(1,8,a),l=Ue("schi",[c]),f=Wa("cenc",65536),p=Ha("mp4a"),h=Ue("sinf",[p,f,l]),I=ip(1,e,t,r,i,d,h);return hr([I])})();return ho(n,"audio",u,Ip(),0,0)}function ja(n,e,t,r,i,o,a,s){let[,d,u]=a.split("00000001");if(d===void 0||u===void 0)throw new Error("Smooth: unsupported codec private data.");let c=Xe(d),l=Xe(u),f=fp(c,l,o),p;if(s===void 0){let h=tp(e,t,r,i,"AVC Coding",24,f);p=hr([h])}else{let h=qa(1,8,s),I=Ue("schi",[h]),g=Wa("cenc",65536),b=Ha("avc1"),T=Ue("sinf",[b,g,I]),v=np(e,t,r,i,"AVC Coding",24,f,T);p=hr([v])}return ho(n,"video",p,dp(),e,t)}function Ya(n){let e=vn(n,3565190898,3392751253,2387879627,2655430559);if(e===void 0)return[];let t=[],r=e[0],i=e[4];for(let o=0;o<i;o++){let a,s;r===1?(s=qe(e,o*16+5),a=qe(e,o*16+5+8)):(s=J(e,o*8+5),a=J(e,o*8+5+4)),t.push({time:s,duration:a})}return t}function Qa(n){let e=vn(n,1830656773,1121273062,2162299933,2952222642);if(e!==void 0)return{duration:qe(e,12),time:qe(e,4)}}function Nl(){return V.browser!==V.BROWSERS.Ie11&&V.browser!==V.BROWSERS.OtherIeOrEdgePreEdgeChromium}function Ul(n,e,t,r,i){let o=[n,e,t];return i!==void 0&&o.push(le("senc",i),yp(i),hp(r,n,e,t)),Ue("traf",o)}function $a(n,e){let t=Ge(n,1836019558);if(t===null)throw new Error("Smooth: Invalid ISOBMFF given");let r=n.subarray(t[1],t[2]),i=Ls(r,1835427940),o=Ee(r,1953653094);if(o===null||i===null)throw new Error("Smooth: Invalid ISOBMFF given");let a=Ge(o,1952868452),s=Ge(o,1953658222);if(a===null||s===null)throw new Error("Smooth: Invalid ISOBMFF given");let d=o.subarray(a[0],a[2]),u=o.subarray(s[0],s[2]);d.set([0,0,0,1],a[1]-a[0]+4);let c=sp(e),l=qb(u,s[1]-s[0]),f=vn(o,2721664850,1520127764,2722393154,2086964724),p=Ul(d,c,l,i,f),h=Ue("moof",[i,p]),I=Ge(h,1836019558),g=Ge(p,1953653094),b=Ge(l,1953658222);if(I===null||g===null||b===null)throw new Error("Smooth: Invalid moof, trun or traf generation");let T=I[1]-I[0]+i.length+(g[1]-g[0])+d.length+c.length+(b[1]-b[0])+8,v=t[2]-t[0],_=h.length-v,R=Ge(n,1835295092);if(R===null)throw new Error("Smooth: Invalid ISOBMFF given");if(Nl()&&(_===0||_<=-8)){let k=R[1];return h.set(_e(k),T),n.set(h,t[0]),_<=-8&&n.set(lp(-_),h.length),n}else{let k=R[1]+_;h.set(_e(k),T);let x=new Uint8Array(n.length+_),P=n.subarray(0,t[0]),M=n.subarray(t[2],n.length);return x.set(P,0),x.set(h,P.length),x.set(M,P.length+h.length),x}}function qb(n,e){if((n[e+3]&1)>0)return n;let r=new Uint8Array(n.length+4);return r.set(n.subarray(0,e+8),0),r[e+3]=r[e+3]|1,r.set([0,0,0,0],e+8),r.set(n.subarray(e+8,n.length),e+12),Ks(r)}function Xa(n,e,t,r,i){var p;let o=[],a,s,d;if(i){let h=Wr(n);h!==null?(d=Ya(h),s=Qa(h)):m.warn("smooth","could not find traf atom")}if(d!==void 0)for(let h of d)o.push({time:h.time,duration:h.duration,timescale:t});if(s!==void 0)return a={time:s.time/t,duration:s.duration/t},{nextSegments:o,chunkInfos:a,scaledSegmentTime:s.time};if(e||!r.complete)return{nextSegments:o,chunkInfos:null,scaledSegmentTime:void 0};let u=r.duration*t,c=Math.min(t*.9,u/4),l=jr(n),f=((p=r.privateInfos)==null?void 0:p.smoothMediaSegment)!==void 0?r.privateInfos.smoothMediaSegment.time:Math.round(r.time*t);return l!==void 0&&Math.abs(l-u)<=c?a={time:r.time,duration:l/t}:a={time:r.time,duration:r.duration},{nextSegments:o,chunkInfos:a,scaledSegmentTime:f}}function Kn(n){return typeof n=="string"&&n.indexOf("mp4")>=0}async function Sp(n,e,t,r,i,o){var p,h;let a=((p=r.cmcdPayload)==null?void 0:p.type)==="headers"?r.cmcdPayload.value:void 0,s=e.segment.range,d;Array.isArray(s)?d=ue(ae({},a),{Range:et(s)}):a!==void 0&&(d=a);let u=((h=r.cmcdPayload)==null?void 0:h.type)==="query"?je(n,r.cmcdPayload.value):n,c=await ke({url:u,responseType:"arraybuffer",headers:d,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i,onProgress:t.onProgress});if(!Kn(e.mimeType)||o!==!0)return{resultType:"segment-loaded",resultData:c};let f=new Uint8Array(c.responseData);return dn(f,e.segment.isInit),{resultType:"segment-loaded",resultData:ue(ae({},c),{responseData:f})}}var Gb=({checkMediaSegmentIntegrity:n,segmentLoader:e})=>(t,r,i,o,a)=>{let{segment:s}=r;if(s.isInit){if(s.privateInfos===void 0||s.privateInfos.smoothInitSegment===void 0)throw new Error("Smooth: Invalid segment format");let d=s.privateInfos.smoothInitSegment,u,{codecPrivateData:c,timescale:l,height:f,width:p,protection:h={keyId:void 0,keySystems:void 0}}=d;if(c===void 0)throw new Error("Smooth: no codec private data.");switch(r.type){case"video":{u=ja(l,p!=null?p:0,f!=null?f:0,72,72,4,c,h.keyId);break}case"audio":{let{channels:I=0,bitsPerSample:g=0,packetSize:b=0,samplingRate:T=0}=d;u=Ga(l,I,g,b,T,c,h.keyId);break}default:y.CURRENT_ENV===y.DEV&&ne(!1,"responseData should have been set"),u=new Uint8Array(0)}return Promise.resolve({resultType:"segment-created",resultData:u})}else return t===null?Promise.resolve({resultType:"segment-created",resultData:null}):typeof e!="function"?Sp(t,r,a,i,o,n):new Promise((d,u)=>{let c=!1,I={reject:_=>{var P,M;if(c||o.isCancelled())return;c=!0,o.deregister(v);let R=_,k=(P=R==null?void 0:R.message)!=null?P:"Unknown error when fetching a Smooth segment through a custom segmentLoader.",x=new dt(k,(M=R==null?void 0:R.canRetry)!=null?M:!1,R==null?void 0:R.xhr);u(x)},resolve:_=>{if(c||o.isCancelled())return;c=!0,o.deregister(v);let R;_.data instanceof Uint8Array?_.data.buffer instanceof ArrayBuffer?R=_.data:R=_.data.slice():R=_.data,(!Kn(r.mimeType)||n!==!0)&&d({resultType:"segment-loaded",resultData:{responseData:R,size:_.size,requestDuration:_.duration}});let x=R instanceof Uint8Array?R:new Uint8Array(R);dn(x,r.segment.isInit),d({resultType:"segment-loaded",resultData:{responseData:x,size:_.size,requestDuration:_.duration}})},fallback:()=>{c||o.isCancelled()||(c=!0,o.deregister(v),Sp(t,r,a,i,o,n).then(d,u))},progress:_=>{c||o.isCancelled()||a.onProgress({duration:_.duration,size:_.size,totalSize:_.totalSize})}},g;r.segment.range!==void 0&&(g=[r.segment.range],r.segment.indexRange!==void 0&&g.push(r.segment.indexRange));let b={isInit:r.segment.isInit,timeout:i.timeout,byteRanges:g,trackType:r.type,url:t,cmcdPayload:i.cmcdPayload},T=e(b,I);o.register(v);function v(_){c||(c=!0,!c&&typeof T=="function"&&T(),u(_))}})},Tp=Gb;function Bl(n,e){return n===null?null:e.url===null?n.baseUrl:hn(n.baseUrl,e.url)}function Ep(n){let e=ep(n),t=Tp(n),r={customManifestLoader:n.manifestLoader},o={loadManifest:Gi(r,"text",null),parseManifest(d,u){var g;let c=(g=d.url)!=null?g:u.originalUrl,{receivedTime:l,responseData:f}=d,p=typeof f=="string"?new DOMParser().parseFromString(f,"text/xml"):f,h=e(p,c,l);return{manifest:new Jn(h,{representationFilter:n.representationFilter}),url:c}}},a={loadSegment(d,u,c,l,f){let p=Bl(d,u.segment);return t(p,u,c,l,f)},parseSegment(d,u,c){var R,k;let{segment:l}=u,{data:f,isChunked:p}=d;if(f===null)return l.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let h=f instanceof Uint8Array?f:new Uint8Array(f);if(l.isInit){let x=(k=(R=l.privateInfos)==null?void 0:R.smoothInitSegment)==null?void 0:k.timescale;return{segmentType:"init",initializationData:f,initializationDataSize:f.byteLength,initTimescale:x,protectionData:[]}}let I=c!==void 0?Xa(h,p,c,l,u.isLive):null;if(I===null||I.chunkInfos===null||I.scaledSegmentTime===void 0)throw new Error("Smooth Segment without time information");let{nextSegments:g,chunkInfos:b,scaledSegmentTime:T}=I,v=$a(h,T),_=g.length>0?g:void 0;return{segmentType:"media",chunkData:v,chunkInfos:b,chunkOffset:0,chunkSize:v.length,protectionData:[],predictedSegments:_,appendWindow:[void 0,void 0]}}};return{transportName:"smooth",manifest:o,audio:a,video:a,text:{loadSegment(d,u,c,l,f){var g,b,T,v;let{segment:p}=u,h=Bl(d,p);return p.isInit||h===null?Promise.resolve({resultType:"segment-created",resultData:null}):Kn(u.mimeType)?ke({url:((T=c.cmcdPayload)==null?void 0:T.type)==="query"?je(h,c.cmcdPayload.value):h,headers:((v=c.cmcdPayload)==null?void 0:v.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"arraybuffer",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(_=>{if(n.checkMediaSegmentIntegrity!==!0)return{resultType:"segment-loaded",resultData:_};let R=new Uint8Array(_.responseData);return dn(R,u.segment.isInit),{resultType:"segment-loaded",resultData:ue(ae({},_),{responseData:R})}}):ke({url:((g=c.cmcdPayload)==null?void 0:g.type)==="query"?je(h,c.cmcdPayload.value):h,headers:((b=c.cmcdPayload)==null?void 0:b.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"text",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(_=>({resultType:"segment-loaded",resultData:_}))},parseSegment(d,u,c){var F;let{segment:l,language:f,mimeType:p="",codecs:h=""}=u,I=Kn(u.mimeType),{data:g,isChunked:b}=d,T;if(l.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};if(g===null)return{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let v,_=null,R,k,x,P;if(I){let D;typeof g=="string"?D=Te(g):D=g instanceof Uint8Array?g:new Uint8Array(g),T=D.length;let B=c!==void 0?Xa(D,b,c,l,u.isLive):null;v=B==null?void 0:B.nextSegments,_=(F=B==null?void 0:B.chunkInfos)!=null?F:null,_===null?b?m.warn("smooth","Unavailable time data for current text track."):(R=l.time,k=l.end):(R=_.time,k=_.duration!==void 0?_.time+_.duration:l.end);let A=h.toLowerCase();if(p==="application/ttml+xml+mp4"||A==="stpp"||A==="stpp.ttml"||A==="stpp.ttml.im1t")P="ttml";else if(A==="wvtt")P="vtt";else throw new Error(`could not find a text-track parser for the type ${p}`);let C=Rn(D);x=C===null?"":ce(C)}else{R=l.time,k=l.end;let D;if(typeof g!="string"){let B=g instanceof Uint8Array?g:new Uint8Array(g);T=B.length,D=ce(B)}else D=g;switch(p){case"application/x-sami":case"application/smil":P="sami";break;case"application/ttml+xml":P="ttml";break;case"text/vtt":P="vtt";break}if(P===void 0)if(h.toLowerCase()==="srt")P="srt";else throw new Error(`could not find a text-track parser for the type ${p}`);x=D}let M=Array.isArray(v)&&v.length>0?v:void 0,L=R!=null?R:0;return{segmentType:"media",chunkData:{type:P,data:x,start:R,end:k,initTimescale:c!=null?c:null,language:f},chunkSize:T,chunkInfos:_,chunkOffset:L,protectionData:[],predictedSegments:M,appendWindow:[void 0,void 0]}}},thumbnails:{loadThumbnail:()=>Promise.reject(new Error("Thumbnail tracks aren't implemented with smooth")),parseThumbnail:()=>{throw new Error("Thumbnail tracks aren't implemented with smooth")}}}}var _p=Ep;function Fl(n){n.transports.smooth===void 0&&(n.transports.smooth=_p),n.mainThreadMediaSourceInit=Mn}function vp(){if(V.browser!==V.BROWSERS.Firefox)return m.warn("utils","getFirefoxVersion: Can't access Firefox version. Not a firefox browser."),null;let n=navigator.userAgent,e=/Firefox\/([0-9]+)\./.exec(n);if(e===null)return-1;let t=parseInt(e[1],10);return isNaN(t)?-1:t}function Kl(){if(V.browser!==V.BROWSERS.Firefox)return!0;let n=vp();if(n===null||n<67)return!0;let e=HTMLVideoElement==null?void 0:HTMLVideoElement.prototype;return(e==null?void 0:e.requirePictureInPicture)!==void 0}function yo(n){let e=n;if(typeof e.getStartDate=="function"){let t=e.getStartDate();if(typeof t=="object"&&t!==null){let r=+t;if(!isNaN(r))return r/1e3}else if(typeof t=="number"&&!isNaN(t))return t}}function Vl(){return V.device===V.DEVICES.PlayStation4&&typeof Worker=="object"||typeof Worker=="function"}var mn=class n extends Error{constructor(e,t){super(nt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="WorkerInitializationError",this.type="WORKER_INITIALIZATION_ERROR",this.code=e}};function Za(n,e,t){let r=e(n.getReference(),t);return{getCurrentTime(){return n.getCurrentTime()},getReadyState(){return n.getReadyState()},getPlaybackRate(){return n.getPlaybackRate()},getIsPaused(){return n.getIsPaused()},getReference(){return r},listen(i,o){t.isCancelled()||o.clearSignal.isCancelled()||r.onUpdate(i,{clearSignal:o.clearSignal,emitCurrentValue:o.includeLastObservation})},deriveReadOnlyObserver(i){return Za(this,i,t)}}}var jb=["canplay","ended","play","pause","seeking","seeked","loadedmetadata","ratechange"],Io=class{constructor(e,t){this._internalSeeksIncoming=[],this._mediaElement=e,this._withMediaSource=t.withMediaSource,this._lowLatencyMode=t.lowLatencyMode,this._canceller=new U,this._observationRef=this._createSharedReference(),this._expectedSeekingPosition=null,this._pendingSeek=null,this._isSeekBlocked=!1;let r=()=>{if(this._pendingSeek!==null&&!this._isSeekBlocked){let{position:i,isInternal:o}=this._pendingSeek;this._pendingSeek=null,this._actuallySetCurrentTime(i,o)}};e.addEventListener("loadedmetadata",r),this._canceller.signal.register(()=>{e.removeEventListener("loadedmetadata",r)})}stop(){this._canceller.cancel()}getCurrentTime(){return this._mediaElement.currentTime}getPlaybackRate(){return this._mediaElement.playbackRate}getIsPaused(){return this._mediaElement.paused}blockSeeking(){this._isSeekBlocked=!0}unblockSeeking(){if(this._isSeekBlocked&&(this._isSeekBlocked=!1,this._pendingSeek!==null&&this._mediaElement.readyState>=1)){let{position:e,isInternal:t}=this._pendingSeek;this._pendingSeek=null,this._actuallySetCurrentTime(e,t)}}isSeekingBlocked(){return this._isSeekBlocked}getPendingSeekInformation(){return this._pendingSeek}setCurrentTime(e,t=!0){!this._isSeekBlocked&&this._mediaElement.readyState>=1?this._actuallySetCurrentTime(e,t):(this._pendingSeek={position:e,isInternal:t},this._internalSeeksIncoming=[],this._isSeekBlocked||this._generateObservationForEvent("manual"))}setPlaybackRate(e){this._mediaElement.playbackRate=e}getReadyState(){return this._mediaElement.readyState}getReference(){return this._observationRef}listen(e,t){if(this._canceller.isUsed()||t.clearSignal.isCancelled())return te;this._observationRef.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return Za(this,e,this._canceller.signal)}_actuallySetCurrentTime(e,t){m.info("media","Actually seeking.",{time:e,isInternal:t}),t&&this._internalSeeksIncoming.push(e),this._mediaElement.currentTime=e}_createSharedReference(){if(this._observationRef!==void 0)return this._observationRef;let{SAMPLING_INTERVAL_MEDIASOURCE:e,SAMPLING_INTERVAL_LOW_LATENCY:t,SAMPLING_INTERVAL_NO_MEDIASOURCE:r}=O.getCurrent(),i=new j(this._getCurrentObservation("init"),this._canceller.signal),o;this._lowLatencyMode?o=t:this._withMediaSource?o=e:o=r;let a=()=>{this._generateObservationForEvent("timeupdate")},s=setInterval(a,o);return jb.map(u=>{let c=()=>{d(),this._generateObservationForEvent(u)};this._mediaElement.addEventListener(u,c),this._canceller.signal.register(()=>{this._mediaElement.removeEventListener(u,c)})}),this._canceller.signal.register(()=>{clearInterval(s),i.finish()}),i;function d(){clearInterval(s),s=setInterval(a,o)}}_getCurrentObservation(e){var v,_,R,k;let t=e,r=this._observationRef===void 0?Zb(this._mediaElement):this._observationRef.getValue(),i=!1,o=(_=(v=this._pendingSeek)==null?void 0:v.position)!=null?_:null,a=kp(this._mediaElement),{buffered:s,readyState:d,position:u,seeking:c}=a;if(t==="seeking")if(this._internalSeeksIncoming.length>0){i=!0,t="internal-seeking";let x=this._internalSeeksIncoming.shift();this._expectedSeekingPosition=Cn()?Math.max(u,x!=null?x:0):u}else this._expectedSeekingPosition=u;else c?this._expectedSeekingPosition=Math.max(u,(R=this._expectedSeekingPosition)!=null?R:0):Cn()&&this._expectedSeekingPosition!==null&&u<this._expectedSeekingPosition?o=this._expectedSeekingPosition:this._expectedSeekingPosition=null;c&&r.seeking===1&&e!=="seeking"&&(i=!0);let l=(k=this._expectedSeekingPosition)!=null?k:u,f,p;!this._withMediaSource&&s.length===0&&d>=3?(f=void 0,p=void 0):(f=ds(s,l),p=f!==null?f.end-l:1/0);let h=Yb(l,f,a.ended,a.duration,this._lowLatencyMode),I=Qb({previousObservation:r,currentObservation:a,basePosition:l,observationEvent:t,lowLatencyMode:this._lowLatencyMode,withMediaSource:this._withMediaSource,bufferGap:p,fullyLoaded:h}),g=$b(r,a,t,p),b;i?b=1:c?b=2:b=0;let T=Y({},a,{position:new or(a.position,o),event:t,seeking:b,rebuffering:I,freezing:g,bufferGap:p,currentRange:f,fullyLoaded:h});return m.hasLevel("DEBUG")&&m.debug("media","Current media element state tick.",{evt:T.event,position:T.position.getPolled(),seeking:T.seeking,internalSeek:i,rebuffering:T.rebuffering!==null,freezing:T.freezing!==null,ended:T.ended,paused:T.paused,playbackRate:T.playbackRate,readyState:T.readyState,pendingPosition:o}),T}_generateObservationForEvent(e){let t=this._getCurrentObservation(e);m.hasLevel("DEBUG")&&m.debug("media",`current playback timeline:
|
|
20
|
-
`+
|
|
21
|
-
${e}`),this._observationRef.setValue(t)}};function
|
|
22
|
-
`+r}function Zb(n){let e=kp(n);return Y(e,{rebuffering:null,event:"init",seeking:0,position:new or(e.position,null),freezing:null,bufferGap:0,currentRange:null,fullyLoaded:!1})}async function zl(n,e){let{time:t,container:r}=e;if(n===null||n.fetchThumbnailDataCallback===null||n.manifest===null)return Promise.reject(new gt("NO_CONTENT","Cannot get thumbnail: no content loaded"));let{thumbnailRequestsInfo:i,currentContentCanceller:o}=n,a=new U,s=a.linkToSignal(o.signal),d,u=i.pendingRequests.get(r);u==null||u.cancel(),i.pendingRequests.set(r,a);let c=()=>{s(),a.cancel(),i.pendingRequests.delete(r),setTimeout(()=>{d!==void 0&&URL.revokeObjectURL(d)},0)};try{let f=Hn(n.manifest,t);if(f===void 0)throw new gt("NO_THUMBNAIL","Wanted Period not found.");let p=f.thumbnailTracks,h=e.thumbnailTrackId!==void 0?Q(p,k=>k.id===e.thumbnailTrackId):p[0];if(h===void 0)throw e.thumbnailTrackId!==void 0?new gt("NO_THUMBNAIL","Given `thumbnailTrackId` not found"):new gt("NO_THUMBNAIL","Wanted Period has no thumbnail track.");let{lastResponse:I}=i,g;if(I!==null&&I.thumbnailTrackId===h.id&&I.periodId===f.id){let k=I.response.thumbnails;k.length>0&&t>=k[0].start&&t<k[k.length-1].end&&(g=I.response)}if(g===void 0&&(g=await n.fetchThumbnailDataCallback(f.id,h.id,t),i.lastResponse={response:g,periodId:f.id,thumbnailTrackId:h.id}),a.signal.cancellationError!==null)throw a.signal.cancellationError;let b=document.createElement("canvas"),T=b.getContext("2d");if(T===null)throw new gt("RENDERING","Cannot display thumbnail: cannot create canvas context");let v=Ie(g.thumbnails,k=>k.start<=t&&k.end>t);if(v<0)throw new Error("Cannot display thumbnail: time not found in fetched data");let _=new Image,R=new Blob([g.data],{type:g.mimeType});return d=URL.createObjectURL(R),_.src=d,b.height=g.thumbnails[v].height,b.width=g.thumbnails[v].width,new Promise((k,x)=>{_.onload=()=>{if(a.signal.cancellationError!==null){x(a.signal.cancellationError),c();return}try{T.drawImage(_,g.thumbnails[v].offsetX,g.thumbnails[v].offsetY,g.thumbnails[v].width,g.thumbnails[v].height,0,0,g.thumbnails[v].width,g.thumbnails[v].height),b.style.width="100%",b.style.height="100%",b.className="__rx-thumbnail__",l(),r.appendChild(b),k()}catch(P){x(new gt("RENDERING","Could not draw the image in a canvas:"+(P instanceof Error?P.toString():"Unknown Error")))}c()},_.onerror=()=>{if(a.signal.cancellationError!==null){x(a.signal.cancellationError),c();return}e.keepPreviousThumbnailOnError!==!0&&l(),x(new gt("RENDERING","Could not load the corresponding image in the DOM")),c()}})}catch(f){if(e.keepPreviousThumbnailOnError!==!0&&l(),f!==null&&f===a.signal.cancellationError)throw new gt("ABORTED","Thumbnail rendering has been aborted");let p=Me(f,{defaultCode:"NONE",defaultReason:"Unknown error"}),h;throw p.type==="NETWORK_ERROR"?h=new gt("LOADING",p.message):h=new gt("NOT_FOUND",p.message),c(),h}function l(){for(let f=r.children.length-1;f>=0;f--){let p=r.children[f];p.className==="__rx-thumbnail__"&&r.removeChild(p)}}}var gt=class n extends Error{constructor(e,t){super(nt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="ThumbnailRenderingError",this.code=e}};var bo=class extends se{constructor(e){super(),this._canceller=new U,this._adaptationRef=e,this._updateToken=!1,this._lastEmitted=void 0,this.refresh=te}hasSetTrack(){return this._adaptationRef.getValue()!==void 0}updateTrack(e){if(this._updateToken=!0,e===null){if(this._lastEmitted===null)return;this._updateToken=!1,this._canceller.cancel(),this._canceller=new U,this._lastEmitted=null,this._adaptationRef.setValue(null);return}let{adaptation:t,switchingMode:r,relativeResumingPosition:i}=e;this._canceller.cancel(),this._canceller=new U;let o=this._constructLockedRepresentationsReference(e);this._updateToken&&(this._lastEmitted={adaptation:t,switchingMode:r,lockedRepresentations:null},this._updateToken=!1,this._adaptationRef.setValue({adaptationId:t.id,switchingMode:r,representations:o,relativeResumingPosition:i}))}_constructLockedRepresentationsReference(e){let t=new j({representationIds:[],switchingMode:"lazy"}),r=this;return this.refresh=i,this._canceller.signal.register(o),e.lockedRepresentations.onUpdate(i,{clearSignal:this._canceller.signal,emitCurrentValue:!1}),i(),t;function i(){let a=e.lockedRepresentations.getValue(),s,d;if(a===null)d=e.adaptation.representations.filter(l=>Rt(l)===!0),s="lazy";else{let{representationIds:l}=a;if(s=a.switchingMode,d=e.adaptation.representations.filter(p=>$(l,p.id)).filter(p=>Rt(p)===!0),d.length===0){r.trigger("noPlayableLockedRepresentation",null);return}}if(d.length<=0){r.trigger("noPlayableRepresentation",null);return}let u=t.getValue(),c=d.map(l=>l.id).slice().sort();if(c.length!==u.representationIds.length){t.setValue({representationIds:c,switchingMode:s});return}for(let l=0;l<c.length;l++)if(u.representationIds[l]!==c[l]){t.setValue({representationIds:c,switchingMode:s});return}}function o(){r.refresh=te}}dispose(){this.removeEventListener(),this._canceller.cancel(),this._adaptationRef.finish()}};var So=class extends se{constructor(e){var t;super(),this._storedPeriodInfo=[],this._isDisposed=!1,this._cachedPeriodInfo=new WeakMap,this._isTrickModeTrackEnabled=e.preferTrickModeTracks,this._defaultAudioTrackSwitchingMode=(t=e.defaultAudioTrackSwitchingMode)!=null?t:O.getCurrent().DEFAULT_AUDIO_TRACK_SWITCHING_MODE,this.onTracksNotPlayableForType=e.onTracksNotPlayableForType}getAvailablePeriods(){return this._storedPeriodInfo.reduce((e,t)=>(t.isPeriodAdvertised&&e.push(jt(t.period)),e),[])}onManifestCodecSupportUpdate(){this._selectInitialTrackIfNeeded()}checkPeriodHasSupportedTrack(e,t){var d,u;let r=e.adaptations[t],i=[...(d=e.adaptations.audio)!=null?d:[],...(u=e.adaptations.video)!=null?u:[]];if(!(r!==void 0&&r.length>0))return;let a=r.every(c=>c.supportStatus.hasSupportedCodec===!1),s=i.every(c=>c.supportStatus.hasSupportedCodec===!1);if(a){let c=new re("MANIFEST_INCOMPATIBLE_CODECS_ERROR","No supported "+t+" adaptations",{tracks:void 0});if(s){if(this.trigger("error",c),this._isDisposed)return;this.dispose();return}else if(this.onTracksNotPlayableForType[t]==="continue")this.trigger("warning",c);else{if(this.trigger("error",c),this._isDisposed)return;this.dispose();return}}}onManifestUpdate(e){var o,a,s;let{periods:t}=e;if(y.CURRENT_ENV===y.DEV)for(let d=1;d<t.length;d++)ne(t[d-1].start<=t[d].start);let r=[];for(let d of t)if(["audio","video"].forEach(u=>{this.checkPeriodHasSupportedTrack(d,u)}),this._isDisposed)return;let i=0;for(let d=0;d<this._storedPeriodInfo.length;d++){let u=this._storedPeriodInfo[d].period,c=t[i];if(c===void 0)for(let l=this._storedPeriodInfo.length-1;l>=d;l--)this._storedPeriodInfo[l].inManifest=!1,Wl(this._storedPeriodInfo[l])&&this._removePeriodObject(l);else if(u===c)i++,this.resetSelectedTrackIfNotAvailableAnymore(this._storedPeriodInfo[d],c,"video"),this.resetSelectedTrackIfNotAvailableAnymore(this._storedPeriodInfo[d],c,"audio"),this.resetSelectedTrackIfNotAvailableAnymore(this._storedPeriodInfo[d],c,"text");else if(u.start<=c.start)this._storedPeriodInfo[d].inManifest=!1,Wl(this._storedPeriodInfo[d])&&(this._removePeriodObject(d),d--);else{let l=Hl(c,!0);this._storedPeriodInfo.splice(d,0,l),r.push(l),i++}}if(i<t.length){let d=t.slice(i).map(u=>Hl(u,!0));this._storedPeriodInfo.push(...d),r.push(...d)}for(let d of this._storedPeriodInfo)(o=d.audio.dispatcher)==null||o.refresh(),(a=d.video.dispatcher)==null||a.refresh(),(s=d.text.dispatcher)==null||s.refresh()}onDecipherabilityUpdates(){var e,t,r;for(let i of this._storedPeriodInfo)(e=i.audio.dispatcher)==null||e.refresh(),(t=i.video.dispatcher)==null||t.refresh(),(r=i.text.dispatcher)==null||r.refresh()}resetSelectedTrackIfNotAvailableAnymore(e,t,r){var d;let i=e[r].storedSettings;if(E(i))return;let o=Ot(t,r);if(o.some(u=>u.id===i.adaptation.id)||(m.warn("Track",`Chosen ${r} Adaptation not available anymore`),r==="video"?e.video.storedSettings=this.getDefaultStoredSettingsForAdaptation(o,"video"):r==="audio"?e.audio.storedSettings=this.getDefaultStoredSettingsForAdaptation(o,"audio"):r==="text"&&(e.text.storedSettings=this.getDefaultStoredSettingsForAdaptation(o,"text")),this.trigger("trackUpdate",{period:jt(t),trackType:r,reason:"missing"}),this._isDisposed))return;let s=xt(this._storedPeriodInfo,e.period.id);s!==void 0&&s.isPeriodAdvertised&&s[r].storedSettings===null&&((d=s[r].dispatcher)==null||d.updateTrack(null))}getDefaultStoredSettingsForAdaptation(e,t){let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:r}=O.getCurrent();if(t==="text"||e.length===0)return null;switch(t){case"text":return null;case"video":{let i=e[0],o=Ja(i,this._isTrickModeTrackEnabled),a=new j(null);return{adaptationBase:i,adaptation:o,switchingMode:r,lockedRepresentations:a}}case"audio":return{adaptation:e[0],switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new j(null)};default:ze(t)}}addTrackReference(e,t,r){m.debug("Track","Adding Track Reference",{bufferType:e,periodId:t.id});let i=xt(this._storedPeriodInfo,t.id);if(i===void 0){i=Hl(t,!1);let s=!1;for(let d=0;d<this._storedPeriodInfo.length;d++)this._storedPeriodInfo[d].period.start>t.start&&(this._storedPeriodInfo.splice(d,0,i),s=!0);s||this._storedPeriodInfo.push(i)}i[e].dispatcher!==null&&(m.error("Track","Subject already added for type and Period",{bufferType:e,periodId:t.id}),i[e].dispatcher.dispose());let o=new bo(r);if(i[e].dispatcher=o,o.addEventListener("noPlayableRepresentation",()=>{this.handleMissingOrUnplayableTrack(t,e,!1)}),o.addEventListener("noPlayableLockedRepresentation",()=>{i!==void 0&&(this.unlockVideoRepresentations(i),this.trigger("brokenRepresentationsLock",{period:{id:t.id,start:t.start,end:t.end},trackType:e}))}),this._selectInitialTrackIfNeeded(),this._shouldAdvertisePeriod(i)&&(i.isPeriodAdvertised=!0,this.trigger("newAvailablePeriods",[{id:t.id,start:t.start,end:t.end}]),this._isDisposed))return;let a=["audio","video","text"];for(let s of a){let d=i[s];if(i.isPeriodAdvertised&&d.dispatcher!==null&&!d.dispatcher.hasSetTrack()&&d.storedSettings!==void 0&&d.dispatcher.updateTrack(d.storedSettings),this._isDisposed)return}}throwIfTracksAreNotSetForPeriod(e){let t=xt(this._storedPeriodInfo,e.id);if(t!==void 0&&["audio","video"].every(i=>t[i].storedSettings===null)){let i=new re("NO_AUDIO_VIDEO_TRACKS","No audio and no video tracks are set.");this.trigger("error",i),this.dispose()}}handleMissingOrUnplayableTrack(e,t,r){var u,c,l,f;let{fallbackTrack:i,noSourceMedia:o}=Jb(e,t),a=(u=xt(this._storedPeriodInfo,e.id))==null?void 0:u[t];if(a===void 0){m.warn("Track","Could not find period",{periodId:e.id});return}let s=a.storedSettings,d=()=>a.storedSettings!==s;if(i!==null){let p;t==="audio"?p=this._defaultAudioTrackSwitchingMode:t==="text"?p="direct":p="reload";let h={adaptation:i,switchingMode:p,lockedRepresentations:new j(null)};if(a.storedSettings=h,r||this.trigger("trackUpdate",{period:jt(e),trackType:t,reason:"no-playable-representation"}),this._isDisposed)return;a.storedSettings===h&&((c=a.dispatcher)==null||c.updateTrack(h))}else if(i===null&&!o){if(this.trigger("noPlayableTrack",{trackType:t,period:{id:e.id,start:e.start,end:e.end}}),this._isDisposed)return;let p=this.onTracksNotPlayableForType[t];if(!d()){if(p==="continue")m.warn("Track",`No playable ${t}, continuing without ${t}`),a.storedSettings=null,r||this.trigger("trackUpdate",{period:jt(e),trackType:t,reason:"no-playable-representation"}),a.storedSettings!==null||this._isDisposed||(l=a.dispatcher)==null||l.updateTrack(null);else if(p==="error"){let h=new re("NO_PLAYABLE_REPRESENTATION",`No ${t} Representation can be played`,{tracks:void 0});this.trigger("error",h)}}}else i===null&&o&&(m.debug("Track",`The period does not have adaptation for ${t} there is no track to choose`),a.storedSettings=null,r||this.trigger("trackUpdate",{period:jt(e),trackType:t,reason:"no-playable-representation"}),a.storedSettings!==null||this._isDisposed||(f=a.dispatcher)==null||f.updateTrack(null));this._isDisposed||t!=="text"&&this.throwIfTracksAreNotSetForPeriod(e)}removeTrackReference(e,t){m.debug("Track","Removing Track Reference",{bufferType:e,periodId:t});let r;for(let a=0;a<this._storedPeriodInfo.length;a++)if(this._storedPeriodInfo[a].period.id===t){r=a;break}if(r===void 0){m.warn("Track","type not found for period",{bufferType:e,periodId:t});return}let i=this._storedPeriodInfo[r],o=i[e];if((o==null?void 0:o.dispatcher)===null){m.warn("Track","TrackDispatcher already removed for type and Period",{bufferType:e,periodId:t});return}o.dispatcher.dispose(),o.dispatcher=null,Wl(i)&&this._removePeriodObject(r)}getPeriodObjectFromPeriod(e){let t=xt(this._storedPeriodInfo,e.id);return t===void 0&&e!==void 0?this._cachedPeriodInfo.get(e):t}getPeriodObjectFromId(e){return xt(this._storedPeriodInfo,e)}disableVideoTrickModeTracks(){this._isTrickModeTrackEnabled&&(this._isTrickModeTrackEnabled=!1,this._resetVideoTrackChoices("trickmode-disabled"))}enableVideoTrickModeTracks(){this._isTrickModeTrackEnabled||(this._isTrickModeTrackEnabled=!0,this._resetVideoTrackChoices("trickmode-enabled"))}resetPeriodObjects(){var e,t,r;m.debug("Track","Resetting Period Objects");for(let i=this._storedPeriodInfo.length-1;i>=0;i--){let o=this._storedPeriodInfo[i];(e=o.audio.dispatcher)==null||e.dispose(),o.audio.dispatcher=null,(t=o.video.dispatcher)==null||t.dispose(),o.video.dispatcher=null,(r=o.text.dispatcher)==null||r.dispose(),o.text.dispatcher=null,o.inManifest||this._removePeriodObject(i)}}isTrickModeEnabled(){return this._isTrickModeTrackEnabled}setAudioTrack(e){let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;return this._setAudioOrTextTrack({bufferType:"audio",periodRef:t,trackId:r,switchingMode:i!=null?i:this._defaultAudioTrackSwitchingMode,lockedRepresentations:o,relativeResumingPosition:a})}setTextTrack(e,t){return this._setAudioOrTextTrack({bufferType:"text",periodRef:e,trackId:t,switchingMode:"direct",lockedRepresentations:null,relativeResumingPosition:void 0})}_setAudioOrTextTrack({bufferType:e,periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}){var p,h;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Q((p=s.adaptations[e])!=null?p:[],({id:I,supportStatus:g})=>g.hasSupportedCodec!==!1&&g.isDecipherable!==!1&&I===r);if(d===void 0)throw new Error(`Wanted ${e} track not found.`);let u=t[e],c;if(o===null)c=new j(null);else{let I=this._getRepresentationsToLock(d,o),g=e==="audio"?this._defaultAudioTrackSwitchingMode:"direct";c=new j({representationIds:I,switchingMode:g})}let l={adaptation:d,switchingMode:i,lockedRepresentations:c,relativeResumingPosition:a};if(u.storedSettings=l,this.trigger("trackUpdate",{period:jt(s),trackType:e,reason:"manual"}),this._isDisposed)return;let f=xt(this._storedPeriodInfo,s.id);f!==void 0&&f[e].storedSettings===l&&((h=f[e].dispatcher)==null||h.updateTrack(l))}setVideoTrack(e){var I,g;let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Q((I=s.adaptations.video)!=null?I:[],({id:b,supportStatus:T})=>T.isDecipherable!==!1&&T.hasSupportedCodec!==!1&&b===r);if(d===void 0)throw new Error("Wanted video track not found.");let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:u}=O.getCurrent(),c=t.video,l=Ja(d,this._isTrickModeTrackEnabled),f;if(o===null)f=new j(null);else{let b=this._getRepresentationsToLock(d,o),T=u;f=new j({representationIds:b,switchingMode:T})}let p={adaptationBase:d,switchingMode:i!=null?i:u,adaptation:l,relativeResumingPosition:a,lockedRepresentations:f};if(c.storedSettings=p,this.trigger("trackUpdate",{period:jt(s),trackType:"video",reason:"manual"}),this._isDisposed)return;let h=xt(this._storedPeriodInfo,s.id);h!==void 0&&h.video.storedSettings===p&&((g=h.video.dispatcher)==null||g.updateTrack(p))}disableTrack(e,t){var o,a;if(!e.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let r=e[t];if(r.storedSettings===null||(t!=="text"&&((o=e[t].storedSettings)==null||o.lockedRepresentations.finish()),r.storedSettings=null,this.trigger("trackUpdate",{period:jt(e.period),trackType:t,reason:"manual"}),this._isDisposed))return;let i=xt(this._storedPeriodInfo,e.period.id);if(i!==void 0&&i[t].storedSettings===null&&((a=i[t].dispatcher)==null||a.updateTrack(null)),i!==void 0&&["audio","video"].every(d=>i[d].storedSettings===null)){let d=new re("NO_AUDIO_VIDEO_TRACKS","No audio and no video tracks are set.");this.trigger("error",d),this.dispose();return}}getChosenAudioTrack(e,t){return E(e.audio.storedSettings)?null:Lo(e.audio.storedSettings.adaptation,t)}getChosenTextTrack(e){return E(e.text.storedSettings)?null:No(e.text.storedSettings.adaptation)}getChosenVideoTrack(e,t){return E(e.video.storedSettings)?null:Uo(e.video.storedSettings.adaptation,t)}getAvailableAudioTracks(e,t){let r=e.audio.storedSettings,i=E(r)?null:r.adaptation.id;return Ot(e.period,"audio").map(a=>{let s=i===null?!1:i===a.id;return Y(Lo(a,t),{active:s})})}getAvailableTextTracks(e){let t=e.text.storedSettings,r=E(t)?null:t.adaptation.id;return Ot(e.period,"text").map(o=>{let a=r===null?!1:r===o.id;return Y(No(o),{active:a})})}getAvailableVideoTracks(e,t){let r=e.video.storedSettings,i=E(r)?void 0:r.adaptation.id;return Ot(e.period,"video").map(a=>{let s=i===null?!1:i===a.id,d=Uo(a,t),u=d.trickModeTracks!==void 0?d.trickModeTracks.map(l=>{let f=i===null?!1:i===l.id;return Y(l,{active:f})}):[],c=Y(d,{active:s});return u!==void 0&&(c.trickModeTracks=u),c})}getLockedAudioRepresentations(e){let{storedSettings:t}=e.audio;if(E(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}getLockedVideoRepresentations(e){let{storedSettings:t}=e.video;if(E(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}lockAudioRepresentations(e,t){var s;let{storedSettings:r}=e.audio;if(E(r))return;let{DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:i}=O.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}lockVideoRepresentations(e,t){var s;let{storedSettings:r}=e.video;if(E(r))return;let{DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:i}=O.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}unlockAudioRepresentations(e){let{storedSettings:t}=e.audio;E(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}unlockVideoRepresentations(e){let{storedSettings:t}=e.video;E(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}dispose(){for(this._isDisposed=!0;;){let e=this._storedPeriodInfo.pop();if(e===void 0)return;e.isRemoved=!0}}_resetVideoTrackChoices(e){var r;for(let i=0;i<this._storedPeriodInfo.length;i++){let o=this._storedPeriodInfo[i];if(!E(o.video.storedSettings)){let a=o.video.storedSettings.adaptationBase;if(a!==null){let s=Ja(a,this._isTrickModeTrackEnabled);o.video.storedSettings.adaptationBase=a,o.video.storedSettings.adaptation=s}}}let t=this._storedPeriodInfo.slice();for(let i=0;i<t.length;i++){let o=t[i].period,s=t[i].video.storedSettings;if(s!==void 0){if(this.trigger("trackUpdate",{period:jt(o),trackType:"video",reason:e}),this._isDisposed)return;let d=xt(this._storedPeriodInfo,o.id);d!==void 0&&d.isPeriodAdvertised&&d.video.storedSettings===s&&((r=d.video.dispatcher)==null||r.updateTrack(s))}}}_removePeriodObject(e){ne(e<this._storedPeriodInfo.length);let t=this._storedPeriodInfo[e];this._storedPeriodInfo[e].isRemoved=!0,this._storedPeriodInfo.splice(e,1),this._cachedPeriodInfo.set(t.period,t)}_getRepresentationsToLock(e,t){let r=t.reduce((i,o)=>{let a=Q(e.representations,s=>s.id===o);return a===void 0?m.warn("Track","Wanted locked Representation not found."):i.push(a.id),i},[]);if(r.length===0)throw new Error("Cannot lock Representations: None of the given Representation id are found");return r}_selectInitialTrackIfNeeded(){var i,o,a,s;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:e}=O.getCurrent(),t=[],r=[];for(let d of this._storedPeriodInfo){let{period:u}=d;if(d.audio.storedSettings!==void 0&&d.video.storedSettings!==void 0&&d.text.storedSettings!==void 0)continue;let c=[...(i=u.adaptations.audio)!=null?i:[],...(o=u.adaptations.video)!=null?o:[]],l=c.every(g=>g.supportStatus.hasCodecWithUndefinedSupport);if(c.length>0&&l)continue;let f=Ot(u,"audio")[0];if(f===void 0){if(d.audio.storedSettings=null,this.handleMissingOrUnplayableTrack(u,"audio",!0),this._isDisposed)return}else d.audio.storedSettings={adaptation:f,switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new j(null)};let p=Ot(u,"video")[0];if(p===void 0){if(d.video.storedSettings=null,this.handleMissingOrUnplayableTrack(u,"video",!0),this._isDisposed)return}else{let g=Ja(p,this._isTrickModeTrackEnabled);d.video.storedSettings={adaptation:g,adaptationBase:p,switchingMode:e,lockedRepresentations:new j(null)}}let h=null,I=((a=u.adaptations.text)!=null?a:[]).filter(g=>g.isForcedSubtitles===!0);if(I.length>0){if(f!=null){let g=Q(I,b=>b.normalizedLanguage===f.normalizedLanguage);g!==void 0&&(h=g)}h===null&&(h=(s=Q(I,g=>g.normalizedLanguage===void 0))!=null?s:null)}d.text.storedSettings=h===null?null:{adaptation:h,switchingMode:"direct",lockedRepresentations:new j(null)},r.push(d),this._shouldAdvertisePeriod(d)&&(d.isPeriodAdvertised=!0,t.push({id:u.id,start:u.start,end:u.end}))}if(!(t.length>0&&(this.trigger("newAvailablePeriods",t),this._isDisposed)))for(let d of r){if(!d.isPeriodAdvertised)continue;let u=["audio","video","text"];for(let c of u){let l=d[c];if(l.dispatcher!==null&&l.storedSettings!==void 0&&!l.dispatcher.hasSetTrack()&&(l.dispatcher.updateTrack(l.storedSettings),this._isDisposed))return}}}_shouldAdvertisePeriod(e){return!e.isPeriodAdvertised&&e.text.dispatcher!==null&&e.video.dispatcher!==null&&e.audio.dispatcher!==null}};function xt(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.period.id===e)return r}}function Wl(n){var e,t,r;return!n.inManifest&&((e=n.text)==null?void 0:e.dispatcher)===null&&((t=n.audio)==null?void 0:t.dispatcher)===null&&((r=n.video)==null?void 0:r.dispatcher)===null}function Ja(n,e){var t;return e&&((t=n.trickModeTracks)==null?void 0:t[0])!==void 0?n.trickModeTracks[0]:n}function Hl(n,e){return{period:n,inManifest:e,isPeriodAdvertised:!1,isRemoved:!1,audio:{storedSettings:void 0,dispatcher:null},video:{storedSettings:void 0,dispatcher:null},text:{storedSettings:void 0,dispatcher:null}}}function jt(n){return{start:n.start,end:n.end,id:n.id}}function Jb(n,e){if(!(n.adaptations[e]!==void 0&&n.adaptations[e].length>0))return{fallbackTrack:null,noSourceMedia:!0};let r=eS(n,e);return{fallbackTrack:r!=null?r:null,noSourceMedia:!1}}function eS(n,e){var r;return Q((r=n.adaptations[e])!=null?r:[],i=>i.supportStatus.hasSupportedCodec===!1||i.supportStatus.isDecipherable===!1?!1:i.representations.filter(a=>Rt(a)===!0).length>0)}var Pp=So;function Cp(n){let e,t,r,i,o,a,{DEFAULT_BASE_BANDWIDTH:s,DEFAULT_VIDEO_RESOLUTION_LIMIT:d,DEFAULT_MAX_BUFFER_AHEAD:u,DEFAULT_MAX_BUFFER_BEHIND:c,DEFAULT_MAX_VIDEO_BUFFER_SIZE:l,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:f,DEFAULT_WANTED_BUFFER_AHEAD:p}=O.getCurrent();if(E(n.maxBufferAhead))e=u;else if(e=Number(n.maxBufferAhead),isNaN(e))throw new Error("Invalid maxBufferAhead parameter. Should be a number.");if(E(n.maxBufferBehind))t=c;else if(t=Number(n.maxBufferBehind),isNaN(t))throw new Error("Invalid maxBufferBehind parameter. Should be a number.");if(E(n.wantedBufferAhead))r=p;else if(r=Number(n.wantedBufferAhead),isNaN(r))throw new Error("Invalid wantedBufferAhead parameter. Should be a number.");if(E(n.maxVideoBufferSize))i=l;else if(i=Number(n.maxVideoBufferSize),isNaN(i))throw new Error("Invalid maxVideoBufferSize parameter. Should be a number.");let h=E(n.videoResolutionLimit)?d:n.videoResolutionLimit,I=E(n.throttleVideoBitrateWhenHidden)?f:!!n.throttleVideoBitrateWhenHidden;if(E(n.videoElement))o=document.createElement("video");else if(n.videoElement.nodeName.toLowerCase()==="video"||n.videoElement.nodeName.toLowerCase()==="audio")o=n.videoElement;else throw new Error("Invalid videoElement parameter. Should be a HTMLMediaElement.");if(E(n.baseBandwidth))a=s;else if(a=Number(n.baseBandwidth),isNaN(a))throw new Error("Invalid baseBandwidth parameter. Should be a number.");return{maxBufferAhead:e,maxBufferBehind:t,videoResolutionLimit:h,videoElement:o,wantedBufferAhead:r,maxVideoBufferSize:i,throttleVideoBitrateWhenHidden:I,baseBandwidth:a}}function Ap(n){var e,t,r,i;if(n===null||typeof n!="object"&&n!==void 0)throw new Error("API: reload - Invalid options format.");if((n==null?void 0:n.reloadAt)===null||typeof(n==null?void 0:n.reloadAt)!="object"&&(n==null?void 0:n.reloadAt)!==void 0)throw new Error("API: reload - Invalid 'reloadAt' option format.");if(typeof((e=n==null?void 0:n.reloadAt)==null?void 0:e.position)!="number"&&((t=n==null?void 0:n.reloadAt)==null?void 0:t.position)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.position' option format.");if(typeof((r=n==null?void 0:n.reloadAt)==null?void 0:r.relative)!="number"&&((i=n==null?void 0:n.reloadAt)==null?void 0:i.relative)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.relative' option format.");if(!Array.isArray(n==null?void 0:n.keySystems)&&(n==null?void 0:n.keySystems)!==void 0)throw new Error("API: reload - Invalid 'keySystems' option format.");if((n==null?void 0:n.autoPlay)!==void 0&&typeof n.autoPlay!="boolean")throw new Error("API: reload - Invalid 'autoPlay' option format.")}function Mp(n){var P,M,L,F;let e,t,r,i,o,a,s,{DEFAULT_AUTO_PLAY:d,DEFAULT_CODEC_SWITCHING_BEHAVIOR:u,DEFAULT_ENABLE_FAST_SWITCHING:c,DEFAULT_TEXT_TRACK_MODE:l,DEFAULT_AUDIO_TRACKS_NOT_PLAYABLE_BEHAVIOR:f,DEFAULT_VIDEO_TRACKS_NOT_PLAYABLE_BEHAVIOR:p}=O.getCurrent();if(E(n))throw new Error("No option set on loadVideo");if(!E(n.url))e=String(n.url);else if(E(n.initialManifest)&&E(n.manifestLoader))throw new Error("Unable to load a content: no url set on loadVideo.\nPlease provide at least either an `url` argument, a `initialManifest` option or a `manifestLoader` option so the RxPlayer can load the content.");if(E(n.transport))throw new Error("No transport set on loadVideo");t=String(n.transport);let h=E(n.autoPlay)?d:!!n.autoPlay;if(E(n.keySystems))r=[];else{r=Array.isArray(n.keySystems)?n.keySystems:[n.keySystems];for(let D of r)if(typeof D.type!="string"||typeof D.getLicense!="function")throw new Error("Invalid key system given: Missing type string or getLicense callback")}let I=n.lowLatencyMode===void 0?!1:!!n.lowLatencyMode,g=n.initialManifest,b=(P=n.minimumManifestUpdateInterval)!=null?P:0,T=(M=n.defaultAudioTrackSwitchingMode)!=null?M:void 0;T!==void 0&&!$(["seamless","direct","reload"],T)&&(m.warn("API","The `defaultAudioTrackSwitchingMode` loadVideo option must match one of the following strategy name:\n- `seamless`\n- `direct`\n- `reload`"),T=void 0);let v=E(n.onCodecSwitch)?u:n.onCodecSwitch;$(["continue","reload"],v)||(m.warn("API","The `onCodecSwitch` loadVideo option must match one of the following string:\n- `continue`\n- `reload`\nIf badly set, "+u+" will be used as default"),v=u);let _=E(n.onAudioTracksNotPlayable)?f:n.onAudioTracksNotPlayable;$(["continue","error"],_)||(m.warn("API","The `onAudioTracksNotPlayable` loadVideo option must match one of the following string:\n- `continue`\n- `error`\nIf badly set, "+f+" will be used as default"),_=f);let R=E(n.onVideoTracksNotPlayable)?p:n.onVideoTracksNotPlayable;if($(["continue","error"],R)||(m.warn("API","The `onVideoTracksNotPlayable` loadVideo option must match one of the following string:\n- `continue`\n- `error`\nIf badly set, "+p+" will be used as default"),R=p),E(n.textTrackMode))i=l;else{if(n.textTrackMode!=="native"&&n.textTrackMode!=="html")throw new Error("Invalid textTrackMode.");i=n.textTrackMode}if(i==="html"){if(E(n.textTrackElement))throw new Error('You have to provide a textTrackElement in "html" textTrackMode.');if(n.textTrackElement instanceof HTMLElement)a=n.textTrackElement;else throw new Error("textTrackElement should be an HTMLElement.")}else E(n.textTrackElement)||m.warn("API",'You have set a textTrackElement without being in an "html" textTrackMode. It will be ignored.');if(E(n.mode))o="auto";else{if(!$(["auto","multithread","main"],n.mode))throw new Error("Invalid `mode` option.");o=n.mode}let k=E(n.enableFastSwitching)?c:n.enableFastSwitching;if(!E(n.startAt))if("wallClockTime"in n.startAt&&n.startAt.wallClockTime instanceof Date){let D=n.startAt.wallClockTime.getTime()/1e3;s=Y({},n.startAt,{wallClockTime:D})}else s=n.startAt;let x=(L=n.requestConfig)!=null?L:{};return{__priv_patchLastSegmentInSidx:n.__priv_patchLastSegmentInSidx,__priv_manifestUpdateUrl:n.__priv_manifestUpdateUrl,checkMediaSegmentIntegrity:n.checkMediaSegmentIntegrity,checkManifestIntegrity:n.checkManifestIntegrity,autoPlay:h,defaultAudioTrackSwitchingMode:T,enableFastSwitching:k,initialManifest:g,keySystems:r,lowLatencyMode:I,manifestLoader:n.manifestLoader,minimumManifestUpdateInterval:b,requestConfig:x,onCodecSwitch:v,onAudioTracksNotPlayable:_,onVideoTracksNotPlayable:R,referenceDateTime:n.referenceDateTime,representationFilter:n.representationFilter,segmentLoader:n.segmentLoader,serverSyncInfos:n.serverSyncInfos,startAt:s,textTrackElement:a,textTrackMode:i,transport:t,mode:o,url:e,cmcd:n.cmcd,experimentalOptions:{enableRepresentationAvoidance:((F=n.experimentalOptions)==null?void 0:F.enableRepresentationAvoidance)===!0}}}function ql(n){return!(n&&(V.browser===V.BROWSERS.SafariMobile||V.browser===V.BROWSERS.SafariDesktop))}function xp(n,e,t,r){if(r.isCancelled())return;let i=n.getReference().getValue().seeking===2;i&&(e(),r.isCancelled())||n.listen(o=>{o.event==="seeking"?(i=!0,e()):i&&o.event==="seeked"&&(i=!1,t())},{includeLastObservation:!0,clearSignal:r})}function wp(n,e,t,r){r.isCancelled()||n===null||(n.addEventListener("play",e),n.addEventListener("pause",t),r.register(()=>{n.removeEventListener("play",e),n.removeEventListener("pause",t)}))}function Op(n,e,t,r,i){let o=new j("LOADING",i);n.addEventListener("loaded",()=>{if(o.getValue()==="LOADING"){if(o.setValue("LOADED"),!i.isCancelled()){let d=Gl(e,null,r,o.getValue());d!=="PAUSED"&&o.setValue(d)}}else o.getValue()==="RELOADING"?o.setValue(Gl(e,null,r,o.getValue())):s(null)},i),n.addEventListener("reloadingMediaSource",()=>{yr(o.getValue())&&o.setValueIfChanged("RELOADING")},i);let a=null;return n.addEventListener("stalled",d=>{d!==a&&(s(d),a=d)},i),n.addEventListener("unstalled",()=>{a!==null&&(s(null),a=null)},i),t.listen(d=>{$(["seeking","ended","play","pause"],d.event)&&s(a)},{clearSignal:i}),o;function s(d){if(!yr(o.getValue()))return;let u=Gl(e,d,r,o.getValue());o.getValue()==="LOADED"&&u==="PAUSED"||o.setValueIfChanged(u)}}function Gl(n,e,t,r){let{FORCED_ENDED_THRESHOLD:i}=O.getCurrent();if(n.ended)return"ENDED";if(e!==null){let o=Math.abs(n.duration-n.currentTime);return!E(i)&&o<i?"ENDED":e==="seeking"?"SEEKING":e==="freezing"?"FREEZING":r==="LOADED"&&!ql(t)?"LOADED":"BUFFERING"}return n.paused?"PAUSED":"PLAYING"}function yr(n){return n!=="LOADING"&&n!=="RELOADING"&&n!=="STOPPED"}var jl=Z,To=typeof jl.__RX_PLAYER_DEBUG_MODE__=="boolean"&&jl.__RX_PLAYER_DEBUG_MODE__;try{Object.defineProperty(jl,"__RX_PLAYER_DEBUG_MODE__",{get(){return To},set(n){To=n,n&&(Ir.LogLevel="DEBUG",Ir.LogFormat="full")}})}catch(n){}To?m.setLevel("DEBUG","full"):y.CURRENT_ENV===y.DEV&&m.setLevel(S.CURRENT_LEVEL,"standard");var tS=rt(),nS=["manifestLoader","segmentLoader"],Yt=class Yt extends se{static get ErrorTypes(){return tt}static get ErrorCodes(){return gs}static get LogLevel(){return m.getLevel()}static set LogLevel(e){m.setLevel(e,m.getFormat())}static get LogFormat(){return m.getFormat()}static set LogFormat(e){m.setLevel(m.getLevel(),e)}static addFeatures(e){ya(e)}static _priv_registerVideoElement(e){Yt._priv_currentlyUsedVideoElements.has(e)&&console.warn(`The video element is already attached to another RxPlayer instance.
|
|
23
|
-
Make sure to dispose the previous instance with player.dispose() before creating a new player instance attaching that video element.`),Yt._priv_currentlyUsedVideoElements.add(e)}static _priv_deregisterVideoElement(e){Yt._priv_currentlyUsedVideoElements.has(e)&&Yt._priv_currentlyUsedVideoElements.delete(e)}constructor(e={}){super();let{baseBandwidth:t,videoResolutionLimit:r,maxBufferAhead:i,maxBufferBehind:o,throttleVideoBitrateWhenHidden:a,videoElement:s,wantedBufferAhead:d,maxVideoBufferSize:u}=Cp(e);s.preload="auto",this.version="4.4.0",this.log=m,this.state="STOPPED",this.videoElement=s,Yt._priv_registerVideoElement(this.videoElement);let c=new U;this._destroyCanceller=c,this._priv_pictureInPictureRef=Lc(s,c.signal),this._priv_speed=new j(s.playbackRate,this._destroyCanceller.signal),this._priv_preferTrickModeTracks=!1,this._priv_contentLock=new j(!1,this._destroyCanceller.signal),this._priv_bufferOptions={wantedBufferAhead:new j(d,this._destroyCanceller.signal),maxBufferAhead:new j(i,this._destroyCanceller.signal),maxBufferBehind:new j(o,this._destroyCanceller.signal),maxVideoBufferSize:new j(u,this._destroyCanceller.signal)},this._priv_bitrateInfos={lastBitrates:{audio:t,video:t}},this._priv_throttleVideoBitrateWhenHidden=a,this._priv_videoResolutionLimit=r,this._priv_currentError=null,this._priv_contentInfos=null,this._priv_contentEventsMemory={},this._priv_reloadingMetadata={},this._priv_lastAutoPlay=!1,this._priv_worker=null;let l=()=>{this.trigger("volumeChange",{volume:s.volume,muted:s.muted})};s.addEventListener("volumechange",l),c.signal.register(()=>{s.removeEventListener("volumechange",l)})}attachWorker(e){return new Promise((t,r)=>{var a;if(!Vl())return m.warn("API","Cannot rely on a WebWorker: Worker API unavailable"),r(new mn("INCOMPATIBLE_ERROR","Worker unavailable"));if(this._priv_worker!==null){if(this.state!=="STOPPED")return m.warn("API","Cannot attach a new worker while a content is playing, please stop the player first."),r(new mn("SETUP_ERROR","Cannot attach a new worker while a content is playing"));this._priv_worker.terminate()}if(typeof e.workerUrl=="string")this._priv_worker=new Worker(e.workerUrl);else{let s=URL.createObjectURL(e.workerUrl);this._priv_worker=new Worker(s),URL.revokeObjectURL(s)}this._priv_worker.onerror=s=>{this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null),m.error("API","Unexpected worker error",s.error instanceof Error?s.error:void 0),r(new mn("UNKNOWN_ERROR",'Unexpected Worker "error" event'))};let i=s=>{let d=s.data;d.type==="init-error"?(m.warn("API","Processing InitError worker message: detaching worker"),this._priv_worker!==null&&(this._priv_worker.removeEventListener("message",i),this._priv_worker.terminate(),this._priv_worker=null),r(new mn("SETUP_ERROR","Worker parser initialization failed: "+d.value.errorMessage))):d.type==="init-success"&&(m.info("API","InitSuccess received from worker."),this._priv_worker!==null&&this._priv_worker.removeEventListener("message",i),t())};this._priv_worker.addEventListener("message",i),m.debug("M-->C","Sending message",{name:"init"}),this._priv_worker.postMessage({type:"init",value:{dashWasmUrl:e.dashWasmUrl,logLevel:m.getLevel(),logFormat:m.getFormat(),sendBackLogs:To,date:Date.now(),timestamp:z(),hasVideo:((a=this.videoElement)==null?void 0:a.nodeName.toLowerCase())==="video"}}),m.addEventListener("onLogLevelChange",s=>{this._priv_worker!==null&&(m.debug("M-->C","Sending message",{name:"log-level-update"}),this._priv_worker.postMessage({type:"log-level-update",value:{logLevel:s.level,logFormat:s.format,sendBackLogs:To}}))},this._destroyCanceller.signal);let o=s=>{this._priv_worker!==null&&(m.debug("M-->C","Sending message:",{name:"config-update"}),this._priv_worker.postMessage({type:"config-update",value:s}))};O.updated&&o(O.getCurrent()),O.addEventListener("update",o,this._destroyCanceller.signal)})}getCurrentModeInformation(){return this._priv_contentInfos===null?null:{isDirectFile:this._priv_contentInfos.isDirectFile,useWorker:this._priv_contentInfos.useWorker}}addEventListener(e,t){return super.addEventListener(e,t)}stop(){this._priv_contentInfos!==null&&this._priv_contentInfos.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this.state!=="STOPPED"&&this._priv_setPlayerState("STOPPED")}dispose(){this.stop(),this.videoElement!==null&&(Yt._priv_deregisterVideoElement(this.videoElement),qn(this.videoElement).catch(e=>{let t=e instanceof Error?e.message:"Unknown error";m.error("API","Could not dispose decryption resources: "+t)})),this._destroyCanceller.cancel(),this._priv_reloadingMetadata={},this.videoElement=null,this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null)}loadVideo(e){let t=Mp(e);m.info("API","Calling loadvideo",{url:t.url,transport:t.transport}),this._priv_reloadingMetadata={options:t},this._priv_initializeContentPlayback(t),this._priv_lastAutoPlay=t.autoPlay}reload(e){var c,l,f;let{options:t,manifest:r,reloadPosition:i,reloadInPause:o}=this._priv_reloadingMetadata;if(t===void 0)throw new Error("API: Can't reload without having previously loaded a content.");Ap(e);let a;if(((c=e==null?void 0:e.reloadAt)==null?void 0:c.position)!==void 0)a={position:e.reloadAt.position};else if(((l=e==null?void 0:e.reloadAt)==null?void 0:l.relative)!==void 0){if(i===void 0)throw new Error("Can't reload to a relative position when previous content was not loaded.");a={position:e.reloadAt.relative+i}}else i!==void 0&&(a={position:i});let s;(e==null?void 0:e.autoPlay)!==void 0?s=e.autoPlay:o!==void 0&&(s=!o);let d;(e==null?void 0:e.keySystems)!==void 0?d=e.keySystems:((f=this._priv_reloadingMetadata.options)==null?void 0:f.keySystems)!==void 0&&(d=this._priv_reloadingMetadata.options.keySystems);let u=ue(ae({},t),{initialManifest:r});a!==void 0&&(u.startAt=a),s!==void 0&&(u.autoPlay=s),d!==void 0&&(u.keySystems=d),this._priv_initializeContentPlayback(u)}createDebugElement(e){if(pe.createDebugElement===null)throw new Error("Feature `DEBUG_ELEMENT` not added to the RxPlayer");let t=new U;return pe.createDebugElement(e,this,t.signal),{dispose(){t.cancel()}}}getAvailableThumbnailTracks({time:e,periodId:t}={}){if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return[];let{manifest:r}=this._priv_contentInfos,i;if(e!==void 0){if(i=Hn(this._priv_contentInfos.manifest,e),i===void 0||i.thumbnailTracks.length===0)return[]}else if(t!==void 0){if(i=Q(r.periods,o=>o.id===t),i===void 0)return m.error("API","getAvailableThumbnailTracks: periodId not found",{periodId:t}),[]}else{let{currentPeriod:o}=this._priv_contentInfos;if(o===null)return[];i=o}return i.thumbnailTracks.map(o=>({id:o.id,width:Math.floor(o.width/o.horizontalTiles),height:Math.floor(o.height/o.verticalTiles),mimeType:o.mimeType}))}async renderThumbnail(e){if(E(e.time))throw new Error("You have to provide a `time` property to `renderThumbnail`, indicating the wanted thumbnail time in seconds.");if(E(e.container))throw new Error("You have to provide a `container` property to `renderThumbnail`, specifying the HTML Element in which the thumbnail should be inserted.");return zl(this._priv_contentInfos,e)}_priv_initializeContentPlayback(e){var oe,fe,Re,ge,he,_t;let{autoPlay:t,cmcd:r,defaultAudioTrackSwitchingMode:i,enableFastSwitching:o,initialManifest:a,keySystems:s,lowLatencyMode:d,minimumManifestUpdateInterval:u,requestConfig:c,onCodecSwitch:l,startAt:f,transport:p,checkMediaSegmentIntegrity:h,checkManifestIntegrity:I,manifestLoader:g,referenceDateTime:b,segmentLoader:T,serverSyncInfos:v,mode:_,experimentalOptions:R,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x,url:P,onAudioTracksNotPlayable:M,onVideoTracksNotPlayable:L}=e;if(this.videoElement===null)throw new Error("the attached video element is disposed");let F=p==="directfile",D=new U,B=this.videoElement,A,C=!1,N=null;if(F){if(pe.directfile===null)throw this.stop(),this._priv_currentError=null,new Error("DirectFile feature not activated in your build.");if(E(P))throw new Error("No URL for a DirectFile content");if(m.info("API","Initializing DirectFile mode in the main thread"),N=this._priv_initializeMediaElementTracksStore(D.signal),D.isUsed())return;A=new pe.directfile.initDirectFile({autoPlay:t,keySystems:s,speed:this._priv_speed,startAt:f,url:P})}else{let ee={lowLatencyMode:d,maxRetry:(oe=c.manifest)==null?void 0:oe.maxRetry,requestTimeout:(fe=c.manifest)==null?void 0:fe.timeout,connectionTimeout:(Re=c.manifest)==null?void 0:Re.connectionTimeout,minimumManifestUpdateInterval:u,initialManifest:a},ye=Kl(),ot={throttleBitrate:{},limitResolution:{}};this._priv_throttleVideoBitrateWhenHidden&&(ye?ot.throttleBitrate={video:gn(Nc(this._priv_pictureInPictureRef,D.signal),Qt=>Qt?1/0:0,D.signal)}:m.warn("API","Can't apply throttleVideoBitrateWhenHidden because browser can't be trusted for visibility.")),this._priv_videoResolutionLimit==="videoElement"?ye?ot.limitResolution={video:Bc(B,this._priv_pictureInPictureRef,D.signal)}:m.warn("API","Can't apply videoResolutionLimit because browser can't be trusted for video size."):this._priv_videoResolutionLimit==="screen"&&(ot.limitResolution={video:Uc(D.signal)});let pn={initialBitrates:this._priv_bitrateInfos.lastBitrates,lowLatencyMode:d,throttlers:ot},ht=e.textTrackMode==="native"?{textTrackMode:"native"}:{textTrackMode:"html",textTrackElement:e.textTrackElement},yt=Y({enableFastSwitching:o,onCodecSwitch:l},this._priv_bufferOptions),Yl={lowLatencyMode:d,maxRetry:(ge=c.segment)==null?void 0:ge.maxRetry,requestTimeout:(he=c.segment)==null?void 0:he.timeout,connectionTimeout:(_t=c.segment)==null?void 0:_t.connectionTimeout},Lp=pe.multithread!==null&&this._priv_worker!==null&&this.videoElement.FORCED_MEDIA_SOURCE===void 0&&p==="dash"&&nS.every(Qt=>E(e[Qt]))&&typeof e.representationFilter!="function";if(_==="main"||_==="auto"&&!Lp){if(pe.mainThreadMediaSourceInit===null)throw new Error("Cannot load video, neither in a WebWorker nor with the `MEDIA_SOURCE_MAIN` feature");let Qt=pe.transports[p];if(typeof Qt!="function")throw this.stop(),this._priv_currentError=null,new Error(`transport "${p}" not supported`);let Np=typeof e.representationFilter=="string"?Mc(e.representationFilter):e.representationFilter;m.info("API","Initializing MediaSource mode in the main thread");let Up=Qt({lowLatencyMode:d,checkMediaSegmentIntegrity:h,checkManifestIntegrity:I,manifestLoader:g,referenceDateTime:b,representationFilter:Np,segmentLoader:T,serverSyncInfos:v,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x});A=new pe.mainThreadMediaSourceInit({adaptiveOptions:pn,autoPlay:t,bufferOptions:yt,cmcd:r,enableRepresentationAvoidance:R.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transport:Up,manifestRequestSettings:ee,segmentRequestOptions:Yl,speed:this._priv_speed,startAt:f,textTrackOptions:ht,url:P})}else{if(pe.multithread===null)throw new Error("Cannot load video in multithread mode: `MULTI_THREAD` feature not imported.");if(this._priv_worker===null)throw new Error("Cannot load video in multithread mode: `attachWorker` method not called.");ne(typeof e.representationFilter!="function"),C=!0,m.info("API","Initializing MediaSource mode in a WebWorker");let Qt={lowLatencyMode:d,checkMediaSegmentIntegrity:h,checkManifestIntegrity:I,referenceDateTime:b,serverSyncInfos:v,manifestLoader:void 0,segmentLoader:void 0,representationFilter:e.representationFilter,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x};A=new pe.multithread.init({adaptiveOptions:pn,autoPlay:t,bufferOptions:yt,cmcd:r,enableRepresentationAvoidance:R.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transportOptions:Qt,manifestRequestSettings:ee,segmentRequestOptions:Yl,speed:this._priv_speed,startAt:f,textTrackOptions:ht,worker:this._priv_worker,url:P,useMseInWorker:vm})}}let K=new Io(B,{withMediaSource:!F,lowLatencyMode:d});K.blockSeeking(),D.signal.register(()=>{K.stop()});let q={contentId:tS(),originalUrl:P,playbackObserver:K,currentContentCanceller:D,defaultAudioTrackSwitchingMode:i,initializer:A,isDirectFile:F,manifest:null,currentPeriod:null,activeAdaptations:null,activeRepresentations:null,tracksStore:null,mediaElementTracksStore:N,useWorker:C,segmentSinkMetricsCallback:null,fetchThumbnailDataCallback:null,thumbnailRequestsInfo:{pendingRequests:new WeakMap,lastResponse:null},onAudioTracksNotPlayable:M,onVideoTracksNotPlayable:L};A.addEventListener("error",ee=>{this._priv_onFatalError(ee,q)}),A.addEventListener("warning",ee=>{let ye=Me(ee,{defaultCode:"NONE",defaultReason:"An unknown error happened."});m.warn("API","Sending warning:",ye),this.trigger("warning",ye)}),A.addEventListener("reloadingMediaSource",ee=>{q.tracksStore!==null&&q.tracksStore.resetPeriodObjects(),this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=null),this._priv_lastAutoPlay=ee.autoPlay}),A.addEventListener("inbandEvents",ee=>this.trigger("inbandEvents",ee)),A.addEventListener("streamEvent",ee=>this.trigger("streamEvent",ee)),A.addEventListener("streamEventSkip",ee=>this.trigger("streamEventSkip",ee)),A.addEventListener("activePeriodChanged",ee=>this._priv_onActivePeriodChanged(q,ee)),A.addEventListener("periodStreamReady",ee=>this._priv_onPeriodStreamReady(q,ee)),A.addEventListener("periodStreamCleared",ee=>this._priv_onPeriodStreamCleared(q,ee)),A.addEventListener("representationChange",ee=>this._priv_onRepresentationChange(q,ee)),A.addEventListener("adaptationChange",ee=>this._priv_onAdaptationChange(q,ee)),A.addEventListener("bitrateEstimateChange",ee=>this._priv_onBitrateEstimateChange(ee)),A.addEventListener("manifestReady",ee=>this._priv_onManifestReady(q,ee)),A.addEventListener("manifestUpdate",ee=>this._priv_onManifestUpdate(q,ee)),A.addEventListener("codecSupportUpdate",()=>this._priv_onCodecSupportUpdate(q)),A.addEventListener("decipherabilityUpdate",ee=>this._priv_onDecipherabilityUpdate(q,ee)),A.addEventListener("loaded",ee=>{this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=ee.getSegmentSinkMetrics,this._priv_contentInfos.fetchThumbnailDataCallback=ee.getThumbnailData)}),A.prepare(),this.stop();let X=Op(A,B,K,F,D.signal);D.signal.register(()=>{A.dispose()});let W=ee=>{switch(ee){case"STOPPED":case"RELOADING":case"LOADING":break;case"ENDED":this._priv_reloadingMetadata.reloadInPause=!0,this._priv_reloadingMetadata.reloadPosition=K.getReference().getValue().position.getPolled();break;default:{let ye=K.getReference().getValue();this._priv_reloadingMetadata.reloadInPause=ye.paused,this._priv_reloadingMetadata.reloadPosition=ye.position.getWanted();break}}},H=null,G=ee=>{H!==null&&(H.cancel(),H=null),X.onUpdate((ye,ot)=>{yr(ye)&&(ot(),H!==null&&H.cancel(),H=new U,H.linkToSignal(D.signal),ee!==!B.paused&&(B.paused?this.trigger("pause",null):this.trigger("play",null)),wp(B,()=>this.trigger("play",null),()=>this.trigger("pause",null),D.signal))},{emitCurrentValue:!1,clearSignal:D.signal})};G(t),A.addEventListener("reloadingMediaSource",ee=>{G(ee.autoPlay)}),this._priv_currentError=null,this._priv_contentInfos=q;let ie=null;X.onUpdate(ee=>{W(ee),this._priv_setPlayerState(ee),!D.isUsed()&&(ie!==null?yr(this.state)||(ie.cancel(),ie=null):yr(this.state)&&(ie=new U,ie.linkToSignal(D.signal),xp(K,()=>this.trigger("seeking",null),()=>this.trigger("seeked",null),ie.signal)))},{emitCurrentValue:!0,clearSignal:D.signal}),K.listen(ee=>{W(this.state),this._priv_triggerPositionUpdate(q,ee)},{clearSignal:D.signal}),D.signal.register(()=>{A.removeEventListener()}),this._priv_contentLock.onUpdate((ee,ye)=>{ee||(ye(),A.start(B,K))},{emitCurrentValue:!0,clearSignal:D.signal})}getError(){return this._priv_currentError}getVideoElement(){return this.videoElement}getPlayerState(){return this.state}isContentLoaded(){return!$(["LOADING","RELOADING","STOPPED"],this.state)}isBuffering(){return $(["BUFFERING","SEEKING","LOADING","RELOADING"],this.state)}isPaused(){return this.videoElement!==null?$(["LOADING","RELOADING"],this.state)?!this._priv_lastAutoPlay:this.videoElement.paused:!0}isLive(){if(this._priv_contentInfos===null)return!1;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;return e||t===null?!1:t.isLive}areTrickModeTracksEnabled(){return this._priv_preferTrickModeTracks}getContentUrls(){if(this._priv_contentInfos===null)return;let{isDirectFile:e,manifest:t,originalUrl:r}=this._priv_contentInfos;if(e)return r===void 0?void 0:[r];if(t!==null)return t.uris}updateContentUrls(e,t){if(this._priv_contentInfos===null)throw new Error("No content loaded");let r=(t==null?void 0:t.refresh)===!0;this._priv_contentInfos.initializer.updateContentUrls(e,r)}getMediaDuration(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}getCurrentBufferGap(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement,t=pc(e.buffered,e.currentTime);return t===1/0?0:t}getWallClockTime(){if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)return this.videoElement.currentTime;let e=this.getWallClockOffset();return this.videoElement.currentTime+e}getWallClockOffset(){var r;if(this.videoElement===null||this._priv_contentInfos===null)return 0;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){let i=yo(this.videoElement);return i!=null?i:0}return t!==null&&(r=t.availabilityStartTime)!=null?r:0}getPosition(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.currentTime}getLastStoredContentPosition(){return this._priv_reloadingMetadata.reloadPosition}getPlaybackRate(){return this._priv_speed.getValue()}setPlaybackRate(e,t){var o;e!==this._priv_speed.getValue()&&this._priv_speed.setValue(e);let r=t==null?void 0:t.preferTrickModeTracks;if(typeof r!="boolean")return;this._priv_preferTrickModeTracks=r;let i=(o=this._priv_contentInfos)==null?void 0:o.tracksStore;E(i)||(r&&!i.isTrickModeEnabled()?i.enableVideoTrickModeTracks():!r&&i.isTrickModeEnabled()&&i.disableVideoTrickModeTracks())}getVideoRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return E(e.video)?e.video:In(e.video)}getAudioRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return E(e.audio)?e.video:Bo(e.audio)}play(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement.play();return E(e)||typeof e.catch!="function"?Promise.resolve():e.catch(t=>{if(t.name==="NotAllowedError"){let r=new re("MEDIA_ERR_PLAY_NOT_ALLOWED",t.toString());this.trigger("warning",r)}throw t})}pause(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.pause()}seekTo(e){var o;if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)throw new Error("player: no content loaded");let{isDirectFile:t,manifest:r}=this._priv_contentInfos,i;if(typeof e=="number")i=e;else if(typeof e=="object"){let a=e,s=this.videoElement.currentTime;if(!E(a.relative))i=s+a.relative;else if(!E(a.position))i=a.position;else{if(E(a.wallClockTime))throw new Error('invalid time object. You must set one of the following properties: "relative", "position" or "wallClockTime"');if(r!==null)i=a.wallClockTime-((o=r.availabilityStartTime)!=null?o:0);else if(t){if(this.videoElement!==null){let d=yo(this.videoElement);d!==void 0&&(i=a.wallClockTime-d)}}else throw new Error("Cannot seek: wallClockTime asked but Manifest not yet loaded.");i===void 0&&(i=a.wallClockTime)}}if(i===void 0)throw new Error("invalid time given");return m.info("API","API seekTo",{positionWanted:i}),this._priv_contentInfos.playbackObserver.setCurrentTime(i,!1),i}getVolume(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.volume}setVolume(e){if(this.videoElement===null)throw new Error("Disposed player");let t=this.videoElement;e!==t.volume&&(t.volume=e)}isMute(){var e;return((e=this.videoElement)==null?void 0:e.muted)===!0}mute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted||(this.videoElement.muted=!0)}unMute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted&&(this.videoElement.muted=!1)}setMaxBufferBehind(e){this._priv_bufferOptions.maxBufferBehind.setValue(e)}setMaxBufferAhead(e){this._priv_bufferOptions.maxBufferAhead.setValue(e)}setWantedBufferAhead(e){this._priv_bufferOptions.wantedBufferAhead.setValue(e)}setMaxVideoBufferSize(e){this._priv_bufferOptions.maxVideoBufferSize.setValue(e)}getMaxBufferBehind(){return this._priv_bufferOptions.maxBufferBehind.getValue()}getMaxBufferAhead(){return this._priv_bufferOptions.maxBufferAhead.getValue()}getWantedBufferAhead(){return this._priv_bufferOptions.wantedBufferAhead.getValue()}getMaxVideoBufferSize(){return this._priv_bufferOptions.maxVideoBufferSize.getValue()}getCurrentPeriod(){var t;let e=(t=this._priv_contentInfos)==null?void 0:t.currentPeriod;return E(e)?null:{id:e.id,start:e.start,end:e.end}}getKeySystemConfiguration(){if(this.videoElement===null)throw new Error("Disposed player");let e=Zn(this.videoElement);return e===null?null:{keySystem:e[0],configuration:e[1]}}getAvailablePeriods(){if(this._priv_contentInfos===null)return[];let{isDirectFile:e,tracksStore:t}=this._priv_contentInfos;return e?[]:t===null?[]:t.getAvailablePeriods().slice()}getAvailableAudioTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableAudioTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var c;return(c=d.getAvailableAudioTracks(u,o))!=null?c:[]})}getAvailableTextTracks(e){var i;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?(i=r==null?void 0:r.getAvailableTextTracks())!=null?i:[]:this._priv_callTracksStoreGetterSetter(e,[],(o,a)=>{var s;return(s=o.getAvailableTextTracks(a))!=null?s:[]})}getAvailableVideoTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableVideoTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var c;return(c=d.getAvailableVideoTracks(u,o))!=null?c:[]})}getAudioTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenAudioTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenAudioTrack(d,o))}getTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?r===null?void 0:r.getChosenTextTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.getChosenTextTrack(o))}getVideoTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenVideoTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenVideoTrack(d,o))}setAudioTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let c=typeof e=="string"?e:e.trackId;r==null||r.setAudioTrackById(c);return}catch(c){throw new Error("player: unknown audio track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(c,l)=>c.setAudioTrack({periodRef:l,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}setTextTrack(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let a=typeof e=="string"?e:e.trackId;r==null||r.setTextTrackById(a);return}catch(a){throw new Error("player: unknown text track")}let i,o;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.setTextTrack(s,o))}disableTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t){r==null||r.disableTextTrack();return}return this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"text"))}setVideoTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let c=typeof e=="string"?e:e.trackId;r==null||r.setVideoTrackById(c);return}catch(c){throw new Error("player: unknown video track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(c,l)=>c.setVideoTrack({periodRef:l,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}disableVideoTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t&&r!==null?r.disableVideoTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"video"))}lockVideoRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock video Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockVideoRepresentations(s,{representations:r,switchingMode:o}))}disableAudioTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t&&r!==null?r.disableAudioTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"audio"))}lockAudioRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock audio Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockAudioRepresentations(s,{representations:r,switchingMode:o}))}getLockedVideoRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedVideoRepresentations(i))}getLockedAudioRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedAudioRepresentations(i))}unlockVideoRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockVideoRepresentations(i))}unlockAudioRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockAudioRepresentations(i))}getMinimumPosition(){if(this._priv_contentInfos===null)return null;if(this._priv_contentInfos.isDirectFile)return 0;let{manifest:e}=this._priv_contentInfos;return e!==null?bn(e):null}getLivePosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(!e)return(t==null?void 0:t.isLive)!==!0?null:Sn(t)}getMaximumPosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}return t!==null?!t.isDynamic&&this.videoElement!==null?this.videoElement.duration:kt(t):null}async __priv_getSegmentSinkMetrics(){var e,t;return(t=(e=this._priv_contentInfos)==null?void 0:e.segmentSinkMetricsCallback)==null?void 0:t.call(e)}__priv_getManifest(){return this._priv_contentInfos===null?null:this._priv_contentInfos.manifest}__priv_getCurrentAdaptation(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeAdaptations:t}=this._priv_contentInfos;return e===null||t===null||E(t[e.id])?null:t[e.id]}__priv_getCurrentRepresentations(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeRepresentations:t}=this._priv_contentInfos;return e===null||t===null||E(t[e.id])?null:t[e.id]}_priv_cleanUpCurrentContentState(){var t,r,i,o;m.debug("API","Locking `contentLock` to clean-up the current content."),this._priv_contentLock.setValue(!0),(r=(t=this._priv_contentInfos)==null?void 0:t.tracksStore)==null||r.dispose(),(o=(i=this._priv_contentInfos)==null?void 0:i.mediaElementTracksStore)==null||o.dispose(),this._priv_contentInfos=null,this._priv_contentEventsMemory={};let e=()=>{this.videoElement!==null&&(m.debug("API","Unlocking `contentLock`. Next content can begin."),this._priv_contentLock.setValue(!1))};E(this.videoElement)?e():zo(this.videoElement).then(()=>{m.debug("API","DRM session cleaned-up with success!"),e()},a=>{m.error("API","An error arised when trying to clean-up the DRM session:"+(a instanceof Error?a.toString():"Unknown Error")),e()})}_priv_onManifestReady(e,t){var i;if(e.contentId!==((i=this._priv_contentInfos)==null?void 0:i.contentId))return;e.manifest=t,t.manifestFormat===0&&(this._priv_reloadingMetadata.manifest=t);let r=new Pp({preferTrickModeTracks:this._priv_preferTrickModeTracks,defaultAudioTrackSwitchingMode:e.defaultAudioTrackSwitchingMode,onTracksNotPlayableForType:{audio:e.onAudioTracksNotPlayable,video:e.onVideoTracksNotPlayable,text:"continue"}});e.tracksStore=r,r.addEventListener("newAvailablePeriods",o=>{this.trigger("newAvailablePeriods",o)}),r.addEventListener("brokenRepresentationsLock",o=>{this.trigger("brokenRepresentationsLock",o)}),r.addEventListener("trackUpdate",o=>{var s,d;this.trigger("trackUpdate",o);let a=(d=(s=this._priv_contentInfos)==null?void 0:s.currentPeriod)!=null?d:void 0;o.reason==="no-playable-representation"&&o.period.id===(a==null?void 0:a.id)&&this._priv_onAvailableTracksMayHaveChanged(o.trackType)}),r.addEventListener("warning",o=>{this.trigger("warning",o)}),r.addEventListener("error",o=>{this._priv_onFatalError(o,e)}),r.addEventListener("noPlayableTrack",o=>{this.trigger("noPlayableTrack",o)}),r.onManifestUpdate(t)}_priv_onManifestUpdate(e,t){var o,a,s;if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return;E(e==null?void 0:e.tracksStore)||e.tracksStore.onManifestUpdate(this._priv_contentInfos.manifest);let r=(a=(o=this._priv_contentInfos)==null?void 0:o.currentPeriod)!=null?a:void 0,i=(s=this._priv_contentInfos)==null?void 0:s.tracksStore;if(!(r===void 0||E(i))){for(let d of t.updatedPeriods)if(d.period.id===r.id&&(d.result.addedAdaptations.length>0||d.result.removedAdaptations.length>0)){if(i.getPeriodObjectFromPeriod(r)===void 0)return;this._priv_onAvailableTracksMayHaveChanged("audio"),this._priv_onAvailableTracksMayHaveChanged("text"),this._priv_onAvailableTracksMayHaveChanged("video")}}}_priv_onCodecSupportUpdate(e){let t=e==null?void 0:e.tracksStore;E(t)||t.onManifestCodecSupportUpdate()}_priv_onDecipherabilityUpdate(e,t){if(e===null||e.manifest===null)return;E(e==null?void 0:e.tracksStore)||e.tracksStore.onDecipherabilityUpdates();let r=t.reduce((i,o)=>{var s,d,u;if(!(Q(i,c=>c[0].id===o.period.id&&c[1]===o.adaptation.type)!==void 0)){let c=e.tracksStore;if(c===null)return i;let l=!1,f=c.getPeriodObjectFromPeriod(o.period);if(f===void 0)return i;switch(o.adaptation.type){case"audio":l=((s=c.getChosenAudioTrack(f,!1))==null?void 0:s.id)===o.adaptation.id;break;case"video":l=((d=c.getChosenVideoTrack(f,!1))==null?void 0:d.id)===o.adaptation.id;break;case"text":l=((u=c.getChosenTextTrack(f))==null?void 0:u.id)===o.adaptation.id;break}l&&i.push([o.period,o.adaptation.type])}return i},[]);for(let[i,o]of r)this._priv_triggerEventIfNotStopped("representationListUpdate",{period:{start:i.start,end:i.end,id:i.id},trackType:o,reason:"decipherability-update"},e.currentContentCanceller.signal)}_priv_onActivePeriodChanged(e,{period:t}){var s,d,u,c,l,f;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;e.currentPeriod=t;let r=e.currentContentCanceller.signal;this._priv_contentEventsMemory.periodChange!==t&&(this._priv_contentEventsMemory.periodChange=t,this._priv_triggerEventIfNotStopped("periodChange",{start:t.start,end:t.end,id:t.id},r)),this._priv_triggerEventIfNotStopped("availableAudioTracksChange",this.getAvailableAudioTracks(),r),this._priv_triggerEventIfNotStopped("availableTextTracksChange",this.getAvailableTextTracks(),r),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",this.getAvailableVideoTracks(),r);let i=(d=this._priv_contentInfos)==null?void 0:d.tracksStore;if(E(i))this._priv_triggerEventIfNotStopped("audioTrackChange",null,r),this._priv_triggerEventIfNotStopped("textTrackChange",null,r),this._priv_triggerEventIfNotStopped("videoTrackChange",null,r);else{let p=i.getPeriodObjectFromPeriod(t);if(p!==void 0){let h=i.getChosenAudioTrack(p,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",h,r);let I=i.getChosenTextTrack(p);this._priv_triggerEventIfNotStopped("textTrackChange",I,r);let g=i.getChosenVideoTrack(p,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",g,r)}}let o=(c=(u=this.__priv_getCurrentRepresentations())==null?void 0:u.audio)!=null?c:null;this._priv_triggerEventIfNotStopped("audioRepresentationChange",E(o)?o:In(o),r);let a=(f=(l=this.__priv_getCurrentRepresentations())==null?void 0:l.video)!=null?f:null;this._priv_triggerEventIfNotStopped("videoRepresentationChange",E(a)?a:In(a),r)}_priv_onPeriodStreamReady(e,t){var s;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{type:r,period:i,adaptationRef:o}=t,a=e.tracksStore;switch(r){case"video":case"audio":case"text":E(a)?(m.error("API",`TracksStore not instanciated for a new ${r} period`),o.setValue(null)):a.addTrackReference(r,i,o);break;default:ze(r)}}_priv_onPeriodStreamCleared(e,t){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;let{type:r,periodId:i}=t,o=e.tracksStore;switch(r){case"audio":case"text":case"video":E(o)||o.removeTrackReference(r,i);break}let{activeAdaptations:a,activeRepresentations:s}=e;if(!E(a)&&!E(a[i])){let u=a[i];delete u[r],Object.keys(u).length===0&&delete a[i]}if(!E(s)&&!E(s[i])){let u=s[i];delete u[r],Object.keys(u).length===0&&delete s[i]}}_priv_onAdaptationChange(e,{type:t,adaptation:r,period:i}){var c;if(e.contentId!==((c=this._priv_contentInfos)==null?void 0:c.contentId))return;e.activeAdaptations===null&&(e.activeAdaptations={});let{activeAdaptations:o,currentPeriod:a}=e,s=o[i.id];E(s)?o[i.id]={[t]:r}:s[t]=r;let{tracksStore:d}=e,u=e.currentContentCanceller.signal;if(d!==null&&a!==null&&!E(i)&&i.id===a.id){let l=d.getPeriodObjectFromPeriod(i);if(l===void 0)return;switch(t){case"audio":{let f=d.getChosenAudioTrack(l,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",f,u);break}case"text":{let f=d.getChosenTextTrack(l);this._priv_triggerEventIfNotStopped("textTrackChange",f,u);break}case"video":{let f=d.getChosenVideoTrack(l,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",f,u);break}}}}_priv_onRepresentationChange(e,{type:t,period:r,representation:i}){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;e.activeRepresentations===null&&(e.activeRepresentations={});let{activeRepresentations:o,currentPeriod:a}=e,s=o[r.id];if(E(s)?o[r.id]={[t]:i}:s[t]=i,!E(r)&&a!==null&&a.id===r.id){let u=this._priv_contentInfos.currentContentCanceller.signal;t==="video"?this._priv_triggerEventIfNotStopped("videoRepresentationChange",E(i)?i:In(i),u):t==="audio"&&this._priv_triggerEventIfNotStopped("audioRepresentationChange",E(i)?i:Bo(i),u)}}_priv_onBitrateEstimateChange({type:e,bitrate:t}){t!==void 0&&(this._priv_bitrateInfos.lastBitrates[e]=t),this.trigger("__priv_bitrateEstimateChange",{type:e,bitrate:t})}_priv_setPlayerState(e){this.state!==e&&(this.state=e,m.info("API","playerStateChange event",{newState:e}),this.trigger("playerStateChange",e))}_priv_triggerPositionUpdate(e,t){var s,d;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{isDirectFile:r,manifest:i}=e;if(!r&&i===null||E(t))return;let o=i!==null?kt(i):void 0,a={position:t.position.getPolled(),duration:t.duration,playbackRate:t.playbackRate,maximumPosition:o,bufferGap:t.bufferGap===void 0||!isFinite(t.bufferGap)?0:t.bufferGap};if(i!==null&&i.isLive&&t.position.getPolled()>0){let u=(d=i.availabilityStartTime)!=null?d:0;a.wallClockTime=t.position.getPolled()+u;let c=Sn(i);c!==void 0&&(a.liveGap=c-t.position.getPolled())}else if(r&&this.videoElement!==null){let u=yo(this.videoElement);u!==void 0&&(a.wallClockTime=u+t.position.getPolled())}this.trigger("positionUpdate",a)}_priv_triggerEventIfNotStopped(e,t,r){r.isCancelled()||this.trigger(e,t)}_priv_initializeMediaElementTracksStore(e){var r,i,o;ne(pe.directfile!==null,"Initializing `MediaElementTracksStore` without Directfile feature"),ne(this.videoElement!==null,"Initializing `MediaElementTracksStore` on a disposed RxPlayer");let t=new pe.directfile.mediaElementTracksStore(this.videoElement);return this._priv_triggerEventIfNotStopped("availableAudioTracksChange",t.getAvailableAudioTracks(),e),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",t.getAvailableVideoTracks(),e),this._priv_triggerEventIfNotStopped("availableTextTracksChange",t.getAvailableTextTracks(),e),this._priv_triggerEventIfNotStopped("audioTrackChange",(r=t.getChosenAudioTrack())!=null?r:null,e),this._priv_triggerEventIfNotStopped("textTrackChange",(i=t.getChosenTextTrack())!=null?i:null,e),this._priv_triggerEventIfNotStopped("videoTrackChange",(o=t.getChosenVideoTrack())!=null?o:null,e),t.addEventListener("availableVideoTracksChange",a=>this.trigger("availableVideoTracksChange",a)),t.addEventListener("availableAudioTracksChange",a=>this.trigger("availableAudioTracksChange",a)),t.addEventListener("availableTextTracksChange",a=>this.trigger("availableTextTracksChange",a)),t.addEventListener("audioTrackChange",a=>this.trigger("audioTrackChange",a)),t.addEventListener("videoTrackChange",a=>this.trigger("videoTrackChange",a)),t.addEventListener("textTrackChange",a=>this.trigger("textTrackChange",a)),t}_priv_callTracksStoreGetterSetter(e,t,r){var d,u;if(this._priv_contentInfos===null||this._priv_contentInfos.tracksStore===null)return m.warn("API","Trying to call track API too soon"),t;let{tracksStore:i}=this._priv_contentInfos,o=(u=(d=this._priv_contentInfos)==null?void 0:d.currentPeriod)!=null?u:void 0,a=e!=null?e:o==null?void 0:o.id;if(a===void 0)return t;let s=a===(o==null?void 0:o.id)?i.getPeriodObjectFromPeriod(o):i.getPeriodObjectFromId(a);return s===void 0?t:r(i,s)}_priv_onAvailableTracksMayHaveChanged(e,t){let r=this._priv_contentInfos;if(r===null)return;let{currentPeriod:i,tracksStore:o,currentContentCanceller:a}=r,s=a.signal;if(E(i)||o===null)return;let d=t!=null?t:o.getPeriodObjectFromPeriod(i);if(d!==void 0)switch(e){case"video":{let u=o.getAvailableVideoTracks(d,!0);this._priv_triggerEventIfNotStopped("availableVideoTracksChange",u!=null?u:[],s);break}case"audio":{let u=o.getAvailableAudioTracks(d,!0);this._priv_triggerEventIfNotStopped("availableAudioTracksChange",u!=null?u:[],s);break}case"text":{let u=o.getAvailableTextTracks(d);this._priv_triggerEventIfNotStopped("availableTextTracksChange",u!=null?u:[],s);break}default:ze(e)}}_priv_onFatalError(e,t){let r=Me(e,{defaultCode:"NONE",defaultReason:"An unknown error stopped content playback."});r.fatal=!0,t.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this._priv_currentError=r,m.error("API","The player stopped because of an error",r),this._priv_setPlayerState("STOPPED"),this._priv_currentError===r&&this.trigger("error",r)}};Yt._priv_currentlyUsedVideoElements=new WeakSet;var Ir=Yt;Ir.version="4.4.0";var Dp=Ir;var es=Dp;ts();es.addFeatures([Fl,Au,Du,Lu,Cl,_l,Ml,Rl,ll,Ku,bl,Wu]);var nue=es;Z.RxPlayer=es;})();
|
|
9
|
+
Char: `+n[t])}return t!==-1&&(t+=1),I}else if(n.charCodeAt(t+1)===ty){if(n.charCodeAt(t+2)===gu){let y=t;for(;t!==-1&&!(n.charCodeAt(t)===Wa&&n.charCodeAt(t-1)===gu&&n.charCodeAt(t-2)===gu);)t=n.indexOf(Om,t+1);t===-1&&(t=n.length),r&&I.push(n.substring(y,t+1))}else if(n.charCodeAt(t+2)===hu&&n.charCodeAt(t+8)===hu&&n.substring(t+3,t+8).toLowerCase()==="cdata"){let y=n.indexOf("]]>",t);y===-1?(I.push(n.substring(t+9)),t=n.length):(I.push(n.substring(t+9,y)),t=y+3);continue}else{let y=t+1;t+=2;let T=!1;for(;(n.charCodeAt(t)!==Wa||T)&&n[t]!==void 0;)n.charCodeAt(t)===hu?T=!0:T&&n.charCodeAt(t)===ny&&(T=!1),t++;I.push(n.substring(y,t))}t++;continue}let h=u();I.push(h),h.tagName[0]==="?"&&(I.push(...h.children),h.children=[])}else{let h=s();if(i)h.length>0&&I.push(h);else{let y=h.trim();y.length>0&&I.push(y)}t++}return I}function s(){let g=t;return t=n.indexOf(JI,t)-1,t===-2&&(t=n.length),n.slice(g,t+1)}function d(){let g=t;for(;ry.indexOf(n[t])===-1&&n[t]!==void 0;)t++;return n.slice(g,t)}function u(){let g=t;t++;let I=d(),h={},y=[];for(;n.charCodeAt(t)!==Wa&&n[t]!==void 0;){let T=n.charCodeAt(t);if(T>64&&T<91||T>96&&T<123){let v=d(),E=n.charCodeAt(t);for(;!isNaN(E)&&E!==Lm&&E!==Nm&&!(E>64&&E<91||E>96&&E<123)&&E!==Wa;)t++,E=n.charCodeAt(t);let R;E===Lm||E===Nm?R=c():(R=null,t--),h[v]=R===null?null:Um(R)}t++}return n.charCodeAt(t-1)!==Dm?(t++,y=a(I)):t++,{tagName:I,attributes:h,children:y,posStart:g,posEnd:t}}function c(){let g=n[t],I=t+1;return t=n.indexOf(g,I),n.slice(I,t)}function l(){let g=new RegExp("\\s"+e.attrName+`\\s*=['"]`+e.attrValue+`['"]`).exec(n);return g!==null?g.index:-1}}function Bm(n,e,t=0,r=""){let i=[];return n.forEach(function(o,a){if(typeof o=="object"&&(e(o,a,t,r)&&i.push(o),o.children.length>0)){let s=Bm(o.children,e,t+1,(x(r)?r+".":"")+a+"."+o.tagName);i=i.concat(s)}}),i}function Ha(n){if(Array.isArray(n)){let e="";return n.forEach(function(t){e+=" "+Ha(t),e=e.trim()}),e}else return typeof n=="object"?Ha(n.children):" "+Um(n)}function Um(n){return n.indexOf("&")<0?n:n.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&#x([A-Fa-f0-9]+);/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&/g,"&")}function Iu(n,e,t){let{repeatCount:r}=n;if(r>=0)return r;let i;return _(e)?t!==void 0?i=t:i=Number.MAX_VALUE:i=e.start,Math.ceil((i-n.start)/n.duration)-1}function Ne(n,e,t){let{start:r,duration:i}=n;if(i<=0)return r;let o=Iu(n,e,t);return r+(o+1)*i}function et(n,e){var t;return n*e.timescale+((t=e.indexTimeOffset)!=null?t:0)}function Ft(n,e){var t;return(n-((t=e.indexTimeOffset)!=null?t:0))/e.timescale}function Fm(n,e,t){return[n*t,(n+e)*t]}function iy(n,e){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i].start<=e?t=i+1:r=i}return t-1}function qa(n,e,t){let{timeline:r}=n,i=et(e,n);if(i<0)return null;let o=iy(r,i);if(o<0||o>=r.length-1)return null;let a=r[o];if(a.duration<=0)return null;let s=r[o+1];if(s===void 0)return null;let d=s.start,u=Ne(a,s,t);return i>=u&&i<d?Ft(d,n):null}function Yt(n,e){var i;let{initialization:t}=n,r={};return e!==void 0&&(r.isEMSGWhitelisted=e),{id:"init",isInit:!0,time:0,end:0,duration:0,timescale:1,range:_(t)?void 0:t.range,indexRange:n.indexRange,url:(i=t==null?void 0:t.url)!=null?i:null,complete:!0,privateInfos:r,timestampOffset:-(n.indexTimeOffset/n.timescale)}}function oy(n,e){let t=n.toString();return t.length>=e?t:(new Array(e+1).join("0")+t).slice(-e)}function yu(n){return(e,t,r)=>{let i=x(r)?parseInt(r,10):1;return oy(String(n),i)}}function Tt(n,e,t){return ay(n,e,t)}function ay(n,e,t){return n.indexOf("$")===-1?n:n.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,String(e)).replace(/\$Bandwidth(%0(\d+)d)?\$/g,yu(t===void 0?0:t))}function Ga(n,e){return function(r){return r.indexOf("$")===-1?r:r.replace(/\$\$/g,"$").replace(/\$Number(%0(\d+)d)?\$/g,(i,o,a)=>{if(e===void 0)throw new Error("Segment number not defined in a $Number$ scheme");return yu(e)(i,o,a)}).replace(/\$Time(%0(\d+)d)?\$/g,(i,o,a)=>{if(n===void 0)throw new Error("Segment time not defined in a $Time$ scheme");return yu(n)(i,o,a)})}}function sy(n,e,t){let r=t-n;return r>0?Math.floor(r/e):0}function no(n,e,t,r,i,o){var T;let a=r.getEstimatedMaximumPosition((T=n.availabilityTimeOffset)!=null?T:0),s=Math.min(e+t,a!=null?a:1/0),d=et(e,n),u=et(s,n),{timeline:c,timescale:l,segmentUrlTemplate:f,startNumber:m,endNumber:g}=n,I=m!=null?m:1,h=[],y=c.length;for(let v=0;v<y;v++){let E=c[v],{duration:R,start:k,range:A}=E,P;a===void 0?P=i:P=Math.min(a*l,i!=null?i:1/0);let M=Iu(E,c[v+1],P),N=n.availabilityTimeComplete!==!1||v!==y-1&&M!==0,U=sy(k,R,d),L=k+U*R;for(;L<u&&U<=M;){let B=I+U;if(g!==void 0&&B>g)break;let C=f===null?null:Ga(L,B)(f),w=L-n.indexTimeOffset,F=R;w<0&&(F=R+w,w=0);let K={id:String(L),time:w/l,end:(w+F)/l,duration:F/l,isInit:!1,range:A,timescale:1,url:C,number:B,timestampOffset:-(n.indexTimeOffset/l),complete:N,privateInfos:{isEMSGWhitelisted:o}};h.push(K),U++,L=k+U*R}if(L>=u||(I+=M+1,g!==void 0&&I>g))return h}return h}function dy(n,e){if(e.timescale!==n.timescale){let{timescale:t}=n;n.timeline.push({start:e.time/e.timescale*t,duration:e.duration/e.timescale*t,repeatCount:e.count===void 0?0:e.count,range:e.range})}else n.timeline.push({start:e.time,duration:e.duration,repeatCount:e.count===void 0?0:e.count,range:e.range});return!0}var zn=class{constructor(e,t){var g,I,h,y;let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t,d=(g=e.timescale)!=null?g:1,c=((I=e.presentationTimeOffset)!=null?I:0)-r*d,l=((h=e.initialization)==null?void 0:h.media)===void 0?null:Tt(e.initialization.media,o,a),f=e.media===void 0?null:Tt(e.media,o,a),m;e.initialization!==void 0?m=e.initialization.range:e.indexRange!==void 0&&(m=[0,e.indexRange[0]-1]),this._index={indexRange:e.indexRange,indexTimeOffset:c,initialization:{url:l,range:m},segmentUrlTemplate:f,startNumber:e.startNumber,endNumber:e.endNumber,timeline:(y=e.timeline)!=null?y:[],timescale:d},this._manifestBoundsCalculator=t.manifestBoundsCalculator,this._scaledPeriodStart=et(r,this._index),this._scaledPeriodEnd=_(i)?void 0:et(i,this._index),this._isInitialized=this._index.timeline.length>0,this._isEMSGWhitelisted=s}getInitSegment(){return Yt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return no(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){let e=this._index;return e.timeline.length===0?null:Ft(Math.max(this._scaledPeriodStart,e.timeline[0].start),e)}getLastAvailablePosition(){var i;let{timeline:e}=this._index;if(e.length===0)return null;let t=e[e.length-1],r=Math.min(Ne(t,null,this._scaledPeriodEnd),(i=this._scaledPeriodEnd)!=null?i:1/0);return Ft(r,this._index)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return this._isInitialized}initialize(e){if(!this._isInitialized){for(let t=0;t<e.length;t++)dy(this._index,e[t]);this._isInitialized=!0}}addPredictedSegments(){p.warn("dash","Cannot add predicted segments to a `BaseRepresentationIndex`")}getTargetSegmentDuration(){let{timeline:e,timescale:t}=this._index,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}_replace(e){this._index=e._index,this._isInitialized=e._isInitialized,this._scaledPeriodEnd=e._scaledPeriodEnd,this._isEMSGWhitelisted=e._isEMSGWhitelisted}_update(){p.error("dash","Base RepresentationIndex: Cannot update a SegmentList")}};var Wn=class{constructor(e,t){var m,g,I;if(e.duration===void 0)throw new Error("Invalid SegmentList: no duration");let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t;this._isEMSGWhitelisted=s,this._periodStart=r,this._periodEnd=i;let d=(m=e.presentationTimeOffset)!=null?m:0,u=(g=e.timescale)!=null?g:1,c=d-r*u,l=((I=e.initialization)==null?void 0:I.media)===void 0?null:Tt(e.initialization.media,o,a),f=e.list.map(h=>({url:h.media===void 0?null:Tt(h.media,o,a),mediaRange:h.mediaRange}));this._index={list:f,timescale:u,duration:e.duration,indexTimeOffset:c,indexRange:e.indexRange,initialization:_(e.initialization)?void 0:{url:l,range:e.initialization.range}}}getInitSegment(){let e=Yt(this._index);return e.privateInfos===void 0&&(e.privateInfos={}),e.privateInfos.isEMSGWhitelisted=this._isEMSGWhitelisted,e}getSegments(e,t){let r=this._index,{duration:i,list:o,timescale:a}=r,s=i/a,d=e-this._periodStart,[u,c]=Fm(d,t,a),l=Math.min(o.length-1,Math.floor(c/i)),f=[],m=Math.floor(u/i);for(;m<=l;){let g=o[m].mediaRange,I=o[m].url,h=m*s+this._periodStart,y={id:String(m),time:h,isInit:!1,range:g,duration:s,timescale:1,end:h+s,url:I,timestampOffset:-(r.indexTimeOffset/a),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};f.push(y),m++}return f}shouldRefresh(e,t){return!1}getFirstAvailablePosition(){return this._periodStart}getLastAvailablePosition(){var i;let e=this._index,{duration:t,list:r}=e;return Math.min(r.length*t/e.timescale+this._periodStart,(i=this._periodEnd)!=null?i:1/0)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return!0}initialize(){p.error("dash","A `ListRepresentationIndex` does not need to be initialized")}addPredictedSegments(){p.warn("dash","Cannot add predicted segments to a `ListRepresentationIndex`")}getTargetSegmentDuration(){let{duration:e,timescale:t}=this._index;return{duration:e/t,isPrecize:!0}}_replace(e){this._index=e._index}_update(){p.error("dash","A `ListRepresentationIndex` cannot be updated")}};function br(n){return O.getCurrent().DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR*n}var Hn=class{constructor(e,t){var y,T,v;let{availabilityTimeOffset:r,manifestBoundsCalculator:i,isDynamic:o,periodEnd:a,periodStart:s,representationId:d,representationBitrate:u,isEMSGWhitelisted:c}=t,l=(y=e.timescale)!=null?y:1;this._availabilityTimeOffset=r,this._manifestBoundsCalculator=i;let f=(T=e.presentationTimeOffset)!=null?T:0,m=s*l,g=f-m;if(e.duration===void 0)throw new Error("Invalid SegmentTemplate: no duration");let I=((v=e.initialization)==null?void 0:v.media)===void 0?null:Tt(e.initialization.media,d,u),h=e.media===void 0?null:Tt(e.media,d,u);this._index={duration:e.duration,timescale:l,indexRange:e.indexRange,indexTimeOffset:g,initialization:_(e.initialization)?void 0:{url:I,range:e.initialization.range},url:h,presentationTimeOffset:f,startNumber:e.startNumber,endNumber:e.endNumber},this._isDynamic=o,this._periodStart=s,this._scaledRelativePeriodEnd=a===void 0?void 0:(a-s)*l,this._isEMSGWhitelisted=c}getInitSegment(){return Yt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){let r=this._index,{duration:i,startNumber:o,endNumber:a,timescale:s,url:d}=r,u=this._periodStart*s,c=this._scaledRelativePeriodEnd,l=e*s-u,f=(e+t)*s-u,m=this._getFirstSegmentStart(),g=this._getLastSegmentStart();if(_(m)||_(g))return[];let I=Math.max(m,l),h=Math.min(g,f);if(h+i<=I)return[];let y=[],T=o!=null?o:1,v=Math.floor(I/i);for(let E=v*i;E<=h;E+=i){let R=v+T;if(a!==void 0&&R>a)return y;let k=!_(c)&&E+i>c?c-E:i,A=E+u,P=E+this._index.presentationTimeOffset,M=d===null?null:Ga(P,R)(d),N={id:String(R),number:R,time:A/s,end:(A+k)/s,duration:k/s,timescale:1,isInit:!1,scaledDuration:k/s,url:M,timestampOffset:-(r.indexTimeOffset/s),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};y.push(N),v++}return y}getFirstAvailablePosition(){let e=this._getFirstSegmentStart();return _(e)?e:e/this._index.timescale+this._periodStart}getLastAvailablePosition(){let e=this._getLastSegmentStart();if(_(e))return e;let t=this._estimateRelativeScaledEnd();return Math.min(e+this._index.duration,t!=null?t:1/0)/this._index.timescale+this._periodStart}getEnd(){if(!this._isDynamic)return this.getLastAvailablePosition();let e=this._estimateRelativeScaledEnd();if(e===void 0)return;let{timescale:t}=this._index;return(e+this._periodStart*t)/t}awaitSegmentBetween(e,t){if(ee(e<=t),!this._isDynamic)return!1;let{timescale:r}=this._index,i=br(r),o=this._periodStart*r,a=e*r-o,s=t*r-o,d=this._getLastSegmentStart();if(_(d)){let l=this._estimateRelativeScaledEnd();return l===void 0?s+i>=0:s+i>=0&&a<l-i}let u=d+this._index.duration,c=this._estimateRelativeScaledEnd();return c===void 0?s>u-i:s>u-i&&a<c-i}shouldRefresh(){return!1}checkDiscontinuity(){return null}isSegmentStillAvailable(e){if(e.isInit)return!0;let t=this.getSegments(e.time,.1);return t.length===0?!1:t[0].time===e.time&&t[0].end===e.end&&t[0].number===e.number}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){if(!this._isDynamic)return!1;let e=this._estimateRelativeScaledEnd();if(e===void 0)return!0;let{timescale:t}=this._index,r=this._getLastSegmentStart();if(_(r))return!0;let i=r+this._index.duration,o=br(t);return i+o<e}isInitialized(){return!0}initialize(){p.error("dash","A `TemplateRepresentationIndex` does not need to be initialized")}addPredictedSegments(){p.warn("dash","Cannot add predicted segments to a `TemplateRepresentationIndex`")}getTargetSegmentDuration(){return{duration:this._index.duration/this._index.timescale,isPrecize:!0}}_replace(e){this._index=e._index,this._isDynamic=e._isDynamic,this._periodStart=e._periodStart,this._scaledRelativePeriodEnd=e._scaledRelativePeriodEnd,this._manifestBoundsCalculator=e._manifestBoundsCalculator}_update(e){this._replace(e)}_getFirstSegmentStart(){var a;if(!this._isDynamic)return 0;if(this._scaledRelativePeriodEnd===0||this._scaledRelativePeriodEnd===void 0){let s=this._manifestBoundsCalculator.getEstimatedMaximumPosition((a=this._availabilityTimeOffset)!=null?a:0);if(s!==void 0&&s<this._periodStart)return null}let{duration:e,timescale:t}=this._index,r=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(e/t);if(r===void 0)return;let i=r>this._periodStart?(r-this._periodStart)*t:0;return Math.floor(i/e)*e}_getLastSegmentStart(){var o,a;let{duration:e,timescale:t,endNumber:r,startNumber:i=1}=this._index;if(this._isDynamic){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&this._scaledRelativePeriodEnd!==void 0&&this._scaledRelativePeriodEnd<s-this._periodStart*this._index.timescale){let l=Math.ceil(this._scaledRelativePeriodEnd/e);return r!==void 0&&r-i+1<l&&(l=r-i+1),(l-1)*e}let d=this._manifestBoundsCalculator.getEstimatedMaximumPosition((o=this._availabilityTimeOffset)!=null?o:0);if(d===void 0)return;let u=(d-this._periodStart)*t;if(u<0)return null;let c=Math.floor(u/e);return r!==void 0&&r-i+1<c&&(c=r-i+1),c<=0?null:(c-1)*e}else{let s=(a=this._scaledRelativePeriodEnd)!=null?a:0,d=Math.ceil(s/e);r!==void 0&&r-i+1<d&&(d=r-i+1);let u=(d-1)*e,c=O.getCurrent().MINIMUM_SEGMENT_SIZE*t;return r!==void 0||s-u>c||d<2?u:(d-2)*e}}_estimateRelativeScaledEnd(){var e,t;if(this._index.endNumber!==void 0){let r=this._index.endNumber-((e=this._index.startNumber)!=null?e:1)+1;return Math.max(Math.min(r*this._index.duration,(t=this._scaledRelativePeriodEnd)!=null?t:1/0),0)}if(this._scaledRelativePeriodEnd!==void 0)return Math.max(this._scaledRelativePeriodEnd,0)}};function ro(n,e){let t=0;for(;n.length>0;){let r=n[0];if(r.start>=e||r.repeatCount===-1)return t;if(r.repeatCount===0)n.shift(),t+=1;else{let i=n[1];if(i!==void 0&&i.start<=e)n.shift(),t+=1;else{if(r.duration<=0)return t;let o=r.start+r.duration,a=1;for(;o<e&&a<=r.repeatCount;)o+=r.duration,a++;if(a>r.repeatCount)n.shift(),t=r.repeatCount+1;else{let s=r.repeatCount-a;return r.start=o,r.repeatCount=s,t+=a,t}}}}return t}function io(n,e){if(n.length===0)return n.push(...e),!0;if(e.length===0)return!1;let t=n.length,r=e[0].start,i=n[t-1];if(Ne(i,e[0])<r)throw new re("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");for(let c=t-1;c>=0;c--){let l=n[c].start;if(l===r){let f=t-c;return n.splice(c,f,...e),!1}else if(l<r){let f=n[c];if(f.start+f.duration>r)return p.warn("utils","Manifest update removed all previous segments"),n.splice(0,t,...e),!0;if(f.repeatCount===void 0||f.repeatCount<=0)return f.repeatCount<0&&(f.repeatCount=Math.floor((r-f.start)/f.duration)-1),n.splice(c+1,t-(c+1),...e),!1;if(f.start+f.duration*(f.repeatCount+1)<=r)return n.splice(c+1,t-(c+1),...e),!1;let g=(r-f.start)/f.duration-1;if(g%1===0&&f.duration===e[0].duration){let I=e[0].repeatCount<0?-1:e[0].repeatCount+g+1;return n.splice(c,t-c,...e),n[c].start=f.start,n[c].repeatCount=I,!1}return p.warn("utils","Manifest update removed previous segments"),n[c].repeatCount=Math.floor(g),n.splice(c+1,t-(c+1),...e),!1}}let a=n[n.length-1],s=e[e.length-1];if(a.repeatCount!==void 0&&a.repeatCount<0)return a.start>s.start?(p.warn("utils","The new index is older than the previous one"),!1):(p.warn("utils",'The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0);let d=a.start+a.duration*(a.repeatCount+1),u=s.start+s.duration*(s.repeatCount+1);return d>=u?(p.warn("utils","The new index is older than the previous one"),!1):(p.warn("utils",'The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0)}function oo(n,e,t){let r=n.start,i=n.duration,o=n.repeatCount;return r===void 0&&(e===null?r=0:_(e.duration)||(r=e.start+e.duration*(e.repeatCount+1))),(i===void 0||isNaN(i))&&t!==null&&t.start!==void 0&&!isNaN(t.start)&&r!==void 0&&!isNaN(r)&&(i=t.start-r),r!==void 0&&!isNaN(r)&&i!==void 0&&!isNaN(i)&&(o===void 0||!isNaN(o))?{start:r,duration:i,repeatCount:o===void 0?0:o}:(p.warn("dash",'A "S" Element could not have been parsed.'),null)}function ao(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!_(r))switch(t){case"t":{let i=parseInt(r,10);isNaN(i)?p.warn("dash","invalid t value for <S> element",{val:r}):e.start=i;break}case"d":{let i=parseInt(r,10);isNaN(i)?p.warn("dash","invalid d value for <S> element",{val:r}):e.duration=i;break}case"r":{let i=parseInt(r,10);isNaN(i)?p.warn("dash","invalid r value for <S> element",{val:r}):e.repeatCount=i;break}}}return e}function hn(n){let e=[];for(let r=0;r<n.length;r++)e.push(ao(n[r]));let t=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[t.length-1]===void 0?null:t[t.length-1],a=e[r+1]===void 0?null:e[r+1],s=oo(i,o,a);s!==null&&t.push(s)}return t}function bu(n,e){if(n.length===0||e.length===0)return null;let t=n[0].start,r=e[0].attributes.t,i=_(r)?null:parseInt(r,10);if(i===null||Number.isNaN(i))return null;if(t===i)return{prevSegmentsIdx:0,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(t<i){let o=n[0],a=0;for(;;){if(o.repeatCount>0){let s=i-o.start;if(s%o.duration===0&&s/o.duration<=o.repeatCount)return{repeatNumberInPrevSegments:s/o.duration,prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInNewElements:0}}if(a++,a>=n.length)return null;if(o=n[a],o.start===i)return{prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(o.start>i)return null}}else{let o=0,a=e[0],s=i;for(;;){let d=a.attributes.d,u=_(d)?null:parseInt(d,10);if(u===null||Number.isNaN(u))return null;let c=a.attributes.r,l=_(c)?null:parseInt(c,10);if(l!==null){if(Number.isNaN(l)||l<0)return null;if(l>0){let g=t-s;if(g%u===0&&g/u<=l)return{repeatNumberInPrevSegments:0,repeatNumberInNewElements:g/u,prevSegmentsIdx:0,newElementsIdx:o}}s+=u*(l+1)}else s+=u;if(o++,o>=e.length)return null;a=e[o];let f=a.attributes.t,m=_(f)?null:parseInt(f,10);if(m!==null){if(Number.isNaN(m))return null;s=m}if(s===t)return{newElementsIdx:o,prevSegmentsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(s>i)return null}}}function Su(n,e){var I;let t=bu(e,n);if(t===null)return p.warn("dash",'Cannot perform "based" update. Common segment not found.'),hn(n);let{prevSegmentsIdx:r,newElementsIdx:i,repeatNumberInPrevSegments:o,repeatNumberInNewElements:a}=t,d=e.length-r+i-1;if(d>=n.length)return p.info("dash",'Cannot perform "based" update. New timeline too short'),hn(n);let u=e.slice(r);if(o>0){let h=u[0];h.start+=h.duration*o,u[0].repeatCount-=o}if(a>0&&i!==0)return p.info("dash",'Cannot perform "based" update. The new timeline has a different form.'),hn(n);let c=u[u.length-1],l=ao(n[d]),f=((I=l.repeatCount)!=null?I:0)-a;if(l.duration!==c.duration||c.repeatCount>f)return p.info("dash",'Cannot perform "based" update. The new timeline has a different form at the beginning.'),hn(n);l.repeatCount!==void 0&&l.repeatCount>c.repeatCount&&(c.repeatCount=l.repeatCount);let m=[],g=[];for(let h=d+1;h<n.length;h++)g.push(ao(n[h]));for(let h=0;h<g.length;h++){let y=g[h],T=m[m.length-1]===void 0?c:m[m.length-1],v=g[h+1]===void 0?null:g[h+1],E=oo(y,T,v);E!==null&&m.push(E)}return u.concat(m)}var so=class n{constructor(e,t){var E,R,k,A,P;if(!n.isTimelineIndexArgument(e))throw new Error("The given index is not compatible with a TimelineRepresentationIndex.");let{availabilityTimeComplete:r,availabilityTimeOffset:i,manifestBoundsCalculator:o,isDynamic:a,isLastPeriod:s,representationId:d,representationBitrate:u,periodStart:c,periodEnd:l,isEMSGWhitelisted:f}=t,m=(E=e.timescale)!=null?E:1,g=(R=e.presentationTimeOffset)!=null?R:0,I=c*m,h=g-I;this._manifestBoundsCalculator=o,this._isEMSGWhitelisted=f,this._isLastPeriod=s,this._lastUpdate=(k=t.receivedTime)!=null?k:z(),this._unsafelyBaseOnPreviousIndex=null,t.unsafelyBaseOnPreviousRepresentation!==null&&t.unsafelyBaseOnPreviousRepresentation.index instanceof n&&(t.unsafelyBaseOnPreviousRepresentation.index._unsafelyBaseOnPreviousIndex=null,this._unsafelyBaseOnPreviousIndex=t.unsafelyBaseOnPreviousRepresentation.index),this._isDynamic=a,this._parseTimeline=(A=e.timelineParser)!=null?A:null;let y=((P=e.initialization)==null?void 0:P.media)===void 0?null:Tt(e.initialization.media,d,u),T=e.media===void 0?null:Tt(e.media,d,u),v;i===void 0&&r===void 0?v=1/0:v=i!=null?i:0,this._index={availabilityTimeComplete:r!=null?r:!0,availabilityTimeOffset:v,indexRange:e.indexRange,indexTimeOffset:h,initialization:_(e.initialization)?void 0:{url:y,range:e.initialization.range},segmentUrlTemplate:T,startNumber:e.startNumber,endNumber:e.endNumber,timeline:e.timeline===void 0?null:Tu(e.timeline,e.startNumber,e.endNumber),timescale:m},this._scaledPeriodStart=et(c,this._index),this._scaledPeriodEnd=l===void 0?void 0:et(l,this._index)}getInitSegment(){return Yt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),no(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=this._index.timeline;return e.length===0?null:Ft(Math.max(this._scaledPeriodStart,e[0].start),this._index)}getLastAvailablePosition(){var r;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=ja(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(e===null)return null;let t=Math.min(e.end,(r=this._scaledPeriodEnd)!=null?r:1/0);return Ft(t,this._index)}getEnd(){var r;if(this._isDynamic&&!this._isLastPeriod)return;if(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),this._index.timeline.length<=0)return null;let e=this._index.timeline[this._index.timeline.length-1],t=Math.min(Ne(e,null,this._scaledPeriodEnd),(r=this._scaledPeriodEnd)!=null?r:1/0);return Ft(t,this._index)}awaitSegmentBetween(e,t){var u,c;if(ee(e<=t),!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timescale:r,timeline:i}=this._index,o=br(r),a=et(t,this._index),s=ja(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(s!==null&&Math.min(s.end,(u=this._scaledPeriodEnd)!=null?u:1/0)+o>=Math.min(a,(c=this._scaledPeriodEnd)!=null?c:1/0))return!1;let d=et(e,this._index);if(i.length>0&&s!==null&&!s.isLastOfTimeline){let l=i[i.length-1],m=Ne(l,null,this._scaledPeriodEnd)+o;if(d<m+o)return!0}return this._isLastPeriod?this._scaledPeriodEnd===void 0?a+o>this._scaledPeriodStart?void 0:!1:d-o<this._scaledPeriodEnd&&a+o>this._scaledPeriodStart:!1}isSegmentStillAvailable(e){return e.isInit?!0:(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),uy(e,this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd))}checkDiscontinuity(e){this._refreshTimeline();let t=this._index.timeline;return t===null&&(t=this._getTimeline(),this._index.timeline=t),qa({timeline:t,timescale:this._index.timescale,indexTimeOffset:this._index.indexTimeOffset},e,this._scaledPeriodEnd)}canBeOutOfSyncError(e){return this._isDynamic?e instanceof at&&e.isHttpError(404):!1}_replace(e){this._parseTimeline=e._parseTimeline,this._index=e._index,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._manifestBoundsCalculator=e._manifestBoundsCalculator,this._isLastPeriod=e._isLastPeriod}_update(e){this._index.timeline===null&&(this._index.timeline=this._getTimeline()),e._index.timeline===null&&(e._index.timeline=e._getTimeline()),io(this._index.timeline,e._index.timeline)&&(this._index.startNumber=e._index.startNumber),this._index.availabilityTimeOffset=e._index.availabilityTimeOffset,this._index.availabilityTimeComplete=e._index.availabilityTimeComplete,this._index.endNumber=e._index.endNumber,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._isLastPeriod=e._isLastPeriod}isStillAwaitingFutureSegments(){var a;if(!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timeline:e}=this._index;if(e.length===0){if(this._scaledPeriodEnd!==void 0){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&et(s,this._index)>this._scaledPeriodEnd)return!1}return this._isLastPeriod}let t=br(this._index.timescale),r=ja(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(r!==null&&!r.isLastOfTimeline){let s=Math.min(r.end,(a=this._scaledPeriodEnd)!=null?a:1/0);return!(this._scaledPeriodEnd!==void 0&&s+t>=this._scaledPeriodEnd)}if(!this._isLastPeriod)return!1;if(this._scaledPeriodEnd===void 0)return!0;let i=e[e.length-1];return Ne(i,null,this._scaledPeriodEnd)+t<this._scaledPeriodEnd}isInitialized(){return!0}initialize(){p.error("dash","A `TimelineRepresentationIndex` does not need to be initialized")}addPredictedSegments(){p.warn("dash","Cannot add predicted segments to a `TimelineRepresentationIndex`")}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._index;if(e===null)return;let r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}static isTimelineIndexArgument(e){return typeof e.timelineParser=="function"||Array.isArray(e.timeline)}_refreshTimeline(){var i,o;if(this._index.timeline===null&&(this._index.timeline=this._getTimeline()),!this._isDynamic)return;let e=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(((o=(i=this._index.timeline[0])==null?void 0:i.duration)!=null?o:0)/this._index.timescale);if(_(e))return;let t=et(e,this._index),r=ro(this._index.timeline,t);this._index.startNumber!==void 0?this._index.startNumber+=r:this._index.endNumber!==void 0&&(this._index.startNumber=r+1)}_getTimeline(){if(this._parseTimeline===null)return this._index.timeline!==null?this._index.timeline:(p.error("dash","Timeline already lazily parsed."),[]);let e=this._parseTimeline();this._parseTimeline=null;let{MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:t}=O.getCurrent();if(this._unsafelyBaseOnPreviousIndex===null||e.length<t)return Tu(hn(e),this._index.startNumber,this._index.endNumber);let r;return this._unsafelyBaseOnPreviousIndex._index.timeline===null?(r=this._unsafelyBaseOnPreviousIndex._getTimeline(),this._unsafelyBaseOnPreviousIndex._index.timeline=r):r=this._unsafelyBaseOnPreviousIndex._index.timeline,this._unsafelyBaseOnPreviousIndex=null,Tu(Su(e,r),this._index.startNumber,this._index.endNumber)}};function Tu(n,e,t){if(t===void 0)return n;let r=e!=null?e:1;for(let i=0;i<n.length;i++){let o=n[i];if(r+=o.repeatCount+1,r>t){if(r===t+1)return n.slice(0,i+1);{let a=n.slice(0,i),s=oe({},o),d=r-o.repeatCount-1;return s.repeatCount=Math.max(0,t-d),a.push(s),a}}}return n}function uy(n,e,t,r){let i=ja(e,t,r);if(i===null)return!1;for(let o=0;o<e.timeline.length;o++){if(i.timelineIdx<o)return!1;let a=e.timeline[o],s=(a.start-e.indexTimeOffset)/e.timescale;if(s>n.time)return!1;if(s===n.time)return a.range===void 0?n.range===void 0:!_(n.range)&&a.range[0]===n.range[0]&&a.range[1]===n.range[1];if(a.repeatCount>=0&&a.duration!==void 0){let u=(s-a.start)/a.duration-1;return u%1===0&&u<=i.newRepeatCount}}return!1}function ja(n,e,t){if(n.timeline.length<=0)return null;if(n.availabilityTimeOffset===1/0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:Ne(o,null,t)}}let r=e.getEstimatedMaximumPosition(n.availabilityTimeOffset);if(r===void 0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:Ne(o,null,t)}}for(let i=n.timeline.length-1;i>=n.timeline.length;i--){let o=n.timeline[i],a=o.start+o.duration;if(Ft(a,n)<=r){let s=Ne(o,n.timeline[i+1],t);if(Ft(s,n)<=r)return{isLastOfTimeline:i===n.timeline.length-1,timelineIdx:i,newRepeatCount:o.repeatCount,end:a};{let u=et(r,n)-o.start,c=Math.floor(u/o.duration);return ee(c>=1),{isLastOfTimeline:!1,timelineIdx:i,newRepeatCount:c-1,end:o.start+c*o.duration}}}}return null}var Ya=so;var uo=class{constructor(){this._refs=new Map,this._stored=[]}addReferences(e){for(let t of e)t.attributes.refId!==void 0&&this._refs.set(t.attributes.refId,t)}add(e,t){this._tryParsing(e,t,!1)||this._stored.push([e,t]),t.attributes.refId!==void 0&&(this._refs.set(t.attributes.refId,t),this._resolveStoredRefs(!1))}finalize(){this._resolveStoredRefs(!0)}_resolveStoredRefs(e){for(let t=this._stored.length-1;t>=0;t--){let[r,i]=this._stored[t];(this._tryParsing(r,i,e)||e)&&this._stored.splice(t,1)}return this._stored.length===0}_tryParsing(e,t,r){if(t.attributes.ref===void 0)return _u(e,t),!0;let i=this._getReferenced(t.attributes.ref);return i===void 0?(r&&(p.warn("dash","forcing the parsing of a referencing ContentProtection"),_u(e,t)),!1):(t.children.cencPssh.push(...i.children.cencPssh),t.attributes.keyId===void 0&&i.attributes.keyId!==void 0&&(t.attributes.keyId=i.attributes.keyId),t.attributes.schemeIdUri===void 0&&i.attributes.schemeIdUri!==void 0&&(t.attributes.schemeIdUri=i.attributes.schemeIdUri),t.attributes.value===void 0&&i.attributes.value!==void 0&&(t.attributes.value=i.attributes.value),_u(e,t),!0)}_getReferenced(e){return this._refs.get(e)}};function _u(n,e){let t;if(e.attributes.schemeIdUri!==void 0&&e.attributes.schemeIdUri.substring(0,9)==="urn:uuid:"&&(t=e.attributes.schemeIdUri.substring(9).replace(/-/g,"").toLowerCase()),e.attributes.keyId!==void 0&&e.attributes.keyId.length>0){let a=e.attributes.keyId;n.contentProtections===void 0?n.contentProtections={keyIds:[a],initData:[]}:n.contentProtections.keyIds===void 0?n.contentProtections.keyIds=[a]:n.contentProtections.keyIds.push(a)}if(t===void 0)return;let{cencPssh:r}=e.children,i=[];for(let a of r)i.push({systemId:t,data:a});if(i.length===0)return;if(n.contentProtections===void 0){n.contentProtections={keyIds:[],initData:[{type:"cenc",values:i}]};return}let o=q(n.contentProtections.initData,a=>a.type==="cenc");o===void 0?n.contentProtections.initData.push({type:"cenc",values:i}):o.values.push(...i)}function Qa(n){let e=Date.parse(n)-z();if(isNaN(e)){p.warn("dash","Invalid clock received",{clock:n});return}return e}function Eu(n){let e=n.children.utcTimings.filter(t=>(t.schemeIdUri==="urn:mpeg:dash:utc:http-iso:2014"||t.schemeIdUri==="urn:mpeg:dash:utc:http-xsdate:2014")&&t.value!==void 0);return e.length>0?e[0].value:void 0}function $a(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getLastAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.min(t,i))}return t===null?null:t}function vu(n){for(let e=n.length-1;e>=0;e--){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=$a(r);if(s===void 0)return{safe:void 0,unsafe:void 0};o=s}if(i!==void 0){let s=$a(i);if(s===void 0)return{safe:void 0,unsafe:void 0};a=s}if(r!==void 0&&o===null||i!==void 0&&a===null)return p.info("utils","found Period with no segment. ","Going to previous one to calculate last position"),{safe:void 0,unsafe:void 0};if(a!==null)return o!==null?{safe:Math.min(o,a),unsafe:Math.max(o,a)}:{safe:a,unsafe:a};if(o!==null)return{safe:o,unsafe:o}}}return{safe:void 0,unsafe:void 0}}function Xa(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getFirstAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.max(t,i))}return t===null?null:t}function Ru(n){for(let e=0;e<=n.length-1;e++){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=Xa(r);if(s===void 0)return;o=s}if(i!==void 0){let s=Xa(i);if(s===void 0)return;a=s}if(r!==void 0&&o===null||i!==void 0&&a===null){p.info("utils","found Period with no segment. ","Going to next one to calculate first position");return}if(a!==null)return o!==null?Math.max(o,a):a;if(o!==null)return o}}}function ku(n){if(n.length===0)throw new Error("DASH Parser: no period available for a dynamic content");let e=Ru(n),t=vu(n);return{minimumSafePosition:e,maximumSafePosition:t.safe,maximumUnsafePosition:t.unsafe}}var lo=class{constructor(e){this._isDynamic=e.isDynamic,this._timeShiftBufferDepth=!e.isDynamic||e.timeShiftBufferDepth===void 0?null:e.timeShiftBufferDepth,this._serverTimestampOffset=e.serverTimestampOffset,this._availabilityStartTime=e.availabilityStartTime}setLastPosition(e,t){this._lastPosition=e,this._positionTime=t}lastPositionIsKnown(){return this._isDynamic?this._positionTime!==void 0&&this._lastPosition!==void 0:this._lastPosition!==void 0}getEstimatedMinimumSegmentTime(e){var i;if(!this._isDynamic||this._timeShiftBufferDepth===null)return 0;let t=(i=this.getEstimatedLiveEdge())!=null?i:this.getEstimatedMaximumPosition(0);return t===void 0?void 0:t-(this._timeShiftBufferDepth+e)}getEstimatedLiveEdge(){if(!(!this._isDynamic||this._serverTimestampOffset===void 0))return(z()+this._serverTimestampOffset)/1e3-this._availabilityStartTime}getEstimatedMaximumPosition(e){if(!this._isDynamic)return this._lastPosition;let t=this.getEstimatedLiveEdge();return t!==void 0&&e!==1/0?t+e:this._positionTime!==void 0&&this._lastPosition!==void 0?Math.max(this._lastPosition-this._positionTime+z()/1e3,0):this._lastPosition}};function Cu(n,e){return n.type!=="dynamic"?0:_(n.availabilityStartTime)?e!=null?e:0:n.availabilityStartTime}function Pu(n){if(n.length===0)return[];let e=[n[0]];for(let t=1;t<n.length;t++){let r=n[t],i=e[e.length-1];for(;(i.duration===void 0||i.start+i.duration>r.start)&&(p.warn("dash","Updating overlapping Periods.",{lastStart:i==null?void 0:i.start,newStart:r.start}),i.duration=r.start-i.start,i.end=r.start,!(i.duration>0));){if(e.pop(),e.length===0)break;i=e[e.length-1]}e.push(r)}return e}function Mu(n,e){let t=[];return n.forEach((r,i)=>{let o;if(!_(r.attributes.start))o=r.attributes.start;else if(i===0)o=!e.isDynamic||_(e.availabilityStartTime)?0:e.availabilityStartTime;else{let u=t[t.length-1];if(!_(u)&&!_(u.periodEnd))o=u.periodEnd;else throw new Error("Missing start time when parsing periods.")}let a,s=n[i+1];_(r.attributes.duration)?i===n.length-1?a=e.duration:_(s.attributes.start)||(a=s.attributes.start-o):a=r.attributes.duration;let d=_(a)?void 0:o+a;t.push({periodStart:o,periodDuration:a,periodEnd:d})}),t}function ly(n,e){for(let t of e){let{adaptation:r,trickModeAttachedAdaptationIds:i}=t;for(let o of i)for(let a of an){let s=n[a];if(s!==void 0)for(let d of s)d.id===o&&(d.trickModeTracks===void 0&&(d.trickModeTracks=[]),d.trickModeTracks.push(r))}}}var Km=ly;var cy=["subtitle","caption"];function Au(n,e){var s,d,u,c;let t=(c=q((s=n.children.essentialProperties)!=null?s:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile"))!=null?c:q((u=(d=e!=null?e:n.children.representations[0])==null?void 0:d.children.essentialProperties)!=null?u:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile");if(t===void 0)return null;let r=/(\d+)x(\d+)/;if(t===void 0||t.value===void 0||!r.test(t.value))return p.warn("dash","Invalid thumbnails Representation, no tile-related information"),null;let i=t.value.match(r),o=parseInt(i[1],10),a=parseInt(i[2],10);return{horizontalTiles:o,verticalTiles:a}}function xu(n,e){if(n.attributes.contentType==="image")return Au(n)!==null?"thumbnails":void 0;let t=x(n.attributes.mimeType)?n.attributes.mimeType:null,r=x(n.attributes.codecs)?n.attributes.codecs:null,i=_(n.children.roles)?null:n.children.roles;function o(s,d){let u=s.split("/")[0];if(J(an,u))return u;if(s==="application/ttml+xml")return"text";if(s==="application/mp4")return d!==null&&q(d,c=>c.schemeIdUri==="urn:mpeg:dash:role:2011"&&J(cy,c.value))!==void 0?"text":void 0}function a(s){switch(s.substring(0,3)){case"avc":case"hev":case"hvc":case"vp8":case"vp9":case"av1":return"video";case"vtt":return"text"}switch(s.substring(0,4)){case"mp4a":return"audio";case"wvtt":case"stpp":return"text"}}if(t!==null){let s=o(t,i);if(s!==void 0)return s}if(r!==null){let s=a(r);if(s!==void 0)return s}for(let s=0;s<e.length;s++){let d=e[s],{mimeType:u,codecs:c}=d.attributes;if(u!==void 0){let l=o(u,i);if(l!==void 0)return l}if(c!==void 0){let l=a(c);if(l!==void 0)return l}}}var fy=/[, ]+/g;function Vm(n){return x(n)?n.trim().replace(fy,", "):""}function zm(n){let[e,t,r,i,o,a,s,d]=n.split(".");if(e!=="vp08"&&e!=="vp09"&&e!=="vp10")return;let u,c,l;if((i!==void 0&&i==="10"||i==="12")&&(u=parseInt(i,10)),s!==void 0&&(s==="16"?c="pq":s==="18"&&(c="hlg")),a!==void 0&&d!==void 0&&a==="09"&&d==="09"&&(l="rec2020"),!(u===void 0||c===void 0))return{colorDepth:u,eotf:c,colorSpace:l}}function wu(n,e){var g,I,h;let{availabilityTimeOffset:t,manifestBoundsCalculator:r,isDynamic:i,end:o,start:a,receivedTime:s,unsafelyBaseOnPreviousRepresentation:d,inbandEventStreams:u,isLastPeriod:c}=e,f={availabilityTimeComplete:void 0,availabilityTimeOffset:t,unsafelyBaseOnPreviousRepresentation:d,isEMSGWhitelisted:y=>u===void 0?!1:u.some(({schemeIdUri:T})=>T===y.schemeIdUri),isLastPeriod:c,manifestBoundsCalculator:r,isDynamic:i,periodEnd:o,periodStart:a,receivedTime:s,representationBitrate:n.attributes.bitrate,representationId:n.attributes.id},m;if(n.children.segmentBase!==void 0){let{segmentBase:y}=n.children;m=new zn(y,f)}else if(n.children.segmentList!==void 0){let{segmentList:y}=n.children;m=new Wn(y,f)}else if(n.children.segmentTemplate!==void 0||e.parentSegmentTemplates.length>0){let y=e.parentSegmentTemplates.slice(),T=n.children.segmentTemplate;T!==void 0&&y.push(T);let v=G({},...y);(v.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(f.availabilityTimeOffset=((g=v.availabilityTimeOffset)!=null?g:0)+((I=e.availabilityTimeOffset)!=null?I:0)),(v.availabilityTimeComplete!==void 0||e.availabilityTimeComplete!==void 0)&&(f.availabilityTimeComplete=(h=v.availabilityTimeComplete)!=null?h:e.availabilityTimeComplete),m=Ya.isTimelineIndexArgument(v)?new Ya(v,f):new Hn(v,f)}else{let y=e.adaptation.children;if(y.segmentBase!==void 0){let{segmentBase:T}=y;m=new zn(T,f)}else if(y.segmentList!==void 0){let{segmentList:T}=y;m=new Wn(T,f)}else m=new Hn({duration:Number.MAX_VALUE,timescale:1,startNumber:0,media:""},f)}return m}function Qt(n,e){var i;if(e.length===0)return n;let t=e.map(o=>({url:o.value}));if(n.length===0)return t;let r=[];for(let o=0;o<n.length;o++){let a=n[o];for(let s=0;s<t.length;s++){let d=t[s],u=Un(a.url,d.url);r.push({url:u,serviceLocation:(i=d.serviceLocation)!=null?i:a.serviceLocation})}}return r}function my(n,e){let t=[];if(n.children.inbandEventStreams!==void 0&&t.push(...n.children.inbandEventStreams),e.children.inbandEventStreams!==void 0&&t.push(...e.children.inbandEventStreams),t.length!==0)return t}function py({adaptationProfiles:n,essentialProperties:e,supplementalProperties:t,manifestProfiles:r,codecs:i}){if(((n!=null?n:"")+(r!=null?r:"")).indexOf("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")!==-1&&(i==="hvc1.2.4.L153.B0"||i==="hev1.2.4.L153.B0"))return{colorDepth:10,eotf:"pq",colorSpace:"rec2020"};let a=q([...e!=null?e:[],...t!=null?t:[]],s=>s.schemeIdUri==="urn:mpeg:mpegB:cicp:TransferCharacteristics");if(a!==void 0)switch(a.value){case"15":return;case"16":return{eotf:"pq"};case"18":return{eotf:"hlg"}}if(i!==void 0&&/^vp(08|09|10)/.test(i))return zm(i)}function Ou(n,e,t){var i,o,a,s,d,u,c;let r=[];for(let l of n){let f=l.attributes.id!==void 0?l.attributes.id:String(l.attributes.bitrate)+(l.attributes.height!==void 0?`-${l.attributes.height}`:"")+(l.attributes.width!==void 0?`-${l.attributes.width}`:"")+(l.attributes.mimeType!==void 0?`-${l.attributes.mimeType}`:"")+(l.attributes.codecs!==void 0?`-${l.attributes.codecs}`:"");for(;r.some(M=>M.id===f);)f+="-dup";let m=(o=(i=t.unsafelyBaseOnPreviousAdaptation)==null?void 0:i.getRepresentation(f))!=null?o:null,g=my(l,e),I=(a=l.attributes.availabilityTimeComplete)!=null?a:t.availabilityTimeComplete,h;(l.attributes.availabilityTimeOffset!==void 0||t.availabilityTimeOffset!==void 0)&&(h=((s=l.attributes.availabilityTimeOffset)!=null?s:0)+((d=t.availabilityTimeOffset)!=null?d:0));let y=G({},t,{availabilityTimeOffset:h,availabilityTimeComplete:I,unsafelyBaseOnPreviousRepresentation:m,adaptation:e,inbandEventStreams:g}),T=wu(l,y),v;l.attributes.bitrate===void 0?(p.warn("dash","No usable bitrate found in the Representation."),v=0):v=l.attributes.bitrate;let E=Qt(t.baseURLs,l.children.baseURLs),R=E.length===0?[{baseUrl:"",id:void 0}]:E.map(M=>({baseUrl:M.url,id:M.serviceLocation})),k={bitrate:v,cdnMetadata:R,index:T,id:f};l.children.supplementalProperties!==void 0&&q(l.children.supplementalProperties,M=>M.schemeIdUri==="tag:dolby.com,2018:dash:EC3_ExtensionType:2018"&&M.value==="JOC")!==void 0&&(k.isSpatialAudio=!0);let A;l.attributes.codecs!==void 0?A=l.attributes.codecs:e.attributes.codecs!==void 0&&(A=e.attributes.codecs),A!==void 0&&(A=A==="mp4a.40.02"?"mp4a.40.2":A,k.codecs=A);let P;l.attributes.supplementalCodecs!==void 0?P=l.attributes.supplementalCodecs:e.attributes.supplementalCodecs!==void 0&&(P=e.attributes.supplementalCodecs),P!==void 0&&(k.supplementalCodecs=Vm(P)),l.attributes.frameRate!==void 0?k.frameRate=l.attributes.frameRate:e.attributes.frameRate!==void 0&&(k.frameRate=e.attributes.frameRate),l.attributes.height!==void 0?k.height=l.attributes.height:e.attributes.height!==void 0&&(k.height=e.attributes.height),l.attributes.mimeType!==void 0?k.mimeType=l.attributes.mimeType:e.attributes.mimeType!==void 0&&(k.mimeType=e.attributes.mimeType),l.attributes.width!==void 0?k.width=l.attributes.width:e.attributes.width!==void 0&&(k.width=e.attributes.width);{let M=[...(u=e.children.contentProtections)!=null?u:[],...(c=l.children.contentProtections)!=null?c:[]];for(let N of M)t.contentProtectionParser.add(k,N)}k.hdrInfo=py({adaptationProfiles:e.attributes.profiles,supplementalProperties:e.children.supplementalProperties,essentialProperties:e.children.essentialProperties,manifestProfiles:t.manifestProfiles,codecs:A}),r.push(k)}return r}function gy(n){if(n===void 0)return!1;let e=n.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&n.value==="1",t=n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="description";return e||t}function hy(n,e){return!!(n!==void 0&&n.some(r=>r.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&r.value==="2")||e!==void 0&&e.some(r=>r.schemeIdUri==="urn:mpeg:dash:role:2011"&&r.value==="caption"))}function Iy(n){return n===void 0?!1:n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="sign"}function yy(n,e){if(x(n.attributes.id))return n.attributes.id;let{isClosedCaption:t,isForcedSubtitle:r,isAudioDescription:i,isSignInterpreted:o,isTrickModeTrack:a,type:s}=e,d=s;return x(n.attributes.language)&&(d+=`-${n.attributes.language}`),t===!0&&(d+="-cc"),r===!0&&(d+="-cc"),i===!0&&(d+="-ad"),o===!0&&(d+="-si"),a&&(d+="-trickMode"),x(n.attributes.contentType)&&(d+=`-${n.attributes.contentType}`),x(n.attributes.codecs)&&(d+=`-${n.attributes.codecs}`),x(n.attributes.mimeType)&&(d+=`-${n.attributes.mimeType}`),n.attributes.frameRate!==void 0&&(d+=`-${String(n.attributes.frameRate)}`),d}function by(n){if(!_(n.children.supplementalProperties)){let{supplementalProperties:e}=n.children;for(let t of e)if(t.schemeIdUri==="urn:mpeg:dash:adaptation-set-switching:2016"&&!_(t.value))return t.value.split(",").map(r=>r.trim()).filter(r=>x(r))}return[]}function Du(n,e){var d,u,c,l,f,m,g;let t={video:[],audio:[],text:[]},r=[],i=[],o={},a=[];for(let I=0;I<n.length;I++){let h=n[I],y=h.children,{essentialProperties:T,roles:v,label:E}=y,R=Array.isArray(v)&&v.some(ye=>ye.value==="main")&&v.some(ye=>ye.schemeIdUri==="urn:mpeg:dash:role:2011"),k=h.children.representations,A=(d=h.attributes.availabilityTimeComplete)!=null?d:e.availabilityTimeComplete,P;(h.attributes.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(P=((u=h.attributes.availabilityTimeOffset)!=null?u:0)+((c=e.availabilityTimeOffset)!=null?c:0));let M=xu(h,k);if(M===void 0)continue;let N=(l=h.attributes.selectionPriority)!=null?l:1,U=h.attributes.id,L=by(h),B=[];e.segmentTemplate!==void 0&&B.push(e.segmentTemplate),h.children.segmentTemplate!==void 0&&B.push(h.children.segmentTemplate);let C={availabilityTimeComplete:A,availabilityTimeOffset:P,baseURLs:Qt(e.baseURLs,y.baseURLs),contentProtectionParser:e.contentProtectionParser,manifestBoundsCalculator:e.manifestBoundsCalculator,end:e.end,isDynamic:e.isDynamic,isLastPeriod:e.isLastPeriod,manifestProfiles:e.manifestProfiles,parentSegmentTemplates:B,receivedTime:e.receivedTime,start:e.start,unsafelyBaseOnPreviousAdaptation:null},w=Array.isArray(T)?q(T,ye=>ye.schemeIdUri==="http://dashif.org/guidelines/trickmode"):void 0,F=(f=w==null?void 0:w.value)==null?void 0:f.split(" "),K=F!==void 0,{accessibilities:Y}=y,ie;v!==void 0&&v.some(ye=>ye.value==="dub")&&(ie=!0);let j;M!=="text"?j=!1:j=hy(Y,v);let Q;M==="text"&&v!==void 0&&v.some(ye=>ye.value==="forced-subtitle"||ye.value==="forced_subtitle")&&(Q=!0);let ne;M!=="audio"?ne=!1:Y!==void 0&&(ne=Y.some(gy));let X;M!=="video"?X=!1:Y!==void 0&&(X=Y.some(Iy));let de=yy(h,{isAudioDescription:ne,isForcedSubtitle:Q,isClosedCaption:j,isSignInterpreted:X,isTrickModeTrack:K,type:M});for(;J(a,de);)de+="-dup";let ue=de;a.push(de),C.unsafelyBaseOnPreviousAdaptation=(g=(m=e.unsafelyBaseOnPreviousPeriod)==null?void 0:m.getAdaptation(de))!=null?g:null;let ve=Ou(k,h,C);if(M==="thumbnails"){let ye=Sy(h,ve);ye!==null&&r.push(...ye);continue}let ce={id:de,representations:ve,type:M,isTrickModeTrack:K};if(_(h.attributes.language)||(ce.language=h.attributes.language),_(j)||(ce.closedCaption=j),_(ne)||(ce.audioDescription=ne),ie===!0&&(ce.isDub=!0),Q!==void 0&&(ce.forcedSubtitles=Q),X===!0&&(ce.isSignInterpreted=!0),E!==void 0&&(ce.label=E),F!==void 0)i.push({adaptation:ce,trickModeAttachedAdaptationIds:F});else{let ye=-1;for(let ct of L){let Et=o[ct];if(Et!==void 0&&Et.newID!==ue&&J(Et.adaptationSetSwitchingIDs,U)){ye=Te(t[M],Be=>Be[0].id===ct);let $=t[M][ye];if($!==void 0&&$[0].audioDescription===ce.audioDescription&&$[0].closedCaption===ce.closedCaption&&$[0].language===ce.language){p.info("dash",'merging "switchable" AdaptationSets',{originalID:U,id:ct}),$[0].representations.push(...ce.representations),$[1]={priority:Math.max(N,$[1].priority),isMainAdaptation:R||$[1].isMainAdaptation,indexInMpd:Math.min(I,$[1].indexInMpd)};break}}}ye<0&&t[M].push([ce,{priority:N,isMainAdaptation:R,indexInMpd:I}])}!_(U)&&_(o[U])&&(o[U]={newID:ue,adaptationSetSwitchingIDs:L})}let s=an.reduce((I,h)=>{let y=t[h];return y.length>0&&(y.sort(Wm),I[h]=y.map(([T])=>T)),I},{});return t.video.sort(Wm),Km(s,i),{adaptations:s,thumbnailTracks:r}}function Sy(n,e){var r,i;let t=[];for(let o=0;o<e.length;o++){let a=e[o];if(a!==void 0){if(a.mimeType===void 0){p.warn("dash","Invalid thumbnails Representation, no mime-type");continue}let s=Au(n,n.children.representations[o]);if(s===null)continue;if(a.height===void 0){p.warn("dash","Invalid thumbnails Representation, no height information");continue}if(a.width===void 0){p.warn("dash","Invalid thumbnails Representation, no width information");continue}let d=(r=a.index.getFirstAvailablePosition())!=null?r:void 0,u=(i=a.index.getEnd())!=null?i:void 0,c,l=a.index.getTargetSegmentDuration();l!==void 0&&l.isPrecize?c=l.duration:p.warn("dash","Cannot produce duration estimate for thumbnail track"),t.push({id:a.id,cdnMetadata:a.cdnMetadata,index:a.index,mimeType:a.mimeType,height:a.height,width:a.width,horizontalTiles:s.horizontalTiles,verticalTiles:s.verticalTiles,start:d,end:u,tileDuration:c===void 0?void 0:c/(s.horizontalTiles*s.verticalTiles)})}}return t}function Wm(n,e){let t=e[1].priority-n[1].priority;return t!==0?t:n[1].isMainAdaptation!==e[1].isMainAdaptation?n[1].isMainAdaptation?-1:1:n[1].indexInMpd-e[1].indexInMpd}var Ty=Fe();function Lu(n,e){var a,s,d,u,c;let t=[],r=Mu(n,e);if(r.length!==n.length)throw new Error("MPD parsing error: the time information are incoherent.");let{isDynamic:i,manifestBoundsCalculator:o}=e;!i&&!_(e.duration)&&o.setLastPosition(e.duration);for(let l=n.length-1;l>=0;l--){let f=l===n.length-1,m=n[l],g=e.xlinkInfos.get(m),I=Qt(e.baseURLs,m.children.baseURLs),{periodStart:h,periodDuration:y,periodEnd:T}=r[l],v;for(_(m.attributes.id)?(v="gen-dash-period-"+Ty(),p.warn("dash","No usable id found in the Period. Generating one.",{periodId:v})):v=m.attributes.id;t.some(K=>K.id===v);)v+="-dup";let E=g!==void 0?g.receivedTime:e.receivedTime,R=(s=(a=e.unsafelyBaseOnPreviousManifest)==null?void 0:a.getPeriod(v))!=null?s:null,k=m.attributes.availabilityTimeComplete,A=m.attributes.availabilityTimeOffset,{manifestProfiles:P,contentProtectionParser:M}=e,{segmentTemplate:N}=m.children;M.addReferences((d=m.children.contentProtections)!=null?d:[]);let U={availabilityTimeComplete:k,availabilityTimeOffset:A,baseURLs:I,contentProtectionParser:M,manifestBoundsCalculator:o,end:T,isDynamic:i,isLastPeriod:f,manifestProfiles:P,receivedTime:E,segmentTemplate:N,start:h,unsafelyBaseOnPreviousPeriod:R},{adaptations:L,thumbnailTracks:B}=Du(m.children.adaptations,U),C=((u=e.xmlNamespaces)!=null?u:[]).concat((c=m.attributes.namespaces)!=null?c:[]),w=Ey(m.children.eventStreams,h,C),F={id:v,start:h,end:T,duration:y,thumbnailTracks:B,adaptations:L,streamEvents:w};if(t.unshift(F),!o.lastPositionIsKnown()){let K=_y(L);if(!i)typeof K=="number"&&o.setLastPosition(K);else if(typeof K=="number"){let Y=z()/1e3;o.setLastPosition(K,Y)}else{let Y=Hm(e,h);if(Y!==void 0){let[ie,j]=Y;o.setLastPosition(ie,j)}}}}if(e.isDynamic&&!o.lastPositionIsKnown()){let l=Hm(e,0);if(l!==void 0){let[f,m]=l;o.setLastPosition(f,m)}}return Pu(t)}function Hm(n,e){if(_(n.clockOffset)){let t=Date.now()/1e3;if(t>=e){p.warn("dash","no clock synchronization mechanism found. Using the system clock instead.");let r=t-n.availabilityStartTime,i=z()/1e3;return[r,i]}}else{let t=n.clockOffset/1e3-n.availabilityStartTime,r=z()/1e3,i=r+t;if(i>=e)return[i,r]}}function _y(n){let e=null,t=!0,r=er(n).filter(o=>!_(o)),i=ir(r,o=>o);for(let o of i){let a=o.representations;for(let s of a){let d=s.index.getLastAvailablePosition();d!==null&&(t=!1,typeof d=="number"&&(e=_(e)?d:Math.max(e,d)))}}if(_(e)){if(t)return null}else return e}function Ey(n,e,t){var i,o;let r=[];for(let a of n){let{schemeIdUri:s="",timescale:d=1}=a.attributes,u=t.concat((i=a.attributes.namespaces)!=null?i:[]);for(let c of a.children.events)if(c.eventStreamData!==void 0){let l=((o=c.presentationTime)!=null?o:0)/d+e,f=c.duration===void 0?void 0:l+c.duration/d,m,g;try{g={namespaces:u,data:typeof c.eventStreamData=="string"?c.eventStreamData:he(new Uint8Array(c.eventStreamData))}}catch(I){p.error("dash","Error while parsing event-stream:",I instanceof Error?I.message:"Unknown error")}r.push({start:l,end:f,id:c.id,data:{type:"dash-event-stream",value:{schemeIdUri:s,timescale:d,element:m,xmlData:g}}})}}return r}function Sr(n,e,t,r,i=new WeakMap){let{children:o,attributes:a}=n;if(_(e.externalClockOffset)){let d=a.type==="dynamic",u=q(o.utcTimings,f=>f.schemeIdUri==="urn:mpeg:dash:utc:direct:2014"&&!_(f.value)),c=!_(u)&&!_(u.value)?Qa(u.value):void 0,l=!_(c)&&!isNaN(c)?c:void 0;if(!_(l)&&r!==!0)e.externalClockOffset=l;else if(d&&r!==!0){let f=Eu(n);if(!_(f)&&f.length>0)return{type:"needs-clock",value:{url:f,continue:function(g){return g.success?(e.externalClockOffset=Qa(g.data),Sr(n,e,t,!0)):(t.push(g.error),p.warn("dash","Error on fetching the clock ressource",g.error),Sr(n,e,t,!0))}}}}}let s=[];for(let d=0;d<o.periods.length;d++){let{xlinkHref:u,xlinkActuate:c}=o.periods[d].attributes;!_(u)&&c==="onLoad"&&s.push({index:d,ressource:u})}return s.length===0?vy(n,e,t,i):{type:"needs-xlinks",value:{xlinksUrls:s.map(({ressource:d})=>d),continue:function(u){if(u.length!==s.length)throw new Error("DASH parser: wrong number of loaded ressources.");for(let c=u.length-1;c>=0;c--){let l=s[c].index,{parsed:f,warnings:m,receivedTime:g,sendingTime:I,url:h}=u[c];m.length>0&&t.push(...m);for(let y of f)i.set(y,{receivedTime:g,sendingTime:I,url:h});o.periods.splice(l,1,...f)}return Sr(n,e,t,r,i)}}}}function vy(n,e,t,r){var C,w,F,K,Y;let{children:i,attributes:o}=n,a=o.type==="dynamic",s=e.url!==void 0?[{url:e.url.substring(0,Li(e.url))}]:[],d=Qt(s,i.baseURLs),u=Cu(o,e.referenceDateTime),c=o.timeShiftBufferDepth,l=o.maxSegmentDuration,{externalClockOffset:f,unsafelyBaseOnPreviousManifest:m}=e,{externalClockOffset:g}=e,I=new lo({availabilityStartTime:u,isDynamic:a,timeShiftBufferDepth:c,serverTimestampOffset:g}),h=new uo;h.addReferences((C=i.contentProtections)!=null?C:[]);let y={availabilityStartTime:u,baseURLs:d,clockOffset:f,contentProtectionParser:h,duration:o.duration,isDynamic:a,manifestBoundsCalculator:I,manifestProfiles:n.attributes.profiles,receivedTime:e.manifestReceivedTime,unsafelyBaseOnPreviousManifest:m,xlinkInfos:r,xmlNamespaces:n.attributes.namespaces},T=Lu(i.periods,y);h.finalize();let v=o.duration,E,R,k=null,A;o.minimumUpdatePeriod!==void 0&&o.minimumUpdatePeriod>=0&&(E=o.minimumUpdatePeriod===0?O.getCurrent().DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:o.minimumUpdatePeriod);let{minimumSafePosition:P,maximumSafePosition:M,maximumUnsafePosition:N}=ku(T),U=z();if(a){let ie;M!==void 0?ie=M:g===void 0?(p.warn("dash","use system clock to define maximum position"),ie=Date.now()/1e3-u):ie=(z()+g)/1e3-u;let j=I.getEstimatedLiveEdge();j===void 0&&(N!==void 0?j=N:j=ie),A={isLinear:!0,maximumSafePosition:ie,livePosition:j,time:U},R=P,k=c!=null?c:null,k!==null&&(k+=l!=null?l:0),k!==null&&R!==void 0&&j-R>k&&(k=j-R)}else{R=P,R===void 0&&(R=(F=(w=T[0])==null?void 0:w.start)!=null?F:0);let ie=v!=null?v:1/0;if(T[T.length-1]!==void 0){let j=T[T.length-1],Q=(K=j.end)!=null?K:j.duration!==void 0?j.start+j.duration:void 0;Q!==void 0&&Q<ie&&(ie=Q)}M!==void 0&&M<ie&&(ie=M),A={isLinear:!1,maximumSafePosition:ie,livePosition:void 0,time:U}}let L=!a||n.attributes.minimumUpdatePeriod===void 0&&(((Y=T[T.length-1])==null?void 0:Y.end)!==void 0||n.attributes.duration!==void 0);return{type:"done",value:{parsed:{availabilityStartTime:u,clockOffset:e.externalClockOffset,isDynamic:a,isLive:a,isLastPeriodKnown:L,periods:T,publishTime:o.publishTime,suggestedPresentationDelay:o.suggestedPresentationDelay,transportType:"dash",timeBounds:{minimumSafePosition:R,timeshiftDepth:k,maximumTimeData:A},lifetime:E,uris:_(e.url)?i.locations:[e.url,...i.locations]},warnings:t}}}var qm=Sr;var Ry=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,ky=/([0-9]+)-([0-9]+)/;function tt(n,e){return n==="true"?[!0,null]:n==="false"?[!1,null]:[!1,new pt(`\`${e}\` property is not a boolean value but "${n}"`)]}function Pe(n,e){let t=parseInt(n,10);return isNaN(t)?[null,new pt(`\`${e}\` property is not an integer value but "${n}"`)]:[t,null]}function ut(n,e){if(n==="INF")return[1/0,null];let t=parseFloat(n);return isNaN(t)?[null,new pt(`\`${e}\` property is invalid: "${n}"`)]:[t,null]}function Nu(n,e){if(n==="true")return[!0,null];if(n==="false")return[!1,null];let t=parseInt(n,10);return isNaN(t)?[null,new pt(`\`${e}\` property is not a boolean nor an integer but "${n}"`)]:[t,null]}function Za(n,e){let t=Date.parse(n);return isNaN(t)?[null,new pt(`\`${e}\` is in an invalid date format: "${n}"`)]:[new Date(Date.parse(n)).getTime()/1e3,null]}function Pt(n,e){if(!x(n))return[0,new pt(`\`${e}\` property is empty`)];let t=Ry.exec(n);return t===null?[null,new pt(`\`${e}\` property has an unrecognized format "${n}"`)]:[parseFloat(x(t[2])?t[2]:"0")*365*24*60*60+parseFloat(x(t[4])?t[4]:"0")*30*24*60*60+parseFloat(x(t[6])?t[6]:"0")*24*60*60+parseFloat(x(t[8])?t[8]:"0")*60*60+parseFloat(x(t[10])?t[10]:"0")*60+parseFloat(x(t[12])?t[12]:"0"),null]}function qn(n,e){let t=ky.exec(n);return t===null?[null,new pt(`\`${e}\` property has an unrecognized format "${n}"`)]:[[+t[1],+t[2]],null]}function Gm(n,e){try{return[Ct(n),null]}catch(t){return[null,new pt(`\`${e}\` is not a valid base64 string: "${n}"`)]}}function Tr(n,e){let t=/^(\d+)\/(\d+)$/.exec(n);return t!==null?[+t[1]/+t[2],null]:ut(n,e)}function je(n){let e,t;for(let r of Object.keys(n.attributes)){let i=n.attributes[r];if(!_(i))switch(r){case"schemeIdUri":e=i;break;case"value":t=i;break}}return{schemeIdUri:e,value:t}}function Ye(n,e){return function(t,{asKey:r,parser:i,dashName:o}){let[a,s]=i(t,o);s!==null&&(p.warn("dash","failed to parse DASH value:",s.message,{dashName:o}),e.push(s)),a!==null&&(n[r]=a)}}var pt=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="MPDError"}};function In(n){return Ha(n)}function $t(n){let e=typeof n=="string"?n:In(n.children),t=[];return e===null||e.length===0?[void 0,t]:[{value:e},t]}function Cy(n){let e=[],t=[];for(let r=0;r<n.length;r++){let i=n[r];if(typeof i!="string"&&i.tagName==="cenc:pssh"){let o=In(i.children);if(o!==null&&o.length>0){let[a,s]=Gm(o,"cenc:pssh");s!==null&&(p.warn("dash","Content protection parsing failure",s.message),e.push(s)),a!==null&&t.push(a)}}}return[{cencPssh:t},e]}function Py(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!_(r))switch(t){case"schemeIdUri":e.schemeIdUri=r;break;case"value":e.value=r;break;case"cenc:default_KID":e.keyId=st(r.replace(/-/g,""));break;case"ref":e.ref=r;break;case"refId":e.refId=r;break}}return e}function Xt(n){let[e,t]=Cy(n.children),r=Py(n);return[{children:e,attributes:r},t]}function Bu(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!_(r))switch(t){case"id":e.id=r;break;case"lang":e.language=r;break;case"contentType":e.contentType=r;break;case"par":e.par=r;break}}return e}function Uu(n){let e={},t=[],r=Ye(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!_(o))switch(i){case"range":r(o,{asKey:"range",parser:qn,dashName:"range"});break;case"sourceURL":e.media=o;break}}return[e,t]}function Zt(n){let e={},t=[],r=Ye(e,t),i=n.children;for(let o=0;o<i.length;o++){let a=i[o];if(typeof a!="string"&&a.tagName==="Initialization"){let[s,d]=Uu(a);e.initialization=s,t=t.concat(d)}}for(let o of Object.keys(n.attributes)){let a=n.attributes[o];if(!_(a))switch(o){case"timescale":r(a,{asKey:"timescale",parser:Pe,dashName:"timescale"});break;case"presentationTimeOffset":r(a,{asKey:"presentationTimeOffset",parser:ut,dashName:"presentationTimeOffset"});break;case"indexRange":r(a,{asKey:"indexRange",parser:qn,dashName:"indexRange"});break;case"indexRangeExact":r(a,{asKey:"indexRangeExact",parser:tt,dashName:"indexRangeExact"});break;case"availabilityTimeOffset":r(a,{asKey:"availabilityTimeOffset",parser:ut,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(a,{asKey:"availabilityTimeComplete",parser:tt,dashName:"availabilityTimeComplete"});break;case"duration":r(a,{asKey:"duration",parser:Pe,dashName:"duration"});break;case"startNumber":r(a,{asKey:"startNumber",parser:Pe,dashName:"startNumber"});break;case"endNumber":r(a,{asKey:"endNumber",parser:Pe,dashName:"endNumber"});break}}return[e,t]}function Fu(n){let e={},t=[],r=Ye(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!_(o))switch(i){case"media":e.media=o;break;case"indexRange":r(o,{asKey:"indexRange",parser:qn,dashName:"indexRange"});break;case"index":e.index=o;break;case"mediaRange":r(o,{asKey:"mediaRange",parser:qn,dashName:"mediaRange"});break}}return[e,t]}function co(n){let[e,t]=Zt(n),r=t,i=[],o=n.children;for(let s=0;s<o.length;s++){let d=o[s];if(typeof d!="string"&&d.tagName==="SegmentURL"){let[u,c]=Fu(d);i.push(u),r=r.concat(c)}}return[G(e,{list:i}),r]}function Ku(n){let e=n.children;return function(){for(let t=e.length-1;t>=0;t--){let r=e[t];(typeof r=="string"||r.tagName!=="S")&&e.splice(t,1)}return e}}function Gn(n){let[e,t]=Zt(n),r=t,i;for(let s=0;s<n.children.length;s++){let d=n.children[s];typeof d!="string"&&d.tagName==="SegmentTimeline"&&(i=Ku(d))}let o=G({},e,{duration:e.duration,timelineParser:i}),a=Ye(o,r);for(let s of Object.keys(n.attributes)){let d=n.attributes[s];if(!_(d))switch(s){case"initialization":_(o.initialization)&&(o.initialization={media:d});break;case"index":o.index=d;break;case"availabilityTimeOffset":a(d,{asKey:"availabilityTimeOffset",parser:ut,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":a(d,{asKey:"availabilityTimeComplete",parser:tt,dashName:"availabilityTimeComplete"});break;case"media":o.media=d;break;case"bitstreamSwitching":a(d,{asKey:"bitstreamSwitching",parser:tt,dashName:"bitstreamSwitching"});break}}return[o,r]}function My(n){let e={baseURLs:[]},t=[],r=[];for(let i=0;i<n.length;i++){let o=n[i];if(typeof o!="string")switch(o.tagName){case"BaseURL":{let[a,s]=$t(o);a!==void 0&&e.baseURLs.push(a),r=r.concat(s);break}case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(je(o));break;case"SegmentBase":{let[a,s]=Zt(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=co(o);r=r.concat(s),e.segmentList=a;break}case"SegmentTemplate":{let[a,s]=Gn(o);r=r.concat(s),e.segmentTemplate=a;break}case"ContentProtection":{let[a,s]=Xt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}case"EssentialProperty":_(e.essentialProperties)?e.essentialProperties=[je(o)]:e.essentialProperties.push(je(o));break;case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[je(o)]:e.supplementalProperties.push(je(o));break}}return t.length>0&&(e.contentProtections=t),[e,r]}function Ay(n){let e={},t=[],r=Ye(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!_(o))switch(i){case"audioSamplingRate":e.audioSamplingRate=o;break;case"bandwidth":r(o,{asKey:"bitrate",parser:Pe,dashName:"bandwidth"});break;case"codecs":e.codecs=o;break;case"codingDependency":r(o,{asKey:"codingDependency",parser:tt,dashName:"codingDependency"});break;case"frameRate":r(o,{asKey:"frameRate",parser:Tr,dashName:"frameRate"});break;case"height":r(o,{asKey:"height",parser:Pe,dashName:"height"});break;case"id":e.id=o;break;case"maxPlayoutRate":r(o,{asKey:"maxPlayoutRate",parser:ut,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o,{asKey:"maximumSAPPeriod",parser:ut,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o;break;case"profiles":e.profiles=o;break;case"qualityRanking":r(o,{asKey:"qualityRanking",parser:Pe,dashName:"qualityRanking"});break;case"scte214:supplementalCodecs":e.supplementalCodecs=o;break;case"segmentProfiles":e.segmentProfiles=o;break;case"width":r(o,{asKey:"width",parser:Pe,dashName:"width"});break;case"availabilityTimeOffset":r(o,{asKey:"availabilityTimeOffset",parser:ut,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o,{asKey:"availabilityTimeComplete",parser:tt,dashName:"availabilityTimeComplete"});break}}return e.bitrate===void 0&&t.push(new pt("No bitrate found on a Representation")),[e,t]}function jm(n){let[e,t]=My(n.children),[r,i]=Ay(n),o=t.concat(i);return[{children:e,attributes:r},o]}function xy(n){let e={baseURLs:[],representations:[]},t=[],r=[];for(let i=0;i<n.length;i++){let o=n[i];if(typeof o!="string")switch(o.tagName){case"Accessibility":e.accessibilities===void 0?e.accessibilities=[je(o)]:e.accessibilities.push(je(o));break;case"BaseURL":{let[a,s]=$t(o);a!==void 0&&e.baseURLs.push(a),s.length>0&&(r=r.concat(s));break}case"ContentComponent":e.contentComponent=Bu(o);break;case"EssentialProperty":_(e.essentialProperties)?e.essentialProperties=[je(o)]:e.essentialProperties.push(je(o));break;case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(je(o));break;case"Label":{let a=In(o.children);a!=null&&(e.label=a);break}case"Representation":{let[a,s]=jm(o);e.representations.push(a),s.length>0&&(r=r.concat(s));break}case"Role":_(e.roles)?e.roles=[je(o)]:e.roles.push(je(o));break;case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[je(o)]:e.supplementalProperties.push(je(o));break;case"SegmentBase":{let[a,s]=Zt(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=co(o);e.segmentList=a,s.length>0&&(r=r.concat(s));break}case"SegmentTemplate":{let[a,s]=Gn(o);e.segmentTemplate=a,s.length>0&&(r=r.concat(s));break}case"ContentProtection":{let[a,s]=Xt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}}}return t.length>0&&(e.contentProtections=t),[e,r]}function wy(n){let e={},t=[],r=Ye(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!_(o))switch(i){case"id":e.id=o;break;case"group":r(o,{asKey:"group",parser:Pe,dashName:"group"});break;case"lang":e.language=o;break;case"contentType":e.contentType=o;break;case"par":e.par=o;break;case"minBandwidth":r(o,{asKey:"minBitrate",parser:Pe,dashName:"minBandwidth"});break;case"maxBandwidth":r(o,{asKey:"maxBitrate",parser:Pe,dashName:"maxBandwidth"});break;case"minWidth":r(o,{asKey:"minWidth",parser:Pe,dashName:"minWidth"});break;case"maxWidth":r(o,{asKey:"maxWidth",parser:Pe,dashName:"maxWidth"});break;case"minHeight":r(o,{asKey:"minHeight",parser:Pe,dashName:"minHeight"});break;case"maxHeight":r(o,{asKey:"maxHeight",parser:Pe,dashName:"maxHeight"});break;case"minFrameRate":r(o,{asKey:"minFrameRate",parser:Tr,dashName:"minFrameRate"});break;case"maxFrameRate":r(o,{asKey:"maxFrameRate",parser:Tr,dashName:"maxFrameRate"});break;case"selectionPriority":r(o,{asKey:"selectionPriority",parser:Pe,dashName:"selectionPriority"});break;case"segmentAlignment":r(o,{asKey:"segmentAlignment",parser:Nu,dashName:"segmentAlignment"});break;case"subsegmentAlignment":r(o,{asKey:"subsegmentAlignment",parser:Nu,dashName:"subsegmentAlignment"});break;case"bitstreamSwitching":r(o,{asKey:"bitstreamSwitching",parser:tt,dashName:"bitstreamSwitching"});break;case"audioSamplingRate":e.audioSamplingRate=o;break;case"codecs":e.codecs=o;break;case"scte214:supplementalCodecs":e.supplementalCodecs=o;break;case"codingDependency":r(o,{asKey:"codingDependency",parser:tt,dashName:"codingDependency"});break;case"frameRate":r(o,{asKey:"frameRate",parser:Tr,dashName:"frameRate"});break;case"height":r(o,{asKey:"height",parser:Pe,dashName:"height"});break;case"maxPlayoutRate":r(o,{asKey:"maxPlayoutRate",parser:ut,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o,{asKey:"maximumSAPPeriod",parser:ut,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o;break;case"profiles":e.profiles=o;break;case"segmentProfiles":e.segmentProfiles=o;break;case"width":r(o,{asKey:"width",parser:Pe,dashName:"width"});break;case"availabilityTimeOffset":r(o,{asKey:"availabilityTimeOffset",parser:ut,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o,{asKey:"availabilityTimeComplete",parser:tt,dashName:"availabilityTimeComplete"});break}}return[e,t]}function Ym(n){let e=n.children,[t,r]=xy(e),[i,o]=wy(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Oy(n){let e={},t=[],r=Ye(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!_(o))switch(i){case"schemeIdUri":e.schemeIdUri=o;break;case"value":e.value=o;break;case"timescale":r(o,{asKey:"timescale",parser:Pe,dashName:"timescale"});break;default:Le(i,"xmlns:")&&(e.namespaces===void 0&&(e.namespaces=[]),e.namespaces.push({key:i.substring(6),value:o}));break}}return[e,t]}function Qm(n,e){let[t,r]=Oy(n),i=[];for(let o of n.children)if(typeof o!="string"&&o.tagName==="Event"){let a={};if(_(o.attributes.id)||(a.id=o.attributes.id),!_(o.attributes.presentationTime)){let[s,d]=Pe(o.attributes.presentationTime,"presentationTime");d!==null&&r.push(d),s!==null&&(a.presentationTime=s)}if(!_(o.attributes.duration)){let[s,d]=Pe(o.attributes.duration,"duration");d!==null&&r.push(d),s!==null&&(a.duration=s)}if(o.posStart<o.posEnd){let s=e.substring(o.posStart,o.posEnd);a.eventStreamData=s}i.push(a)}return[{children:{events:i},attributes:t},r]}function Dy(n,e){let t=[],r=[],i,o=[],a=[],s=[];for(let d=0;d<n.length;d++){let u=n[d];if(typeof u!="string")switch(u.tagName){case"BaseURL":{let[c,l]=$t(u);c!==void 0&&t.push(c),a=a.concat(l);break}case"AdaptationSet":{let[c,l]=Ym(u);r.push(c),a=a.concat(l);break}case"EventStream":{let[c,l]=Qm(u,e);s.push(c),a=a.concat(l);break}case"SegmentTemplate":{let[c,l]=Gn(u);i=c,l.length>0&&(a=a.concat(l));break}case"ContentProtection":{let[c,l]=Xt(u);l.length>0&&(a=a.concat(l)),c!==void 0&&o.push(c);break}}}return[{baseURLs:t,adaptations:r,eventStreams:s,segmentTemplate:i,contentProtections:o},a]}function Ly(n){let e={},t=[],r=Ye(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!_(o))switch(i){case"id":e.id=o;break;case"start":r(o,{asKey:"start",parser:Pt,dashName:"start"});break;case"duration":r(o,{asKey:"duration",parser:Pt,dashName:"duration"});break;case"bitstreamSwitching":r(o,{asKey:"bitstreamSwitching",parser:tt,dashName:"bitstreamSwitching"});break;case"xlink:href":e.xlinkHref=o;break;case"xlink:actuate":e.xlinkActuate=o;break;default:Le(i,"xmlns:")&&(e.namespaces===void 0&&(e.namespaces=[]),e.namespaces.push({key:i.substring(6),value:o}));break}}return[e,t]}function Ja(n,e){let[t,r]=Dy(n.children,e),[i,o]=Ly(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Ny(n,e){let t=[],r=[],i=[],o=[],a=[],s=[];for(let d=0;d<n.length;d++){let u=n[d];if(typeof u!="string")switch(u.tagName){case"BaseURL":{let[c,l]=$t(u);c!==void 0&&t.push(c),s=s.concat(l);break}case"Location":r.push(In(u.children));break;case"Period":{let[c,l]=Ja(u,e);i.push(c),s=s.concat(l);break}case"UTCTiming":{let c=je(u);o.push(c);break}case"ContentProtection":{let[c,l]=Xt(u);l.length>0&&(s=s.concat(l)),c!==void 0&&a.push(c);break}}}return[{baseURLs:t,locations:r,periods:i,utcTimings:o,contentProtections:a},s]}function By(n){let e={},t=[],r=Ye(e,t);for(let i of Object.keys(n.attributes)){let o=n.attributes[i];if(!_(o))switch(i){case"id":e.id=o;break;case"profiles":e.profiles=o;break;case"type":e.type=o;break;case"availabilityStartTime":r(o,{asKey:"availabilityStartTime",parser:Za,dashName:"availabilityStartTime"});break;case"availabilityEndTime":r(o,{asKey:"availabilityEndTime",parser:Za,dashName:"availabilityEndTime"});break;case"publishTime":r(o,{asKey:"publishTime",parser:Za,dashName:"publishTime"});break;case"mediaPresentationDuration":r(o,{asKey:"duration",parser:Pt,dashName:"mediaPresentationDuration"});break;case"minimumUpdatePeriod":r(o,{asKey:"minimumUpdatePeriod",parser:Pt,dashName:"minimumUpdatePeriod"});break;case"minBufferTime":r(o,{asKey:"minBufferTime",parser:Pt,dashName:"minBufferTime"});break;case"timeShiftBufferDepth":r(o,{asKey:"timeShiftBufferDepth",parser:Pt,dashName:"timeShiftBufferDepth"});break;case"suggestedPresentationDelay":r(o,{asKey:"suggestedPresentationDelay",parser:Pt,dashName:"suggestedPresentationDelay"});break;case"maxSegmentDuration":r(o,{asKey:"maxSegmentDuration",parser:Pt,dashName:"maxSegmentDuration"});break;case"maxSubsegmentDuration":r(o,{asKey:"maxSubsegmentDuration",parser:Pt,dashName:"maxSubsegmentDuration"});break;default:Le(i,"xmlns:")&&(e.namespaces===void 0&&(e.namespaces=[]),e.namespaces.push({key:i.substring(6),value:o}));break}}return[e,t]}function $m(n,e){let[t,r]=Ny(n.children,e),[i,o]=By(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Vu(n,e){let t=to(n),r=t[t.length-1];if(r===void 0||typeof r=="string"||r.tagName!=="MPD")throw new Error("DASH Parser: document root should be MPD");let[i,o]=$m(r,n),a=qm(i,e,o);return s(a);function s(d){if(d.type==="done")return d;if(d.type==="needs-clock")return{type:"needs-resources",value:{urls:[d.value.url],format:"string",continue(u){if(u.length!==1)throw new Error("DASH parser: wrong number of loaded ressources.");let c=d.value.continue(u[0].responseData);return s(c)}}};if(d.type==="needs-xlinks")return{type:"needs-resources",value:{urls:d.value.xlinksUrls,format:"string",continue(u){let c=[];for(let f=0;f<u.length;f++){let{responseData:m,receivedTime:g,sendingTime:I,url:h}=u[f];if(!m.success)throw m.error;let y="<root>"+m.data+"</root>",T=to(y),v=T[T.length-1];if(v===void 0||typeof v=="string")throw new Error("DASH parser: Invalid external ressources");let E=v.children,R=[],k=[];for(let A=0;A<E.length;A++){let P=E[A];if(typeof P=="string"||P.tagName!=="Period")continue;let[M,N]=Ja(P,y);k.push(...N),R.push(M)}c.push({url:h,receivedTime:g,sendingTime:I,parsed:R,warnings:k})}let l=d.value.continue(c);return s(l)}}};we(d)}}var Xm=Vu;function Ze(n,e){if(e.length===0)return n;let t,r="",i=n.indexOf("#"),o=n;i>=0&&(r=n.substring(i),o=n.substring(0,i));let a=o.indexOf("?");a===-1?t="?":a+1===o.length?t="":t="&";let s=o+t;for(let d=0;d<e.length;d++){let u=e[d];u[1]===null?s+=u[0]:s+=`${u[0]}=${u[1]}`,d<e.length-1&&(s+="&")}return r.length>0&&(s+=r),s}function zu(n,e){return(t,r,i)=>new Promise((o,a)=>{let s=Date.now()-z(),d=!1,f={reject:I=>{var v,E;if(d||i.isCancelled())return;d=!0,i.deregister(g);let h=I,y=(v=h==null?void 0:h.message)!=null?v:"Unknown error when fetching the Manifest through a custom manifestLoader.",T=new gt(y,(E=h==null?void 0:h.canRetry)!=null?E:!1,h==null?void 0:h.xhr);a(T)},resolve:I=>{if(d||i.isCancelled())return;d=!0,i.deregister(g);let h=I.receivingTime!==void 0?I.receivingTime-s:void 0,y=I.sendingTime!==void 0?I.sendingTime-s:void 0;o({responseData:I.data,size:I.size,requestDuration:I.duration,url:I.url,receivedTime:h,sendingTime:y})},fallback:()=>{d||i.isCancelled()||(d=!0,i.deregister(g),e(t,r,i).then(o,a))}},m=n({url:t,timeout:r.timeout,cmcdPayload:r.cmcdPayload},f);i.register(g);function g(I){d||(d=!0,typeof m=="function"&&m(),a(I))}})}function Uy(n){return function(t,r,i){var s,d;if(t===void 0)throw new Error("Cannot perform HTTP(s) request. URL not known");let o=((s=r.cmcdPayload)==null?void 0:s.type)==="query"?Ze(t,r.cmcdPayload.value):t,a=((d=r.cmcdPayload)==null?void 0:d.type)==="headers"?r.cmcdPayload.value:void 0;switch(n){case"arraybuffer":return xe({url:o,headers:a,responseType:"arraybuffer",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"text":return xe({url:o,headers:a,responseType:"text",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"document":return xe({url:o,headers:a,responseType:"document",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});default:we(n)}}}function fo({customManifestLoader:n},e,t){let r=Uy(e),i=typeof n!="function"?r:zu(n,r);return t!==null?t(i):i}function yn(n,e){if(e){if(Nt(n,1718909296)<0)throw new De("INTEGRITY_ERROR","Incomplete `ftyp` box");if(Nt(n,1836019574)<0)throw new De("INTEGRITY_ERROR","Incomplete `moov` box")}else{if(Nt(n,1836019558)<0)throw new De("INTEGRITY_ERROR","Incomplete `moof` box");if(Nt(n,1835295092)<0)throw new De("INTEGRITY_ERROR","Incomplete `mdat` box")}}function Mt(n,e){if(n==="audio"||n==="video")return e==="video/mp4"||e==="audio/mp4"?"mp4":e==="video/webm"||e==="audio/webm"?"webm":void 0;if(n==="text")return e==="application/mp4"?"mp4":void 0}function es(n){return(e,t,r,i,o)=>{return new Promise((s,d)=>{let u=new D,c=u.linkToSignal(i);u.signal.register(d),n(e,t,r,u.signal,me(oe({},o),{onNewChunk(f){try{a(f),o.onNewChunk(f)}catch(m){l(),u.cancel(),d(m)}}})).then(f=>{if(l(),!u.isUsed()){if(f.resultType==="segment-loaded")try{a(f.resultData.responseData)}catch(m){d(m);return}s(f)}},f=>{l(),d(f)});function l(){u.signal.deregister(d),c()}});function a(s){!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)||Mt(t.type,t.mimeType)!=="mp4"||yn(new Uint8Array(s),t.segment.isInit)}}}function Zm(n){return async(e,t,r)=>{let i=await n(e,t,r);return o(i.responseData),i;function o(a){if(typeof a=="string"){let s=a.length-1,d=["</","MPD",">"];for(let u=d.length-1;u>=0;u--){let c=d[u];for(;Fy(a[s]);)s--;for(let l=c.length-1;l>=0;l--){if(a[s]!==c[l])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(a instanceof ArrayBuffer){let s=a.byteLength-1,d=new DataView(a),u=[[60,47],[77,80,68],[62]];for(let c=u.length-1;c>=0;c--){let l=u[c];for(;Ky(d.getUint8(s));)s--;for(let f=l.length-1;f>=0;f--){if(d.getUint8(s)!==l[f])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(!_(Z.Document)&&a instanceof Z.Document&&a.documentElement.nodeName!=="MPD")throw new De("INTEGRITY_ERROR","MPD does not end with </MPD>")}}}function Fy(n){return n===" "||n===" "||n==="\r"||n===`
|
|
10
|
+
`}function Ky(n){return n===32||n===9||n===13||n===10}function Wu(n){let{referenceDateTime:e}=n,t=n.serverSyncInfos!==void 0?n.serverSyncInfos.serverTimestamp-n.serverSyncInfos.clientTime:void 0;return function(i,o,a,s,d){var T;let{responseData:u}=i,c=o.externalClockOffset,l=(T=i.url)!=null?T:o.originalUrl,f=t!=null?t:c,g={unsafelyBaseOnPreviousManifest:o.unsafeMode?o.previousManifest:null,url:l,referenceDateTime:e,externalClockOffset:f},I=pe.dashParsers;if(I.wasm===null||I.wasm.status==="uninitialized"||I.wasm.status==="failure")return p.debug("dash","WASM MPD Parser not initialized. Running JS one."),h();{let v=Hy(u);if(!qy(v))return p.info("dash","MPD doesn't seem to be UTF-8-encoded. Running JS parser instead of the WASM one."),h();if(I.wasm.status==="initialized"){p.debug("dash","Running WASM MPD Parser.");let E=I.wasm.runWasmParser(v,g);return y(E)}else return p.debug("dash","Awaiting WASM initialization before parsing the MPD."),I.wasm.waitForInitialization().catch(()=>{}).then(()=>{if(I.wasm===null||I.wasm.status!=="initialized")return p.warn("dash","WASM MPD parser initialization failed. Running JS parser instead"),h();p.debug("dash","Running WASM MPD Parser.");let R=I.wasm.runWasmParser(v,g);return y(R)})}function h(){if(I.js!==null){let v=Wy(u),E=I.js(v,g);return y(E)}else throw new Error("No MPD parser is imported")}function y(v){if(v.type==="done")return v.value.warnings.length>0&&a(v.value.warnings),s.isCancelled()?Promise.reject(s.cancellationError):{manifest:new pn(v.value.parsed,n),url:l};let{value:E}=v,R=E.urls.map(k=>d(()=>{let A=O.getCurrent().DEFAULT_REQUEST_TIMEOUT,P=O.getCurrent().DEFAULT_CONNECTION_TIMEOUT;return E.format==="string"?xe({url:k,responseType:"text",timeout:A,connectionTimeout:P,cancelSignal:s}):xe({url:k,responseType:"arraybuffer",timeout:A,connectionTimeout:P,cancelSignal:s})}).then(A=>{if(E.format==="string"){if(typeof A.responseData!="string")throw new Error("External DASH resources should have been a string");return G(A,{responseData:{success:!0,data:A.responseData}})}else{if(!(A.responseData instanceof ArrayBuffer))throw new Error("External DASH resources should have been ArrayBuffers");return G(A,{responseData:{success:!0,data:A.responseData}})}},A=>{let P=Ae(A,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"An unknown error occured when parsing ressources."});return G({},{size:void 0,requestDuration:void 0,responseData:{success:!1,error:P}})}));return Promise.all(R).then(k=>E.format==="string"?(Vy(k),y(E.continue(k))):(zy(k),y(E.continue(k))))}}}function Vy(n){b.CURRENT_ENV!==b.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&typeof t.data=="string")&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function zy(n){b.CURRENT_ENV!==b.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&t.data instanceof ArrayBuffer)&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function Wy(n){if(n instanceof ArrayBuffer)return he(new Uint8Array(n));if(typeof n=="string")return n;if(!_(Z.Document)&&n instanceof Z.Document)return n.documentElement.outerHTML;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function Hy(n){if(n instanceof ArrayBuffer)return n;if(typeof n=="string")return Re(n).buffer;if(!_(Z.Document)&&n instanceof Z.Document)return Re(n.documentElement.innerHTML).buffer;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function qy(n){let e=new DataView(n);return e.getUint16(0)===61371&&e.getUint8(2)===191?!0:!(e.getUint16(0)===65279||e.getUint16(0)===65534)}function lt([n,e]){return e===1/0?`bytes=${n}-`:`bytes=${n}-${e}`}function jn(n,e){return n===null?null:e.url===null?n.baseUrl:Un(n.baseUrl,e.url)}function mo(n,e,t,r,i){var u,c;let o=n;((u=t.cmcdPayload)==null?void 0:u.type)==="query"&&(o=Ze(o,t.cmcdPayload.value));let a=((c=t.cmcdPayload)==null?void 0:c.type)==="headers"?t.cmcdPayload.value:void 0;if(e.range===void 0)return xe({url:o,responseType:"arraybuffer",headers:a,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.indexRange===void 0)return xe({url:o,headers:me(oe({},a),{Range:lt(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.range[1]+1===e.indexRange[0])return xe({url:o,headers:me(oe({},a),{Range:lt([e.range[0],e.indexRange[1]])}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));let s=xe({url:o,headers:me(oe({},a),{Range:lt(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}),d=xe({url:o,headers:me(oe({},a),{Range:lt(e.indexRange)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress});return Promise.all([s,d]).then(([l,f])=>{let m=le(new Uint8Array(l.responseData),new Uint8Array(f.responseData)),g=Math.min(l.sendingTime,f.sendingTime),I=Math.max(l.receivedTime,f.receivedTime);return{resultType:"segment-loaded",resultData:{url:o,responseData:m,size:l.size+f.size,requestDuration:I-g,sendingTime:g,receivedTime:I}}})}async function po(n,e,t,r){let i=null;function o(s){let d=new Uint8Array(s.chunk),u=i!==null?le(i,d):d,c=Ia(u),l=c[0];i=c[1],!(l!==null&&(l.forEach(f=>{t.onNewChunk(f)}),r.isCancelled()))&&(t.onProgress({duration:s.duration,size:s.size,totalSize:s.totalSize}),r.isCancelled())}return{resultType:"chunk-complete",resultData:await qo({url:n,headers:e.headers,onData:o,timeout:e.timeout,connectionTimeout:e.connectionTimeout,cancelSignal:r})}}async function Jm(n,e,t,r,i,o){var f,m;if(e.segment.isInit)return mo(n,e.segment,r,o,i);let a=((f=r.cmcdPayload)==null?void 0:f.type)==="query"?Ze(n,r.cmcdPayload.value):n,s=((m=r.cmcdPayload)==null?void 0:m.type)==="headers"?r.cmcdPayload.value:void 0,{segment:d}=e,u;d.range!==void 0?u=me(oe({},s),{Range:lt(d.range)}):s!==void 0&&(u=s);let c=Mt(e.type,e.mimeType);if(t&&(c==="mp4"||c===void 0)){if(Ur())return po(a,{headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout},i,o);jt("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}return{resultType:"segment-loaded",resultData:await xe({url:a,responseType:"arraybuffer",headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:o,onProgress:i.onProgress})}}function Hu({lowLatencyMode:n,segmentLoader:e,checkMediaSegmentIntegrity:t}){return t!==!0?r:es(r);function r(i,o,a,s,d){let u=jn(i,o.segment);return u===null?Promise.resolve({resultType:"segment-created",resultData:null}):n||e===void 0?Jm(u,o,n,a,d,s):new Promise((c,l)=>{let f=!1,y={reject:k=>{var N,U;if(f||s.isCancelled())return;f=!0,s.deregister(R);let A=k,P=(N=A==null?void 0:A.message)!=null?N:"Unknown error when fetching a DASH segment through a custom segmentLoader.",M=new gt(P,(U=A==null?void 0:A.canRetry)!=null?U:!1,A==null?void 0:A.xhr);l(M)},resolve:k=>{if(f||s.isCancelled())return;f=!0,s.deregister(R);let A;k.data instanceof Uint8Array?k.data.buffer instanceof ArrayBuffer?A=k.data:A=k.data.slice():A=k.data,c({resultType:"segment-loaded",resultData:{responseData:A,size:k.size,requestDuration:k.duration}})},progress:k=>{f||s.isCancelled()||d.onProgress({duration:k.duration,size:k.size,totalSize:k.totalSize})},fallback:()=>{f||s.isCancelled()||(f=!0,s.deregister(R),Jm(u,o,n,a,d,s).then(c,l))}},T;o.segment.range!==void 0&&(T=[o.segment.range],o.segment.indexRange!==void 0&&T.push(o.segment.indexRange));let v={isInit:o.segment.isInit,timeout:a.timeout,byteRanges:T,trackType:o.type,url:u,cmcdPayload:a.cmcdPayload},E=e(v,y);s.register(R);function R(k){f||(f=!0,typeof E=="function"&&E(),l(k))}})}}var Gu=408125543,ep=357149030,Gy=2807729,jy=17545,Yy=475249515,Qy=187,$y=179,Xy=183,Zy=241;function bn(n,e,t,[r,i]){let o=r;for(;o<i;){let a=eb(t,o);if(a===null)return null;let{value:s,length:d}=a,u=o+d,c=tb(t,u);if(c===null)return null;let{length:l,value:f}=c,m=u+l,g=m+f;if(s===n)return[m,g];if(e.length>0){for(let I=0;I<e.length;I++)if(s===e[I]){let h=e.slice(I+1,e.length);return bn(n,h,t,[m,g])}}o=g}return null}function ts(n,e){let t=bn(Gy,[Gu,ep],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return 1e9/qu(n,t[0],r)}function Jy(n,e){let t=bn(jy,[Gu,ep],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return r===4?nb(n,t[0]):r===8?rb(n,t[0]):null}function ju(n,e){let t=bn(Gu,[],n,[e,n.length]);if(t===null)return null;let[r,i]=t,o=ts(n,r);if(o===null)return null;let a=Jy(n,r);if(a===null)return null;let s=bn(Yy,[],n,[r,i]);if(s===null)return null;let d=[],u=s[0];for(;u<s[1];){let l=bn(Qy,[],n,[u,s[1]]);if(l===null)break;let f=bn($y,[],n,[l[0],l[1]]);if(f===null)return null;let m=qu(n,f[0],f[1]-f[0]),g=bn(Zy,[Xy],n,[l[0],l[1]]);if(g===null)return null;let I=qu(n,g[0],g[1]-g[0])+r;d.push({time:m,rangeStart:I}),u=l[1]}let c=[];for(let l=0;l<d.length;l++){let f=d[l];l===d.length-1?c.push({time:f.time,timescale:o,duration:l===0?a:a-f.time,range:[f.rangeStart,1/0]}):c.push({time:f.time,timescale:o,duration:d[l+1].time-f.time,range:[f.rangeStart,d[l+1].rangeStart-1]})}return c}function tp(n,e){for(let t=1;t<=8;t++)if(n[e]>=Math.pow(2,8-t))return t}function eb(n,e){let t=tp(n,e);if(t===void 0)return p.warn("webm","unrepresentable length"),null;if(e+t>n.length)return p.warn("webm","impossible length",{offset:e,length:t,bufferLength:n.length}),null;let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function tb(n,e){let t=tp(n,e);if(t===void 0)return p.warn("webm","unrepresentable length"),null;if(e+t>n.length)return p.warn("webm","impossible length",{offset:e,length:t,bufferLength:n.length}),null;let r=(n[e]&(1<<8-t)-1)*Math.pow(2,(t-1)*8);for(let i=1;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function nb(n,e){return new DataView(n.buffer).getFloat32(e)}function rb(n,e){return new DataView(n.buffer).getFloat64(e)}function qu(n,e,t){let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return r}function go(n,e,t,r){let i=Zr(n);if(i===void 0||r===void 0)return null;let o=t.timestampOffset!==void 0?i+t.timestampOffset*r:i,a=Jr(n);if(o<0&&(a!==void 0&&(a+=o),o=0),e||!t.complete)return a===void 0&&p.warn("dash","Chunked segments should indicate a duration through their trun boxes"),{time:o/r,duration:a!==void 0?a/r:void 0};let s,d=t.duration*r,u=Math.min(r*.9,d/4);return a!==void 0&&Math.abs(a-d)<=u&&(s=a),{time:o/r,duration:s!==void 0?s/r:s}}function ib(n,e){if(n.length<=0)return!1;let t=n.length;for(let r=0;r<t;r++){let i=n[r],o=e,{messageData:a}=i,s=he(a),d=Date.parse(s);if(o===void 0||d===void 0||isNaN(d)||d>=o)return!0}return!1}function Yu(n,e){if(n.length===0)return;let{manifestRefreshEventsFromEMSGs:t,EMSGs:r}=n.reduce((a,s)=>(s.schemeIdUri==="urn:mpeg:dash:event:2012"&&s.value==="1"?(a.manifestRefreshEventsFromEMSGs===void 0&&(a.manifestRefreshEventsFromEMSGs=[]),a.manifestRefreshEventsFromEMSGs.push(s)):(a.EMSGs===void 0&&(a.EMSGs=[]),a.EMSGs.push(s)),a),{manifestRefreshEventsFromEMSGs:void 0,EMSGs:void 0}),i=r==null?void 0:r.map(a=>({type:"emsg",value:a})),o=e===void 0||t===void 0?!1:ib(t,e);return{inbandEvents:i,needsManifestRefresh:o}}function Qu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var v,E;let{segment:o,periodStart:a,periodEnd:s}=r,{data:d,isChunked:u}=t,c=[a,s];if(d===null)return o.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:0,protectionData:[],appendWindow:c};let l=Gt(d),f=Mt(r.type,r.mimeType),m=f==="mp4"||f===void 0,g=[];if(m){let R=ya(l),k;o.isInit&&(k=(v=_f(l))!=null?v:void 0),(R.length>0||k!==void 0)&&g.push({initDataType:"cenc",keyId:k,initData:R})}if(!o.isInit){let R=m?go(l,u,o,i):null,k=(E=o.timestampOffset)!=null?E:0;if(m){let A=Tf(l);if(A!==void 0){let P=A.filter(N=>o.privateInfos===void 0||o.privateInfos.isEMSGWhitelisted===void 0?!1:o.privateInfos.isEMSGWhitelisted(N)),M=Yu(P,r.manifestPublishTime);if(M!==void 0){let{needsManifestRefresh:N,inbandEvents:U}=M;return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:R,chunkOffset:k,appendWindow:c,inbandEvents:U,protectionData:g,needsManifestRefresh:N}}}}return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:R,chunkOffset:k,protectionData:g,appendWindow:c}}let{indexRange:I}=o,h;if(f==="webm")h=ju(l,0);else if(m&&(h=Xr(l,Array.isArray(I)?I[0]:0),n===!0&&h!==null&&h.length>0)){let R=h[h.length-1];Array.isArray(R.range)&&(R.range[1]=1/0)}let y;m?y=ei(l):f==="webm"&&(y=ts(l,0));let T=_(y)?void 0:y;return{segmentType:"init",initializationData:l,initializationDataSize:l.length,protectionData:g,initTimescale:T,segmentList:h!=null?h:void 0}}}function $u({lowLatencyMode:n,checkMediaSegmentIntegrity:e}){return e!==!0?t:es(t);async function t(r,i,o,a,s){var h,y;let{segment:d}=i,u=jn(r,d);if(u===null)return Promise.resolve({resultType:"segment-created",resultData:null});if(d.isInit)return mo(u,d,o,a,s);let c=((h=o.cmcdPayload)==null?void 0:h.type)==="query"?Ze(u,o.cmcdPayload.value):u,l=((y=o.cmcdPayload)==null?void 0:y.type)==="headers"?o.cmcdPayload.value:void 0,f;d.range!==void 0?f=me(oe({},l),{Range:lt(d.range)}):l!==void 0&&(f=l);let m=Mt(i.type,i.mimeType),g=m==="mp4"||m===void 0;if(n&&g){if(Ur())return po(c,{headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout},s,a);jt("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}let I;return g?I=await xe({url:c,responseType:"arraybuffer",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}):I=await xe({url:c,responseType:"text",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}),{resultType:"segment-loaded",resultData:I}}}function ob(n){if(n===void 0)throw new Error("Cannot parse subtitles: unknown format");switch(n.toLowerCase()){case"stpp":case"stpp.ttml":case"stpp.ttml.im1t":return"ttml";case"wvtt":return"vtt"}throw new Error(`The codec used for the subtitles "${n}" is not managed yet.`)}function ab(n,e){switch(e){case"application/ttml+xml":return"ttml";case"application/x-sami":case"application/smil":return"sami";case"text/vtt":return"vtt"}if(n!==void 0&&n.toLowerCase()==="srt")return"srt";throw new Error(`could not find a text-track parser for the type ${e!=null?e:""}`)}function np({segment:n,language:e,codecs:t},r,i,o,a){if(n.isInit)return null;let s,d;o===null?a?(s=n.time,d=n.end):p.warn("utils","Unavailable time data for current text track."):(s=o.time,o.duration!==void 0?d=s+o.duration:!a&&n.complete&&(d=s+n.duration));let u=ob(t),c=Dn(r),l=c!==null?he(c):"";return t==="wvtt"&&!Le(l,"WEBVTT")&&!Le(l,"\xFE\xFFWEBVTT")?{data:r,type:"mp4vtt",language:e,start:s,end:d,initTimescale:i!=null?i:null}:{data:l,type:u,language:e,start:s,end:d,initTimescale:i!=null?i:null}}function rp(n,e,t,r){let{segment:i}=n;if(i.isInit)return null;let o,a;r?p.warn("utils","Unavailable time data for current text track."):(o=i.time,i.complete&&(a=i.time+i.duration));let s=ab(n.codecs,n.mimeType);return{data:e,type:s,language:n.language,start:o,end:a,initTimescale:t!=null?t:null}}function sb(n,e,t,r,i){var f;let{segment:o}=t,{isInit:a,indexRange:s}=o,d;if(typeof n=="string"?d=Re(n):n instanceof Uint8Array?d=n:d=new Uint8Array(n),a){let m=Xr(d,Array.isArray(s)?s[0]:0);if(i===!0&&m!==null&&m.length>0){let I=m[m.length-1];Array.isArray(I.range)&&(I.range[1]=1/0)}let g=ei(d);return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:g,segmentList:m!=null?m:void 0}}let u=go(d,e,o,r),c=np(t,d,r,u,e),l=(f=o.timestampOffset)!=null?f:0;return{segmentType:"media",chunkData:c,chunkSize:d.length,chunkInfos:u,chunkOffset:l,protectionData:[],appendWindow:[t.periodStart,t.periodEnd]}}function db(n,e,t,r){let{periodStart:i,periodEnd:o,segment:a}=r,{timestampOffset:s=0}=a;if(a.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};let d,u;if(typeof n!="string"){let l=n instanceof Uint8Array?n:new Uint8Array(n);d=he(l),u=l.length}else d=n;return{segmentType:"media",chunkData:rp(r,d,e,t),chunkSize:u,chunkInfos:null,chunkOffset:s,protectionData:[],appendWindow:[i,o]}}function Xu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var l;let{periodStart:o,periodEnd:a,segment:s}=r,{data:d,isChunked:u}=t;if(d===null)return s.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:(l=s.timestampOffset)!=null?l:0,protectionData:[],appendWindow:[o,a]};let c=Mt(r.type,r.mimeType);if(c==="webm")throw new Error("Text tracks with a WEBM container are not yet handled.");return c==="mp4"?sb(d,u,r,i,n):db(d,i,u,r)}}async function ip(n,e,t,r){var d,u;let i=jn(n,e);if(i===null)return Promise.reject(new Error("Cannot load thumbnail: no URL"));let o=((d=t.cmcdPayload)==null?void 0:d.type)==="query"?Ze(i,t.cmcdPayload.value):i,a=((u=t.cmcdPayload)==null?void 0:u.type)==="headers"?t.cmcdPayload.value:void 0,s;return e.range!==void 0?s=me(oe({},a),{Range:lt(e.range)}):a!==void 0&&(s=a),Fr({url:o,responseType:"arraybuffer",headers:s,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r})}function op(n,e){var u;let{thumbnailTrack:t,thumbnail:r}=e,i=t.height/t.verticalTiles,o=t.width/t.horizontalTiles,a=[],s=(u=t.tileDuration)!=null?u:(r.end-r.time)/(t.horizontalTiles*t.verticalTiles),d=r.time;for(let c=0;c<t.verticalTiles;c++)for(let l=0;l<t.horizontalTiles;l++)a.push({start:d,end:d+s,offsetX:Math.round(l*o),offsetY:Math.round(c*i),height:Math.floor(i),width:Math.floor(o)}),d+=s;return{mimeType:t.mimeType,data:n,thumbnails:a}}function ap(n){let e=fo({customManifestLoader:n.manifestLoader},ub()?"text":"arraybuffer",n.checkManifestIntegrity===!0?Zm:null),t=Wu(n),r=Hu(n),i=Qu(n),o=$u(n),a=Xu(n);return{transportName:"dash",manifest:{loadManifest:e,parseManifest:t},audio:{loadSegment:r,parseSegment:i},video:{loadSegment:r,parseSegment:i},text:{loadSegment:o,parseSegment:a},thumbnails:{loadThumbnail:ip,parseThumbnail:op}}}function ub(){return pe.dashParsers.wasm!==null&&(pe.dashParsers.wasm.status==="initialized"||pe.dashParsers.wasm.status==="initializing")}var sp=ap;function Zu(n){n.transports.dash===void 0&&(n.transports.dash=sp),n.dashParsers.js=Xm,n.monothread={init:Vn,coreInterface:hr,initializeCoreEntry:Ka}}var lb=typeof MediaSource=="function"&&MediaSource.canConstructInDedicatedWorker===!0,dp=lb;function Ju(n,e,t,r){var l;if(e.length===0)return c("No `keySystems` option given.");if(pe.decrypt===null)return c("EME feature not activated.");let i=new D;i.linkToSignal(r);let o=new W({initializationState:{type:"uninitialized",value:null},drmSystemId:void 0},r),a=pe.decrypt,s=(l=n.FORCED_EME_API)!=null?l:_a("auto");if(s===null)return c("EME API not available on the current page.");p.debug("Init","Creating ContentDecryptor");let d=new a(s,n,e),u=f=>{var m;f>0&&((m=t.onCodecSupportUpdate)==null||m.call(t),d.removeEventListener("stateChange",u))};return d.addEventListener("stateChange",u),d.addEventListener("stateChange",f=>{if(f===1){let m=new W(!1);m.onUpdate((g,I)=>{g&&(I(),f===1&&d.attach())},{clearSignal:i.signal}),o.setValue({initializationState:{type:"awaiting-media-link",value:{isMediaLinked:m}},drmSystemId:d.systemId})}else f===2&&(o.setValue({initializationState:{type:"initialized",value:null},drmSystemId:d.systemId}),d.removeEventListener("stateChange"))}),d.addEventListener("error",f=>{i.cancel(),t.onError(f)}),d.addEventListener("warning",f=>{t.onWarning(f)}),d.addEventListener("blackListProtectionData",f=>{t.onBlackListProtectionData(f)}),d.addEventListener("keyIdsCompatibilityUpdate",f=>{t.onKeyIdsCompatibilityUpdate(f)}),i.signal.register(()=>{d.dispose()}),{statusRef:o,contentDecryptor:{enabled:!0,value:d}};function c(f){let m=new be("MEDIA_IS_ENCRYPTED_ERROR",f,{keyStatuses:void 0,keySystemConfiguration:void 0,keySystem:void 0}),g=new W({initializationState:{type:"initialized",value:null},drmSystemId:void 0});return g.finish(),{statusRef:g,contentDecryptor:{enabled:!1,value:m}}}}var ho=class extends Ir{constructor(e){super(),this._settings=e,this._initCanceller=new D}prepare(){}start(e,t){let r=this._initCanceller.signal,{keySystems:i,speed:o,url:a}=this._settings;yr(e),cb(e,this._settings.autoPlay,r);let{statusRef:s}=Ju(e,i,{onError:u=>this._onFatalError(u),onWarning:u=>this.trigger("warning",u),onBlackListProtectionData:ae,onKeyIdsCompatibilityUpdate:ae},r);eo(e,u=>this._onFatalError(u),r);let d=new Kn(t,null,o);d.addEventListener("stalled",u=>this.trigger("stalled",u)),d.addEventListener("unstalled",()=>this.trigger("unstalled",null)),d.addEventListener("warning",u=>this.trigger("warning",u)),r.register(()=>{d.destroy()}),d.start(),s.onUpdate((u,c)=>{u.initializationState.type!=="uninitialized"&&(c(),p.info("Init","Setting URL to HTMLMediaElement",{url:a}),e.src=a,r.register(()=>{p.info("Init","Removing directfile src from media element",{src:e.src}),yr(e)}),u.initializationState.type==="awaiting-media-link"?(u.initializationState.value.isMediaLinked.setValue(!0),s.onUpdate((l,f)=>{l.initializationState.type==="initialized"&&(f(),this._seekAndPlay(e,t))},{emitCurrentValue:!0,clearSignal:r})):(ee(u.initializationState.type==="initialized"),this._seekAndPlay(e,t)))},{emitCurrentValue:!0,clearSignal:r})}updateContentUrls(e,t){throw new Error("Cannot update content URL of directfile contents")}dispose(){this._initCanceller.cancel()}_onFatalError(e){this._initCanceller.cancel(),this.trigger("error",e)}_seekAndPlay(e,t){let r=this._initCanceller.signal,{autoPlay:i,startAt:o}=this._settings;Xi({mediaElement:e,playbackObserver:t,startTime:()=>{p.debug("Init","Calculating initial time");let s=fb(e,o);return p.debug("Init","Initial time calculated",{initialTime:s}),s},mustAutoPlay:i,onWarning:s=>this.trigger("warning",s),isDirectfile:!0},r).autoPlayResult.then(()=>$i(t,!0,r).onUpdate((s,d)=>{s&&(d(),this.trigger("loaded",{getSegmentSinkMetrics:null,getThumbnailData:()=>Promise.reject(new Error("Thumbnail data not available with directfile contents"))}))},{emitCurrentValue:!0,clearSignal:r})).catch(s=>{r.isCancelled()||this._onFatalError(s)})}};function cb(n,e,t){if(!e)return;let r=n.autoplay;n.autoplay=e,t.register(()=>{n.autoplay=r})}function fb(n,e){if(_(e))return 0;if(_(e.position))if(_(e.wallClockTime)){if(!_(e.fromFirstPosition))return e.fromFirstPosition}else return e.wallClockTime;else return e.position;let t=n.duration;if(typeof e.fromLastPosition=="number"){if(!_(t)&&isFinite(t))return Math.max(0,t+e.fromLastPosition);if(n.seekable.length>0){let r=n.seekable.end(n.seekable.length-1);if(isFinite(r))return Math.max(0,r+e.fromLastPosition)}p.warn("Init","startAt.fromLastPosition set but duration is not known, it may be too soon to seek");return}else if(typeof e.fromLivePosition=="number"){let r=n.seekable.length>0?n.seekable.end(0):t;return _(r)?(p.warn("Init","startAt.fromLivePosition set but live position is not known, beginning at 0."),0):Math.max(0,r+e.fromLivePosition)}else if(!_(e.percentage)){if(_(t)||!isFinite(t))return p.warn("Init","startAt.percentage set but duration is not known, beginning at 0."),0;let{percentage:r}=e;if(r>=100)return t;if(r<=0)return 0;let i=+r/100;return t*i}return 0}function el(n,e){for(let t=0;t<n.length;t++)(V.device!==V.DEVICES.Tizen||t!==e)&&(n[t].enabled=!1);return e<0||e>=n.length?!1:(n[e].enabled=!0,!0)}function _r(n,e){var t;if(e.length!==n.length)return!0;for(let r=0;r<e.length;r++)if(e[r].nativeTrack!==((t=n[r])==null?void 0:t.nativeTrack))return!0;return!1}function tl(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_audio_"+a+"_"+s.toString();t[a]=s+1;let u={language:o.language,id:d,normalized:Vr(o.language),audioDescription:o.kind==="descriptions"||o.kind==="description",representations:[]};e.push({track:u,nativeTrack:o})}return e}function nl(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_text_"+a+"_"+s.toString();t[a]=s+1;let u=o.kind==="forced"?!0:void 0,c={language:o.language,forced:u,label:o.label,id:d,normalized:Vr(o.language),closedCaption:o.kind==="captions"};e.push({track:c,nativeTrack:o})}return e}function rl(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_video_"+a+"_"+s.toString();t[a]=s+1,e.push({track:{id:d,representations:[]},nativeTrack:o})}return e}var Io=class extends se{constructor(e){var t,r,i;super(),this._nativeAudioTracks=e.audioTracks,this._nativeVideoTracks=e.videoTracks,this._nativeTextTracks=e.textTracks,this._audioTracks=this._nativeAudioTracks!==void 0?tl(this._nativeAudioTracks):[],this._videoTracks=this._nativeVideoTracks!==void 0?rl(this._nativeVideoTracks):[],this._textTracks=this._nativeTextTracks!==void 0?nl(this._nativeTextTracks):[],this._lastEmittedNativeAudioTrack=(t=this._getCurrentAudioTrack())==null?void 0:t.nativeTrack,this._lastEmittedNativeVideoTrack=(r=this._getCurrentVideoTrack())==null?void 0:r.nativeTrack,this._lastEmittedNativeTextTrack=(i=this._getCurrentTextTrack())==null?void 0:i.nativeTrack,this._handleNativeTracksCallbacks()}setAudioTrackById(e){for(let t=0;t<this._audioTracks.length;t++){let{track:r,nativeTrack:i}=this._audioTracks[t];if(r.id===e){this._enableAudioTrackFromIndex(t),this._audioTrackLockedOn=i;return}}throw new Error("Audio track not found.")}disableTextTrack(){up(this._textTracks),this._textTrackLockedOn=null}setTextTrackById(e){let t=!1;for(let r=0;r<this._textTracks.length;r++){let{track:i,nativeTrack:o}=this._textTracks[r];i.id===e?(o.mode="showing",t=!0,this._textTrackLockedOn=o):(o.mode==="showing"||o.mode==="hidden")&&(o.mode="disabled")}if(!t)throw new Error("Text track not found.")}disableVideoTrack(){lp(this._videoTracks),this._videoTrackLockedOn=null}disableAudioTrack(){pb(this._audioTracks),this._audioTrackLockedOn=null}setVideoTrackById(e){for(let t=0;t<this._videoTracks.length;t++){let{track:r,nativeTrack:i}=this._videoTracks[t];if(r.id===e){i.selected=!0,this._videoTrackLockedOn=i;return}}throw new Error("Video track not found.")}getChosenAudioTrack(){let e=this._getCurrentAudioTrack();return _(e)?e:e.track}getChosenTextTrack(){let e=this._getCurrentTextTrack();return _(e)?e:e.track}getChosenVideoTrack(){let e=this._getCurrentVideoTrack();return _(e)?e:e.track}getAvailableAudioTracks(){return this._audioTracks.map(({track:e,nativeTrack:t})=>({id:e.id,language:e.language,normalized:e.normalized,audioDescription:e.audioDescription,active:t.enabled,representations:e.representations}))}getAvailableTextTracks(){return this._textTracks.map(({track:e,nativeTrack:t})=>({id:e.id,label:e.label,forced:e.forced,language:e.language,normalized:e.normalized,closedCaption:e.closedCaption,active:t.mode==="showing"}))}getAvailableVideoTracks(){return this._videoTracks.map(({track:e,nativeTrack:t})=>({id:e.id,representations:e.representations,active:t.selected}))}dispose(){this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onchange=null,this._nativeVideoTracks.onaddtrack=null,this._nativeVideoTracks.onremovetrack=null),this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onchange=null,this._nativeAudioTracks.onaddtrack=null,this._nativeAudioTracks.onremovetrack=null),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onchange=null,this._nativeTextTracks.onaddtrack=null,this._nativeTextTracks.onremovetrack=null),this.removeEventListener()}_getCurrentAudioTrack(){if(this._nativeAudioTracks!==void 0){for(let e=0;e<this._audioTracks.length;e++){let t=this._audioTracks[e];if(t.nativeTrack.enabled)return t}return null}}_getCurrentVideoTrack(){if(this._nativeVideoTracks!==void 0){for(let e=0;e<this._videoTracks.length;e++){let t=this._videoTracks[e];if(t.nativeTrack.selected)return t}return null}}_getCurrentTextTrack(){if(this._nativeTextTracks!==void 0){for(let e=0;e<this._textTracks.length;e++){let t=this._textTracks[e];if(t.nativeTrack.mode==="showing")return t}return null}}_setPreviouslyLockedAudioTrack(){if(this._audioTrackLockedOn!==void 0)if(this._audioTrackLockedOn===null)for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];t.enabled=!1}else for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];if(t===this._audioTrackLockedOn){this._enableAudioTrackFromIndex(e);return}}}_setPreviouslyLockedTextTrack(){if(this._textTrackLockedOn!==void 0)if(this._textTrackLockedOn===null){up(this._textTracks);return}else for(let e=0;e<this._textTracks.length;e++){let{nativeTrack:t}=this._textTracks[e];if(t===this._textTrackLockedOn){mb(this._textTracks,t),t.mode!=="showing"&&(t.mode="showing");return}}}_setPreviouslyLockedVideoTrack(){if(this._videoTrackLockedOn!==void 0)if(this._videoTrackLockedOn===null){lp(this._videoTracks);return}else for(let e=0;e<this._videoTracks.length;e++){let{nativeTrack:t}=this._videoTracks[e];if(t===this._videoTrackLockedOn){t.selected=!0;return}}}_handleNativeTracksCallbacks(){this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onaddtrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=tl(this._nativeAudioTracks);if(_r(this._audioTracks,r)){this._audioTracks=r,this._setPreviouslyLockedAudioTrack(),this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onremovetrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=tl(this._nativeAudioTracks);if(_r(this._audioTracks,r)){this._audioTracks=r,this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onchange=()=>{if(this._audioTracks!==void 0)for(let e=0;e<this._audioTracks.length;e++){let{track:t,nativeTrack:r}=this._audioTracks[e];if(r.enabled){r!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",t),this._lastEmittedNativeAudioTrack=r);return}}this._lastEmittedNativeAudioTrack!==null&&(this.trigger("audioTrackChange",null),this._lastEmittedNativeAudioTrack=null)}),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onaddtrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=nl(this._nativeTextTracks);if(_r(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onremovetrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=nl(this._nativeTextTracks);if(_r(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onchange=()=>{if(this._textTracks!==void 0)for(let e=0;e<this._textTracks.length;e++){let{track:t,nativeTrack:r}=this._textTracks[e];if(r.mode==="showing"){r!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",t),this._lastEmittedNativeTextTrack=r);return}}this._lastEmittedNativeTextTrack!==null&&(this.trigger("textTrackChange",null),this._lastEmittedNativeTextTrack=null)}),this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onaddtrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=rl(this._nativeVideoTracks);if(_r(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onremovetrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=rl(this._nativeVideoTracks);if(_r(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onchange=()=>{if(this._videoTracks!==void 0)for(let e=0;e<this._videoTracks.length;e++){let{track:t,nativeTrack:r}=this._videoTracks[e];if(r.selected){r!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",t),this._lastEmittedNativeVideoTrack=r);return}}this._lastEmittedNativeVideoTrack!==null&&(this.trigger("videoTrackChange",null),this._lastEmittedNativeVideoTrack=null)})}_enableAudioTrackFromIndex(e){el(this._audioTracks.map(({nativeTrack:t})=>t),e)}};function up(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.mode="disabled"}}function mb(n,e){for(let t=0;t<n.length;t++){let{nativeTrack:r}=n[t];r!==e&&(r.mode==="showing"||r.mode==="hidden")&&(r.mode="disabled")}}function lp(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.selected=!1}}function pb(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.enabled=!1}}function il(n){n.directfile={initDirectFile:ho,mediaElementTracksStore:Io}}function ol(n){n.decrypt=Of}var cp=Z.ResizeObserver;function al(n,e,t){let{height:r,width:i}=n.getBoundingClientRect(),o=new W({height:r,width:i},t),a=r,s=i;if(cp!==void 0){let d=new cp(u=>{if(u.length===0){p.error("utils","Resized but no observed element.");return}let c=u[0],{height:l,width:f}=c.contentRect;(l!==a||f!==s)&&(a=l,s=f,o.setValue({height:l,width:f}))});d.observe(n),t.register(()=>{d.disconnect()})}else{let d=setInterval(()=>{let{height:u,width:c}=n.getBoundingClientRect();(u!==a||c!==s)&&(a=u,s=c,o.setValue({height:u,width:c}))},e);t.register(()=>{clearInterval(d)})}return o}var Yn=class{constructor(){this._ranges=[],this.length=0}insert(e,t){ee(e>=0),ee(t-e>0),Ut(this._ranges,{start:e,end:t}),this.length=this._ranges.length}remove(e,t){ee(e>=0),ee(t-e>0);let r=[];e>0&&r.push({start:0,end:e}),t<1/0&&r.push({start:t,end:1/0}),this._ranges=Qf(this._ranges,r),this.length=this._ranges.length}start(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].start}end(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].end}};function sl(n,e,t,r){p.debug("text","Finding parser for html text tracks:",{type:n});let i=pe.htmlTextTracksParsers[n];if(typeof i!="function")throw new Error("no parser found for the given text track");p.debug("text","Parser found, parsing...",{type:n});let o=i(e,t,r);return p.debug("text","Parsed successfully!",{length:o.length}),o}function Jt(n,e,t=.2){return Math.abs(n-e)<=Math.min(t,.2)}var gb=.05;function fp(n,e){let t=n.end-n.start,r=e.end-e.start,i=Math.abs(n.start-e.start),o=Math.min(t,r,.2);return i/o<=gb}function yo(n,e){for(let t=n.length-1;t>=0;t--)if(n[t].start<e)return n.slice(0,t+1);return[]}function Er(n,e){for(let t=0;t<n.length;t++)if(n[t].end>e)return n.slice(t,n.length);return[]}function dl(n,e,t){let r=Math.max(n.start,e),i=yo(n.cues,e),o={start:n.start,end:r,cues:i},a=Math.min(t,n.end),s=Er(n.cues,t),d={start:a,end:n.end,cues:s};return[o,d]}var mp=.001,hb=5,bo=class{constructor(){this._cuesBuffer=[]}isEmpty(){return this._cuesBuffer.length===0}get(e){let t=this._cuesBuffer,r=[];for(let i=t.length-1;i>=0;i--){let o=t[i];if(e<o.end&&e>=o.start){let a=o.cues;for(let s of a)e>=s.start&&e<s.end&&r.push(s.element);if(r.length===0&&a.length>0)for(let s of a)(Jt(e,s.start,mp)||Jt(e,s.end,mp))&&r.push(s.element);return r}}return[]}remove(e,t){ee(e>=0),ee(t>=0),ee(t>e);let r=Math.max(e,t),i=this._cuesBuffer;for(let o=0;o<i.length;o++)if(i[o].end>e){let a=i[o];if(a.start>=r)return;if(a.end>=r){if(e<=a.start)a.cues=Er(a.cues,r),a.start=r;else{let[s,d]=dl(a,e,r);this._cuesBuffer[o]=s,i.splice(o+1,0,d)}return}a.start>=e?(i.splice(o,1),o--):(a.cues=yo(a.cues,e),a.end=Math.max(e,a.start))}}insert(e,t,r){let i=this._cuesBuffer,o={start:t,end:r,cues:e},a=Math.abs(t-r)/hb;function s(d){let u=i[d];u===void 0||Jt(o.end,u.end,a)?i[d]=o:(u.start>=o.end||(u.cues=Er(u.cues,o.end),u.start=o.end),i.splice(d,0,o))}for(let d=0;d<i.length;d++){let u=i[d];if(t<u.end){if(fp(o,u)){if(Jt(r,u.end,a)){i[d]=o;return}else if(r<u.end){u.cues=Er(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}else if(t<u.start){if(r<u.start){i.splice(d,0,o);return}else if(Jt(r,u.start,a)){u.start=r,i.splice(d,0,o);return}else if(Jt(r,u.end,a)){i.splice(d,1,o);return}else if(r<u.end){u.cues=Er(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}if(Jt(u.end,r,a)){u.cues=yo(u.cues,t),u.end=t,i.splice(d+1,0,o);return}else if(u.end>r){let[c,l]=dl(u,t,r);this._cuesBuffer[d]=c,i.splice(d+1,0,o),i.splice(d+2,0,l);return}else{u.cues=yo(u.cues,t),u.end=t;let c=d+1;for(u=i[c];u!==void 0&&r>u.end;)i.splice(c,1),u=i[c];s(c);return}}}if(i.length>0){let d=i[i.length-1];Jt(d.end,t,a)&&(d.end=t)}i.push(o)}};function ul(n,e,t,r){let i=[e/t.columns,n/t.rows],o=r.getElementsByClassName("proportional-style");for(let a=0;a<o.length;a++){let s=o[a];if(s instanceof HTMLElement){let d=s.getAttribute("data-proportional-font-size");d!==null&&!isNaN(+d)&&(s.style.fontSize=String(+d*i[1])+"px");let u=s.getAttribute("data-proportional-width");u!==null&&!isNaN(+u)&&(s.style.width=String(+u*i[0])+"px");let c=s.getAttribute("data-proportional-height");c!==null&&!isNaN(+c)&&(s.style.height=String(+c*i[1])+"px");let l=s.getAttribute("data-proportional-line-height");l!==null&&!isNaN(+l)&&(s.style.lineHeight=String(+l*i[1])+"px");let f=s.getAttribute("data-proportional-left");f!==null&&!isNaN(+f)&&(s.style.left=String(+f*i[0])+"px");let m=s.getAttribute("data-proportional-top");m!==null&&!isNaN(+m)&&(s.style.top=String(+m*i[1])+"px");let g=s.getAttribute("data-proportional-padding-top");g!==null&&!isNaN(+g)&&(s.style.paddingTop=String(+g*i[1])+"px");let I=s.getAttribute("data-proportional-padding-bottom");I!==null&&!isNaN(+I)&&(s.style.paddingBottom=String(+I*i[1])+"px");let h=s.getAttribute("data-proportional-padding-left");h!==null&&!isNaN(+h)&&(s.style.paddingLeft=String(+h*i[0])+"px");let y=s.getAttribute("data-proportional-padding-right");y!==null&&!isNaN(+y)&&(s.style.paddingRight=String(+y*i[0])+"px")}}return o.length>0}function pp(n,e){try{n.removeChild(e)}catch(t){p.warn("text","Can't remove text track: not in the element.")}}function Ib(n){let e=n.getAttribute("data-resolution-rows"),t=n.getAttribute("data-resolution-columns");if(e===null||t===null)return null;let r=parseInt(e,10),i=parseInt(t,10);return r===null||i===null?null:{rows:r,columns:i}}var So=class{constructor(e,t){p.debug("text","Creating HTMLTextDisplayer"),this._buffered=new Yn,this._videoElement=e,this._textTrackElement=t,this._sizeUpdateCanceller=new D,this._subtitlesIntervalCanceller=new D,this._buffer=new bo,this._currentCues=[],this._isAutoRefreshing=!1}pushTextData(e){var h,y;p.debug("text","Appending new html text tracks");let{timestampOffset:t,appendWindow:r,chunk:i}=e;if(i===null)return We(this._buffered);let{start:o,end:a,data:s,type:d,language:u,initTimescale:c}=i,l=(h=r[0])!=null?h:0,f=(y=r[1])!=null?y:1/0,m=sl(d,s,{initTimescale:c,language:u},t);if(l!==0&&f!==1/0){let T=0;for(;T<m.length&&m[T].end<=l;)T++;for(m.splice(0,T),T=0;T<m.length&&m[T].start<l;)m[T].start=l,T++;for(T=m.length-1;T>=0&&m[T].start>=f;)T--;for(m.splice(T+1,m.length),T=m.length-1;T>=0&&m[T].end>f;)m[T].end=f,T--}let g;if(o!==void 0)g=Math.max(l,o);else{if(m.length<=0)return p.warn("text","Current text tracks have no cues nor start time. Aborting"),We(this._buffered);p.warn("text","No start time given. Guessing from cues."),g=m[0].start}let I;if(a!==void 0)I=Math.min(f,a);else{if(m.length<=0)return p.warn("text","Current text tracks have no cues nor end time. Aborting"),We(this._buffered);p.warn("text","No end time given. Guessing from cues."),I=m[m.length-1].end}return I<=g?(p.warn("text","Invalid text track appended: ","the start time is inferior or equal to the end time."),We(this._buffered)):(this._buffer.insert(m,g,I),this._buffered.insert(g,I),!this._isAutoRefreshing&&!this._buffer.isEmpty()&&this.autoRefreshSubtitles(this._subtitlesIntervalCanceller.signal),We(this._buffered))}removeBuffer(e,t){return p.debug("text","Removing html text track data",{start:e,end:t}),this._buffer.remove(e,t),this._buffered.remove(e,t),this._isAutoRefreshing&&this._buffer.isEmpty()&&(this.refreshSubtitles(),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel(),this._subtitlesIntervalCanceller=new D),We(this._buffered)}getBufferedRanges(){return We(this._buffered)}reset(){p.debug("text","Resetting HTMLTextDisplayer"),this.stop(),this._subtitlesIntervalCanceller=new D}stop(){this._subtitlesIntervalCanceller.isUsed()||(p.debug("text","Stopping HTMLTextDisplayer"),this._disableCurrentCues(),this._buffer.remove(0,1/0),this._buffered.remove(0,1/0),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel())}_disableCurrentCues(){if(this._sizeUpdateCanceller.cancel(),this._currentCues.length>0){for(let e of this._currentCues)pp(this._textTrackElement,e.element);this._currentCues=[]}}_displayCues(e){if(this._currentCues.length===e.length&&this._currentCues.every((i,o)=>i.element===e[o]))return;this._sizeUpdateCanceller.cancel();for(let i of this._currentCues)pp(this._textTrackElement,i.element);this._currentCues=[];for(let i of e){let o=Ib(i);this._currentCues.push({element:i,resolution:o}),this._textTrackElement.appendChild(i)}let r=this._currentCues.filter(i=>i.resolution!==null);if(r.length>0){this._sizeUpdateCanceller=new D,this._sizeUpdateCanceller.linkToSignal(this._subtitlesIntervalCanceller.signal);let{TEXT_TRACK_SIZE_CHECKS_INTERVAL:i}=O.getCurrent();al(this._textTrackElement,i,this._sizeUpdateCanceller.signal).onUpdate(({height:a,width:s})=>{for(let d of r){let{resolution:u,element:c}=d;ul(a,s,u,c)}},{clearSignal:this._sizeUpdateCanceller.signal,emitCurrentValue:!0})}}autoRefreshSubtitles(e){if(this._isAutoRefreshing||e.isCancelled())return;let t=null,{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:r}=O.getCurrent(),i=()=>{this._isAutoRefreshing=!1,t!==null&&(t.cancel(),t=null)},o=()=>{i(),this._isAutoRefreshing=!0,t=new D,t.linkToSignal(e);let a=setInterval(()=>this.refreshSubtitles(),r);t.signal.register(()=>{clearInterval(a)}),this.refreshSubtitles()};af(this._videoElement,()=>{i(),this._disableCurrentCues()},e),sf(this._videoElement,o,e),df(this._videoElement,o,e),o()}refreshSubtitles(){let{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:e}=O.getCurrent(),t;this._videoElement.paused||this._videoElement.playbackRate<=0?t=this._videoElement.currentTime:t=Math.max(this._videoElement.currentTime+e/1e3/2,0);let r=this._buffer.get(t);r.length===0?this._disableCurrentCues():this._displayCues(r)}};b.CURRENT_ENV===b.DEV&&(yb=function(e){function t(r){}});var yb;var Sn=So;function Ue(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer)}var bb=/&#([0-9]+);/g,Sb=/<br>/gi,Tb=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,_b=/\s*<p (?:class=([^>]+))?>(.*)/i,Eb=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function vb(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;r!==null;){let i=r[1],o=kb(r[2],"lang");!_(i)&&!_(o)&&(t[o]=i),r=e.exec(n)}return t}function Rb(n){let t=/p\s*{([^}]*)}/gi.exec(n);return t===null?"":t[1]}function kb(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function Cb(n){return n.replace(bb,(e,t)=>String.fromCharCode(Number(t)))}function Pb(n,{language:e},t){let r;typeof n!="string"?r=he(Ue(n)):r=n;let i=/<sync[ >]/gi,o=/<sync[ >]|<\/body>/gi,a=[],s=Tb.exec(r),d=Array.isArray(s)?s[1]:"",u,c;o.exec(r);let l=vb(d),f=Rb(d),m;if(x(e)&&(m=l[e],m===void 0))throw new Error(`sami: could not find lang ${e} in CSS`);for(;u=i.exec(r),c=o.exec(r),!(u===null&&c===null);){if(u===null||c===null||u.index>=c.index)throw new Error("parse error");let I=r.slice(u.index,c.index),h=Eb.exec(I);if(!Array.isArray(h))throw new Error("parse error (sync time attribute)");let y=+h[1];if(isNaN(y))throw new Error("parse error (sync time attribute NaN)");g(I.split(`
|
|
11
|
+
`),y/1e3)}return a;function g(I,h){let y=I.length;for(;--y>=0;){let T=_b.exec(I[y]);if(!Array.isArray(T))continue;let[,v,E]=T;if(m===v)if(E===" ")a[a.length-1].end=h;else{let R=document.createElement("DIV");R.className="rxp-texttrack-region";let k=document.createElement("DIV");k.className="rxp-texttrack-div",k.style.position="absolute",k.style.bottom="0",k.style.width="100%",k.style.color="#fff",k.style.textShadow="-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000";let A=document.createElement("div");A.className="rxp-texttrack-p",x(f)&&(A.style.cssText=f);let P=E.split(Sb);for(let M=0;M<P.length;M++){M!==0&&A.appendChild(document.createElement("BR"));let N=document.createElement("SPAN");N.className="rxp-texttrack-span",N.textContent=Cb(P[M]),A.appendChild(N)}k.appendChild(A),R.appendChild(k),a.push({element:R,start:h+t,end:-1})}}}}var gp=Pb;function ll(n){n.htmlTextTracksParsers.sami=gp,n.htmlTextDisplayer=Sn}function cl(n,e){let t=e+1;for(;x(n[t]);)t++;return t}function To(n){let e=[];for(let t=0;t<n.length;t++)if(x(n[t])){let r=cl(n,t),i=n.slice(t,r);i.length>0&&(i.length===1?i[0].indexOf("-->")>=0&&e.push(i):(i[1].indexOf("-->")>=0||i[0].indexOf("-->")>=0)&&e.push(i)),t=r}return e}function ns(n){let e=n.split(":");if(x(e[2])){let t=parseInt(e[0],10),r=parseInt(e[1],10),i=parseFloat(e[2].replace(",","."));return isNaN(t)||isNaN(r)||isNaN(i)?void 0:t*60*60+r*60+i}}function _o(n,e){if(n.length===0)return null;let t,r,i=[];if(x(n[1])&&n[1].indexOf("-->")!==-1&&([t,r]=n[1].split("-->").map(s=>s.trim()),i=n.slice(2,n.length)),(!x(t)||!x(r))&&([t,r]=n[0].split("-->").map(s=>s.trim()),i=n.slice(1,n.length)),!x(t)||!x(r))return null;let o=ns(t),a=ns(r);return o===void 0||a===void 0?null:{start:o+e,end:a+e,payload:i}}function fl(n,e,t){let r;typeof n!="string"?r=he(Ue(n)):r=n;let i=r.split(/\r\n|\n|\r/),o=To(i),a=[];for(let s of o){let d=_o(s,t);if(d!==null){let u=Mb(d);u!==null&&a.push(u)}}return a}function Mb(n){let{start:e,end:t,payload:r}=n,i=document.createElement("div");i.className="rxp-texttrack-p",i.style.fontSize="28px",i.style.position="absolute",i.style.bottom="5%",i.style.width="100%",i.style.textAlign="center",i.style.color="#fff",i.style.textShadow="-1px -1px 2px #000,1px -1px 2px #000,-1px 1px 2px #000,1px 1px 2px #000";for(let o=0;o<r.length;o++){o!==0&&i.appendChild(document.createElement("br"));let a=Ab(r[o]);i.appendChild(a)}return{start:e,end:t,element:i}}function Ab(n){let e=document.createElement("div");e.innerHTML=n;let t=function(r){let i=r.childNodes,o=document.createElement("span");o.className="rxp-texttrack-span";for(let a=0;a<i.length;a++){let s=i[a];if(s.nodeName==="#text"){let d=s.wholeText.split(`
|
|
12
|
+
`);for(let u=0;u<d.length;u++)if(u!==0&&o.appendChild(document.createElement("br")),d[u].length>0){let c=document.createTextNode(d[u]);o.appendChild(c)}}else if(s.nodeName==="B"){let d=t(s);d.style.fontWeight="bold",o.appendChild(d)}else if(s.nodeName==="I"){let d=t(s);d.style.fontStyle="italic",o.appendChild(d)}else if(s.nodeName==="U"){let d=t(s);d.style.textDecoration="underline",o.appendChild(d)}else if(xb(s)&&typeof s.color=="string"){let d=t(s);d.style.color=s.color,o.appendChild(d)}else{let d=t(s);o.appendChild(d)}}return o};return t(e)}function xb(n){return n.nodeName==="FONT"&&"color"in n}function ml(n){n.htmlTextTracksParsers.srt=fl,n.htmlTextDisplayer=Sn}var wb=/(\d+) (\d+)/;function pl(n){let e=n.getAttribute("ttp:frameRate"),t=n.getAttribute("ttp:subFramRate"),r=n.getAttribute("ttp:tickRate"),i=n.getAttribute("ttp:frameRateMultiplier"),o=n.getAttribute("xml:space"),a=n.getAttribute("ttp:cellResolution"),s={columns:32,rows:15};if(a!==null){let I=wb.exec(a);if(I===null||I.length<3)p.warn("ttml","Invalid cellResolution",{cellResolution:a});else{let h=parseInt(I[1],10),y=parseInt(I[2],10);isNaN(h)||isNaN(y)?p.warn("ttml","Invalid cellResolution",{cellResolution:a}):s={columns:h,rows:y}}}if(x(o)&&o!=="default"&&o!=="preserve")throw new Error("Invalid spacing style");let d=Number(e);(isNaN(d)||d<=0)&&(d=30);let u=Number(t);(isNaN(u)||u<=0)&&(u=1);let c=Number(r);(isNaN(c)||c<=0)&&(c=void 0);let l=d,f=u!=null?u:1,m=o!=null?o:"default",g=c!=null?c:d*u;if(i!==null){let I=/^(\d+) (\d+)$/g.exec(i);if(I!==null){let h=Number(I[1]),y=Number(I[2]),T=h/y;l=d*T}}return{cellResolution:s,tickRate:g,frameRate:l,subFrameRate:f,spaceStyle:m}}function Qn(n,e,t,r){let i={},o=n.slice();for(let a=0;a<=e.length-1;a++){let s=e[a];if(s!==void 0){let d,u;if(s.nodeType===Node.ELEMENT_NODE){let c=s;for(let l=0;l<=c.attributes.length-1;l++){let f=c.attributes[l],m=f.name;if(m==="style")d=f.value;else if(m==="region")u=f.value;else{let g=m.substring(4);if(J(o,g)&&(i[g]=f.value,o.splice(l,1),o.length===0))return i}}}if(x(d)){let c=q(t,l=>l.id===d);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!x(i[f])&&x(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}if(x(u)){let c=q(r,l=>l.id===u);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!x(i[f])&&x(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}}}return i}function gl(n){if(n.nodeType!==Node.ELEMENT_NODE)return{};let e=n,t={};for(let r=0;r<=e.attributes.length-1;r++){let i=e.attributes[r];if(Le(i.name,"tts")){let o=i.name.substring(4);t[o]=i.value}}return t}function hl(n){let e=[];function t(r,i){e.push(i);for(let o of r.extendsStyles){let a=Te(n,s=>s.id===o);if(a<0)p.warn("ttml","unknown style inheritance",{id:o});else{let s=n[a];J(e,a)?p.warn("ttml","infinite style inheritance loop avoided"):t(s,a),r.style=G({},s.style,r.style)}}r.extendsStyles.length=0}for(let r=0;r<n.length;r++)t(n[r],r),e.length=0}function hp(n,e){if(!(n.parentNode instanceof Element))return[];function t(r){let i=[];r.tagName.toLowerCase()===e.toLowerCase()&&i.push(r);let o=r.parentNode;return o instanceof Element&&i.push(...t(o)),i}return t(n.parentNode)}function rs(n){let e=hp(n,"div");if(e.length===0){let t=hp(n,"tt:div");t.length>0&&(e=t)}return e}function Ip(n){let e=n.getElementsByTagName("body");if(e.length>0)return e[0];let t=n.getElementsByTagName("tt:body");return t.length>0?t[0]:null}function yp(n){let e=n.getElementsByTagName("style");if(e.length>0)return e;let t=n.getElementsByTagName("tt:style");return t.length>0?t:e}function bp(n){let e=n.getElementsByTagName("region");if(e.length>0)return e;let t=n.getElementsByTagName("tt:region");return t.length>0?t:e}function Sp(n){let e=n.getElementsByTagName("p");if(e.length>0)return e;let t=n.getElementsByTagName("tt:p");return t.length>0?t:e}function is(n){return n.nodeName==="br"||n.nodeName==="tt:br"}function os(n){return n.nodeName==="span"||n.nodeName==="tt:span"}var Tp=["align","backgroundColor","color","direction","display","displayAlign","extent","fontFamily","fontSize","fontStyle","fontWeight","lineHeight","opacity","origin","overflow","padding","textAlign","textDecoration","textOutline","unicodeBidi","visibility","wrapOption","writingMode"];function Eo(n,e){let t=[],r=new DOMParser().parseFromString(n,"text/xml");if(r!=null){let o=r.getElementsByTagName("tt")[0];if(o===void 0&&(o=r.getElementsByTagNameNS("*","tt")[0],o===void 0))throw new Error("invalid XML");let a=Ip(o),s=yp(o),d=bp(o),u=Sp(o),c=pl(o),l=[];for(let h=0;h<=s.length-1;h++){let y=s[h];if(y instanceof Element){let T=y.getAttribute("xml:id");if(T!==null){let v=y.getAttribute("style"),E=v===null?[]:v.split(" ");l.push({id:T,style:gl(y),extendsStyles:E})}}}hl(l);let f=[];for(let h=0;h<=d.length-1;h++){let y=d[h];if(y instanceof Element){let T=y.getAttribute("xml:id");if(T!==null){let v=gl(y),E=y.getAttribute("style");if(x(E)){let R=q(l,k=>k.id===E);R!==void 0&&(v=G({},R.style,v))}f.push({id:T,style:v,extendsStyles:[]})}}}let m=Qn(Tp,a!==null?[a]:[],l,f),I=(a!==null?a.getAttribute("xml:space"):void 0)==="default"||c.spaceStyle==="default";for(let h=0;h<u.length;h++){let y=u[h];if(y instanceof Element){let T=rs(y),v=G({},m,Qn(Tp,[y,...T],l,f)),E=y.getAttribute("xml:space"),R=x(E)?E==="default":I,k={paragraph:y,timeOffset:e,idStyles:l,regionStyles:f,body:a,paragraphStyle:v,ttParams:c,shouldTrimWhiteSpace:R};k!==null&&t.push(k)}}}return t}function _p(n){return n.extent===void 0&&n.origin===void 0&&n.displayAlign===void 0&&n.display===void 0&&n.textAlign===void 0&&n.fontSize===void 0}function Ep(n){n.extent="70% 20%",n.fontSize="1c",n.origin="15% 80%",n.displayAlign="before",n.textAlign="center"}var Il=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,yl=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/,bl=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d{2,})$/,Sl=/^(\d*\.?\d*)f$/,Tl=/^(\d*\.?\d*)t$/,_l=/^(?:(\d*\.?\d*)h)?(?:(\d*\.?\d*)m)?(?:(\d*\.?\d*)s)?(?:(\d*\.?\d*)ms)?$/,El=/^(\d{1,2}|100)% (\d{1,2}|100)%$/,nt=/^((?:\+|-)?\d*(?:\.\d+)?)(px|em|c|%|rh|rw)$/,vp=/^#([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})$/,Rp=/^#([0-9A-f])([0-9A-f])([0-9A-f])([0-9A-f])$/,kp=/^rgb\( *(\d+) *, *(\d+) *, *(\d+) *\)/,Cp=/^rgba\( *(\d+) *, *(\d+) *, *(\d+) *, *(\d+) *\)/;function Ob(n,e){if(Il.test(n))return Nb(e,n);if(yl.test(n))return vl(yl,n);if(bl.test(n))return vl(bl,n);if(Sl.test(n))return Db(e,n);if(Tl.test(n))return Lb(e,n);if(_l.test(n))return vl(_l,n)}function Db(n,e){let t=Sl.exec(e);return Number(t[1])/n.frameRate}function Lb(n,e){let t=Tl.exec(e);return Number(t[1])/n.tickRate}function Nb(n,e){let t=Il.exec(e),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]),a=Number(t[4]),s=Number(t[5]);return isNaN(s)&&(s=0),a+=s/n.subFrameRate,o+=a/n.frameRate,o+i*60+r*3600}function vl(n,e){let t=n.exec(e);if(t===null||t[0]==="")return null;let r=Number(t[1]);isNaN(r)&&(r=0);let i=Number(t[2]);isNaN(i)&&(i=0);let o=Number(t[3]);isNaN(o)&&(o=0);let a=Number(t[4]);return isNaN(a)&&(a=0),a/1e3+o+i*60+r*3600}var as=Ob;function vo(n,e){let t=n.getAttribute("begin"),r=n.getAttribute("dur"),i=n.getAttribute("end"),o=x(t)?as(t,e):null,a=x(r)?as(r,e):null,s=x(i)?as(i,e):null;if(_(o)||_(s)&&_(a))throw new Error("Invalid text cue");let d=_(s)?o+a:s;return{start:o,end:d}}var Rl;function Ke(n,e){Rl===void 0&&(Rl=n.classList!==void 0&&typeof n.classList.add=="function"),Rl?n.classList.add(e):(" "+n.className+" ").indexOf(" "+e+" ")<0&&(n.className+=" "+e)}function kl(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=nt.exec(r[0]),o=nt.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.width=i[1]+i[2]:i[2]==="c"?(Ke(n,"proportional-style"),n.setAttribute("data-proportional-width",i[1])):p.warn("ttml","unhandled extent unit",{unit:i[2]}),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.height=o[1]+o[2]:o[2]==="c"?(Ke(n,"proportional-style"),n.setAttribute("data-proportional-height",o[1])):p.warn("ttml","unhandled extent unit",{unit:o[2]}))}function Cl(n,e){let r=e.trim().split(" ");if(r.length===0)return;let i=nt.exec(r[0]);if(i!==null)if(i[2]==="px"||i[2]==="em")n.style.fontSize=i[1]+i[2];else if(i[2]==="c")n.style.position="relative",Ke(n,"proportional-style"),n.setAttribute("data-proportional-font-size",i[1]);else if(i[2]==="%"){let o=Number(i[1]);isNaN(o)?p.warn("ttml",'could not parse fontSize value "'+i[1]+'" into a number'):(n.style.position="relative",Ke(n,"proportional-style"),n.setAttribute("data-proportional-font-size",String(o/100)))}else p.warn("ttml","unhandled fontSize unit",{unit:i[2]})}function Pl(n,e){let t=e.trim(),r=t.split(" ");if(t==="auto")return;let i=nt.exec(r[0]);i!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.lineHeight=i[1]+i[2]:i[2]==="c"?(Ke(n,"proportional-style"),n.setAttribute("data-proportional-line-height",i[1])):p.warn("ttml","unhandled lineHeight unit",{unit:i[2]}))}function Ml(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=nt.exec(r[0]),o=nt.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.left=i[1]+i[2]:i[2]==="c"?(Ke(n,"proportional-style"),n.setAttribute("data-proportional-left",i[1])):p.warn("ttml","unhandled origin unit",{unit:i[2]}),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.top=o[1]+o[2]:o[2]==="c"?(Ke(n,"proportional-style"),n.setAttribute("data-proportional-top",o[1])):p.warn("ttml","unhandled origin unit",{unit:o[2]}))}function Al(n,e){let r=e.trim().split(" ");if(r.length<1)return;let i=nt.exec(r[0]);if(i===null)return;if(i[2]==="px"||i[2]==="%"||i[2]==="em"){let d=i[1]+i[2];r.length===1?n.style.padding=d:r.length===2?(n.style.paddingTop=d,n.style.paddingBottom=d):n.style.paddingTop=d}else i[2]==="c"?(Ke(n,"proportional-style"),r.length===1?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1]),n.setAttribute("data-proportional-padding-left",i[1]),n.setAttribute("data-proportional-padding-right",i[1])):r.length===2?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1])):n.setAttribute("data-proportional-padding-top",i[1])):p.warn("ttml","unhandled padding unit",{unit:i[2]});if(r.length===1)return;let o=nt.exec(r[1]);if(o===null)return;if(o[2]==="px"||o[2]==="%"||o[2]==="em"){let d=o[1]+o[2];r.length<4&&(n.style.paddingLeft=d),n.style.paddingRight=d}else o[2]==="c"?(Ke(n,"proportional-style"),r.length<4&&n.setAttribute("data-proportional-padding-left",o[1]),n.setAttribute("data-proportional-padding-right",o[1])):p.warn("ttml","unhandled padding unit",{unit:o[2]});if(r.length===2)return;let a=nt.exec(r[2]);if(a===null)return;if(a[2]==="px"||a[2]==="%"||a[2]==="em"){let d=a[1]+a[2];n.style.paddingBottom=d}else a[2]==="c"?(Ke(n,"proportional-style"),n.setAttribute("data-proportional-padding-bottom",a[1])):p.warn("ttml","unhandled padding unit",{unit:a[2]});if(r.length===3)return;let s=nt.exec(r[3]);if(s!==null)if(s[2]==="px"||s[2]==="%"||s[2]==="em"){let d=s[1]+s[2];n.style.paddingLeft=d}else s[2]==="c"?(Ke(n,"proportional-style"),n.setAttribute("data-proportional-padding-left",s[1])):p.warn("ttml","unhandled padding unit",{unit:s[2]})}function vr(n,e){let t=e;return x(e)&&e.trim().endsWith("%")&&(t=e.trim().slice(0,-1),t=(parseInt(t,10)/100).toString()+"em"),`-1px -1px ${t} ${n},1px -1px ${t} ${n},-1px 1px ${t} ${n},1px 1px ${t} ${n}`}function Tn(n){let e;return e=vp.exec(n),_(e)?(e=Rp.exec(n),_(e)?(e=kp.exec(n),_(e)?(e=Cp.exec(n),_(e)?n:"rgba("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+","+String(+e[4]/255)+")"):"rgb("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+")"):"rgba("+String(parseInt(e[1]+e[1],16))+","+String(parseInt(e[2]+e[2],16))+","+String(parseInt(e[3]+e[3],16))+","+String(parseInt(e[4]+e[4],16)/255)+")"):"rgba("+String(parseInt(e[1],16))+","+String(parseInt(e[2],16))+","+String(parseInt(e[3],16))+","+String(parseInt(e[4],16)/255)+")"}var Bb=["color","direction","display","fontFamily","fontSize","fontStyle","fontWeight","textDecoration","textOutline","unicodeBidi","visibility","wrapOption"];function Ub(n,e,t){let r=e.color;x(r)&&(n.style.color=Tn(r));let i=e.backgroundColor;x(i)&&(n.style.backgroundColor=Tn(i));let o=e.textOutline;if(x(o)){let h=o.trim().replace(/\s+/g," ").split(" "),y=h.length;if(y===3){let T=Tn(h[0]),v=h[1];n.style.textShadow=vr(T,v)}else if(x(r)&&y===1){let T=h[0];n.style.textShadow=vr(r,T)}else if(y===2){let T=/^[#A-Z]/i.test(h[0]),v=/^[0-9]/.test(h[0]);if(T!==v){if(T){let E=Tn(h[0]),R=h[1];n.style.textShadow=vr(E,R)}else if(x(r)){let E=h[0];n.style.textShadow=vr(r,E)}}}}let a=e.textDecoration;if(x(a))switch(a){case"noUnderline":case"noLineThrough":case"noOverline":n.style.textDecoration="none";break;case"lineThrough":n.style.textDecoration="line-through";break;default:n.style.textDecoration=a;break}let s=e.fontFamily;if(x(s))switch(s){case"proportionalSansSerif":n.style.fontFamily="Arial, Helvetica, Liberation Sans, sans-serif";break;case"monospaceSansSerif":case"sansSerif":n.style.fontFamily="sans-serif";break;case"monospaceSerif":case"default":n.style.fontFamily="Courier New, Liberation Mono, monospace";break;case"proportionalSerif":n.style.fontFamily="serif";break;default:n.style.fontFamily=s}let d=e.fontStyle;x(d)&&(n.style.fontStyle=d);let u=e.fontWeight;x(u)&&(n.style.fontWeight=u);let c=e.fontSize;x(c)?Cl(n,c):(Ke(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1"));let l=e.direction;x(l)&&(n.style.direction=l);let f=e.unicodeBidi;if(x(f))switch(f){case"bidiOverride":n.style.unicodeBidi="bidi-override";break;case"embed":n.style.unicodeBidi="embed";break;default:n.style.unicodeBidi="normal"}let m=e.visibility;x(m)&&(n.style.visibility=m),e.display==="none"&&(n.style.display="none"),e.wrapOption==="noWrap"?t?n.style.whiteSpace="nowrap":n.style.whiteSpace="pre":t?n.style.whiteSpace="normal":n.style.whiteSpace="pre-wrap"}function Fb(n,e){n.style.color="white",n.style.position="absolute";let t=e.extent;x(t)&&kl(n,t);let r=e.writingMode;x(r);let i=e.overflow;n.style.overflow=x(i)?i:"hidden";let o=e.padding;x(o)&&Al(n,o);let a=e.origin;x(a)&&Ml(n,a);let s=e.displayAlign;if(x(s))switch(n.style.display="flex",n.style.flexDirection="column",s){case"before":n.style.justifyContent="flex-start";break;case"center":n.style.justifyContent="center";break;case"after":n.style.justifyContent="flex-end";break}let d=e.opacity;x(d)&&(n.style.opacity=d);let u=e.visibility;x(u)&&(n.style.visibility=u),e.display==="none"&&(n.style.display="none")}function Kb(n,e){n.style.margin="0px",Ke(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1");let t=e.backgroundColor;x(t)&&(n.style.backgroundColor=Tn(t));let r=e.lineHeight;x(r)&&Pl(n,r);let i=e.textAlign;if(x(i))switch(i){case"center":n.style.textAlign="center";break;case"left":case"start":n.style.textAlign="left";break;case"right":case"end":n.style.textAlign="right";break}}function Vb(n,e,t){let r=document.createElement("span"),i=n.textContent===null?"":n.textContent;if(t){let a=i.trim();a=a.replace(/\s+/g," "),i=a}let o=document.createTextNode(i);return r.appendChild(o),r.className="rxp-texttrack-span",Ub(r,e,t),r}function zb(n,e,t,r,i){function o(a,s,d,u){let c=a.childNodes,l=[];for(let f=0;f<c.length;f++){let m=c[f];if(m.nodeName==="#text"){let{backgroundColor:g}=Qn(["backgroundColor"],d,t,e);x(g)?s.backgroundColor=g:s.backgroundColor="";let I=Vb(m,s,u);l.push(I)}else if(is(m)){let g=document.createElement("BR");l.push(g)}else if(os(m)&&m.nodeType===Node.ELEMENT_NODE&&m.childNodes.length>0){let g=m.getAttribute("xml:space"),I=x(g)?g==="default":u,h=G({},s,Qn(Bb,[m],t,e));l.push(...o(m,h,[m,...d],I))}}return l}return o(n,G({},r),[],i)}function xl(n,e,t,r,i,{cellResolution:o,shouldTrimWhiteSpace:a}){let s=rs(n),d=document.createElement("DIV");if(d.className="rxp-texttrack-region",d.setAttribute("data-resolution-columns",String(o.columns)),d.setAttribute("data-resolution-rows",String(o.rows)),Fb(d,i),e!==null){let{bodyBackgroundColor:l}=Qn(["backgroundColor"],[...s,e],r,t);x(l)&&(d.style.backgroundColor=Tn(l))}let u=document.createElement("p");u.className="rxp-texttrack-p",Kb(u,i);let c=zb(n,t,r,i,a);for(let l=0;l<c.length;l++)u.appendChild(c[l]);return d.appendChild(u),d}function wl(n){let{paragraph:e,ttParams:t,body:r,regionStyles:i,idStyles:o,paragraphStyle:a,timeOffset:s,shouldTrimWhiteSpace:d}=n;if(!e.hasAttribute("begin")&&!e.hasAttribute("end")&&/^\s*$/.test(e.textContent===null?"":e.textContent))return null;let{cellResolution:u}=t,{start:c,end:l}=vo(e,t),f=xl(e,r,i,o,a,{cellResolution:u,shouldTrimWhiteSpace:d});return{start:c+s,end:l+s,element:f}}function Ol(n,e,t){let r;typeof n!="string"?r=he(Ue(n)):r=n;let i=Eo(r,t),o=[];for(let a of i){let{paragraphStyle:s}=a;_p(s)&&Ep(s);let d=wl(a);d!==null&&o.push(d)}return o}var Pp=Ol;function Dl(n){n.htmlTextTracksParsers.ttml=Pp,n.htmlTextDisplayer=Sn}function ss(n){let e=n.split(":").reverse();if(x(e[2])||x(e[1])){let t=x(e[2])?parseInt(e[2],10):0,r=parseInt(e[1],10),i=parseFloat(e[0].replace(",","."));return isNaN(t)||isNaN(r)||isNaN(i)?void 0:t*60*60+r*60+i}}function Ll(n){return n.split(/ |\t/).reduce((t,r)=>{let i=r.split(":");return i.length===2&&(t[i[0]]=i[1]),t},{})}function Wb(n){let t=/^([\d:.]+)[ |\t]+-->[ |\t]+([\d:.]+)[ |\t]*(.*)$/.exec(n);if(t===null)return null;let r=ss(t[1]),i=ss(t[2]);if(r===void 0||i===void 0)return null;let o=Ll(t[3]);return{start:r,end:i,settings:o}}function Ro(n,e){let t=/-->/,r,i,o;if(t.test(n[0]))r=n[0],i=n.slice(1,n.length);else{if(!t.test(n[1]))return null;o=n[0],r=n[1],i=n.slice(2,n.length)}let a=Wb(r);if(a===null)return null;let{start:s,end:d,settings:u}=a;return{start:s+e,end:d+e,settings:u,payload:i,header:o}}function $n(n,e,t,r){var c,l;let i=[],o=Zr(n);if(o===void 0)return[];let a=Sf(n),s=Dn(n);if(s===null)return[];let d=0,u=o;for(let f of a){let m=(c=f.duration)!=null?c:0,g=f.compositionTimeOffset!==void 0?u+f.compositionTimeOffset:u;u=g+m;let I=0;for(;I<((l=f.size)!=null?l:0);){let h=te(s,d);d+=4,I+=h;let y=he(s.slice(d,d+4));d+=4;let T=null;if(y==="vttc"?h>8&&(T=s.slice(d,d+(h-8)),d+=h-8):y==="vtte"?h>8&&(d+=h-8):(p.error("vtt","encountered unknown fragmented vtt box",{box:y}),d+=Math.min(h-8,1)),m>0){if(T!==null){let v=Hb(T,t+g/e,t+u/e,r);v!==null&&i.push(v)}}else p.error("vtt","cue duration missing")}}return d!==s.length&&p.error("vtt","end offset is not equal to mdat length",{mdataOffset:d,mdatLength:s.length}),i}function Hb(n,e,t,r){let i=qb(n),o=Gb(n);return i===null?null:r({start:e,end:t,settings:o!==null?Ll(he(o)):{},header:void 0,payload:[he(i)]},{classes:{},global:void 0})}function qb(n){return ke(n,1885436268)}function Gb(n){return ke(n,1937011815)}function ko(n,e){let t=["u","i","b"],r=["u","i","b","c","#text"],i=n.nodeName.toLowerCase().split(".")[0],o;if(J(r,i))if(i==="#text"){let a=n.wholeText.split(`
|
|
13
|
+
`);o=document.createElement("span");for(let s=0;s<a.length;s++)if(s>0&&o.appendChild(document.createElement("br")),a[s].length>0){let d=document.createTextNode(a[s]);o.appendChild(d)}}else{let a=n.nodeName.toLowerCase().split("."),s=[];if(a.forEach(d=>{x(e[d])&&s.push(e[d])}),s.length!==0){let d=document.createAttribute("style");s.forEach(c=>{d.value+=c});let u=J(t,i)?i:"span";o=document.createElement(u),o.setAttributeNode(d)}else{let d=J(t,i)?i:"span";o=document.createElement(d)}for(let d=0;d<n.childNodes.length;d++){let u=ko(n.childNodes[d],e);o.appendChild(u)}}else{o=document.createElement("span");for(let a=0;a<n.childNodes.length;a++){let s=ko(n.childNodes[a],e);o.appendChild(s)}}return o}function Nl(n,e){let t=n.replace(/<[0-9]{2}:[0-9]{2}.[0-9]{3}>/,"").replace(/<([u,i,b,c])(\..*?)?(?: .*?)?>(.*?)<\/\1>/g,"<$1$2>$3</$1$2>"),i=new DOMParser().parseFromString(t,"text/html").body.childNodes,o=[];for(let a=0;a<i.length;a++)o.push(ko(i[a],e));return o}function Bl(n){let e=document.createAttribute("style");return e.value=jb(n),e}var jb=n=>{if(!(n!==void 0&&er(n).length!==0))return"text-align:center";let t=Yb(n),r=Xb(n);return`position: absolute;margin: 0;transform: translate(${t.offset}%,${r.offset}%);width: ${eS(n.size)}%;left: ${t.position}%;top: ${r.position!==null?`${r.position}%`:"auto"};text-align: ${Ul(n.align)};`};var Yb=n=>({position:Qb(n),offset:$b(n)}),Qb=n=>{let e=Fl(n.position);if(e!==null)return e;let t=Ul(n.align);return{left:0,center:50,right:100}[t]},$b=n=>{let e=a=>{let d=/,(line-left|line-right|center)/.exec(a);return!Array.isArray(d)||d.length<2?null:d[1]},t={"line-left":0,center:-50,"line-right":-100},r=n.position!==void 0?e(n.position):null;if(r!==null)return t[r];let i={left:0,center:-50,right:-100},o=n.align!==void 0?Ul(n.align):"center";return i[o]},Xb=n=>({position:Zb(n.line),offset:Jb(n.line)}),Zb=n=>Fl(n),Jb=n=>{let e=i=>{let a=/,(start|center|end)/.exec(i);return!Array.isArray(a)||a.length<2?null:a[1]},t={start:0,center:-50,end:-100};if(n===void 0)return t.start;let r=e(n);return r!==null?t[r]:t.start},Ul=n=>{switch(n){case"left":case"start":return"left";case"right":case"end":return"right";default:return"center"}},eS=n=>tS(n,100),tS=(n,e)=>{let t=Fl(n);return t!==null?t:e},Fl=n=>{if(n===void 0)return null;let t=/^([\d.]+)%/.exec(n);return!Array.isArray(t)||t.length<2?null:parseInt(t[1],10)};function Rr(n,e){let{start:t,end:r,settings:i,header:o,payload:a}=n,s=document.createElement("div"),d=document.createAttribute("style");d.value="width:100%;height:100%;display:flex;flex-direction:column;justify-content:flex-end;align-items:center;",s.setAttributeNode(d);let u=document.createElement("p"),c=Bl(i);u.setAttributeNode(c);let l=document.createElement("span"),f=document.createAttribute("style");f.value="background-color:rgba(0,0,0,0.8);color:white;",l.setAttributeNode(f);let{global:m,classes:g}=e,I=x(o)?g[o]:void 0,h=[m,I].filter(y=>y!==void 0).join("");return f.value+=h,l.setAttributeNode(f),Nl(a.join(`
|
|
14
|
+
`),g).forEach(y=>{l.appendChild(y)}),s.appendChild(u),u.appendChild(l),{start:t,end:r,element:s}}function ds(n,{initTimescale:e},t){return typeof n=="string"?$n(Re(n),e!=null?e:1,t,Rr):$n(Ue(n),e!=null?e:1,t,Rr)}function us(n){let e=0;for(;e<n.length;){if(n[e]==="")return e+1;e++}return e}function Kl(n,e){return typeof n[e]=="string"&&/^STYLE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function nS(n,e){return typeof n[e]=="string"&&/^NOTE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function rS(n,e){return typeof n[e]=="string"&&/^REGION( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function Mp(n,e){let t=n[e];if(t===void 0||t===""||Kl(n,e)||rS(n,e)||nS(n,e))return!1;if(t.indexOf("-->")>=0)return!0;let r=n[e+1];return r!==void 0&&r.indexOf("-->")>=0}function Ap(n,e){let t=e+1;for(;x(n[t]);)t++;return t}function Co(n,e){let t=[];for(let r=e;r<n.length;r++)if(Mp(n,r)){let i=Ap(n,r);t.push(n.slice(r,i)),r=i}else if(x(n[r]))for(;x(n[r]);)r++;return t}function Po(n,e){let t=[];for(let r=e;r<n.length;r++)if(Kl(n,r)){let i=r;for(r++;x(n[r]);)r++;let o=n.slice(i,r);t.push(o)}else if(x(n[r]))for(;x(n[r]);)r++;return t}var Vl={white:"#ffffff",lime:"#00ff00",cyan:"#00ffff",red:"#ff0000",yellow:"#ffff00",magenta:"#ff00ff",blue:"#0000ff",black:"#000000"};function zl(){return Object.keys(Vl).reduce((n,e)=>(n[e]=`color: ${Vl[e]};`,n[`bg_${e}`]=`background-color: ${Vl[e]};`,n),{})}function Mo(n){let e=zl(),t="";return n.forEach(r=>{if(r.length>=2)for(let i=1;i<r.length;i++){let o=r[i];if(Array.isArray(/::cue {/.exec(o)))for(o=r[++i];x(o)&&!(Array.isArray(/}/.exec(o))||o.length===0);)t+=o,o=r[++i];else{let a=[],s=/::cue\(\.?(.*?)\)(?:,| {)/.exec(o);for(;x(o)&&Array.isArray(s);)a.push(s[1]),o=r[++i],s=/::cue\(\.?(.*?)\)(?:,| {)/.exec(o);let d="";for(;x(o)&&!(Array.isArray(/}/.exec(o))||o.length===0);)d+=o,o=r[++i];a.forEach(u=>{e[u]===void 0?e[u]=d:e[u]+=d})}}}),{classes:e,global:t}}function ls(n,e,t){let r;typeof n=="string"?r=n:r=he(Ue(n));let i=/\r\n|\n|\r/g,o=r.split(i),a=[];if(/^WEBVTT( |\t|\n|\r|$)/.exec(o[0])===null)throw new Error("Can't parse WebVTT: Invalid File.");let s=us(o),d=Po(o,s),u=Co(o,s),c=Mo(d);for(let l=0;l<u.length;l++){let f=Ro(u[l],t);if(f!==null){let m=Rr(f,c);a.push(m)}}return a}function Wl(n){n.htmlTextTracksParsers.vtt=ls,n.htmlTextTracksParsers.mp4vtt=ds,n.htmlTextDisplayer=Sn}function Hl(n){var i;let e,t,r="subtitles";if(V.browser===V.BROWSERS.Ie11||V.browser===V.BROWSERS.OtherIeOrEdgePreEdgeChromium){let o=n.textTracks.length;e=o>0?n.textTracks[o-1]:n.addTextTrack(r),e.mode=(i=e.SHOWING)!=null?i:"showing"}else t=document.createElement("track"),n.appendChild(t),e=t.track,t.kind=r,e.mode="showing";return{track:e,trackElement:t}}function iS(n,e){let{activeCues:t}=n;if(t===null)return!1;for(let r=0;r<t.length;r++)if(t[r]===e)return!0;return!1}function ql(n,e){if(V.browser===V.BROWSERS.Firefox&&iS(n,e)){let t=n.mode;n.mode="hidden";try{n.removeCue(e)}catch(r){p.warn("text","Could not remove cue from text track.")}n.mode=t;return}try{n.removeCue(e)}catch(t){p.warn("text","Could not remove cue from text track.")}}function Gl(n,e,t,r){p.debug("text","Finding parser for native text tracks:",{type:n});let i=pe.nativeTextTracksParsers[n];if(typeof i!="function")throw new Error("no parser found for the given text track");p.debug("text","Parser found, parsing...",{type:n});let o=i(e,t,r);return p.debug("text","Parsed successfully!",{length:o.length}),o}var Ao=class{constructor(e){p.debug("text","Creating NativeTextDisplayer");let{track:t,trackElement:r}=Hl(e);this._buffered=new Yn,this._videoElement=e,this._track=t,this._trackElement=r}pushTextData(e){var h,y;if(p.debug("text","Appending new native text tracks"),e.chunk===null)return We(this._buffered);let{timestampOffset:t,appendWindow:r,chunk:i}=e,{start:o,end:a,data:s,type:d,language:u,initTimescale:c}=i,l=(h=r[0])!=null?h:0,f=(y=r[1])!=null?y:1/0,m=Gl(d,s,{initTimescale:c,language:u},t);if(l!==0&&f!==1/0){let T=0;for(;T<m.length&&m[T].endTime<=l;)T++;for(m.splice(0,T),T=0;T<m.length&&m[T].startTime<l;)m[T].startTime=l,T++;for(T=m.length-1;T>=0&&m[T].startTime>=f;)T--;for(m.splice(T,m.length),T=m.length-1;T>=0&&m[T].endTime>f;)m[T].endTime=f,T--}let g;if(o!==void 0)g=Math.max(l,o);else{if(m.length<=0)return p.warn("text","Current text tracks have no cues nor start time. Aborting"),We(this._buffered);p.warn("text","No start time given. Guessing from cues."),g=m[0].startTime}let I;if(a!==void 0)I=Math.min(f,a);else{if(m.length<=0)return p.warn("text","Current text tracks have no cues nor end time. Aborting"),We(this._buffered);p.warn("text","No end time given. Guessing from cues."),I=m[m.length-1].endTime}if(I<=g)return p.warn("text","Invalid text track appended: ","the start time is inferior or equal to the end time."),We(this._buffered);if(m.length>0){let T=m[0],v=this._track.cues;v!==null&&v.length>0&&T.startTime<v[v.length-1].startTime&&this._removeData(T.startTime,1/0);for(let E of m)this._track.addCue(E)}return this._buffered.insert(g,I),We(this._buffered)}removeBuffer(e,t){return this._removeData(e,t),We(this._buffered)}getBufferedRanges(){return We(this._buffered)}reset(){p.debug("text","Aborting NativeTextDisplayer"),this._removeData(0,1/0),this._clearTrackElement()}stop(){p.debug("text","Aborting NativeTextDisplayer"),this._removeData(0,1/0);let{_trackElement:e,_videoElement:t}=this;if(e!==void 0&&t.hasChildNodes())try{t.removeChild(e)}catch(r){p.warn("text","Can't remove track element from the video")}this._track.mode="disabled",this._trackElement!==void 0&&(this._trackElement.innerHTML="")}_removeData(e,t){p.debug("text","Removing native text track data",{start:e,end:t});let r=this._track,i=r.cues;if(i!==null)for(let o=i.length-1;o>=0;o--){let a=i[o],{startTime:s,endTime:d}=a;s>=e&&s<=t&&d<=t&&ql(r,a)}this._buffered.remove(e,t)}_clearTrackElement(){let{_trackElement:e,_videoElement:t}=this;if(e!==void 0&&t.hasChildNodes())try{t.removeChild(e)}catch(i){p.warn("text","Can't remove track element from the video")}let r=this._track.mode;this._track.mode="disabled",this._track.mode=r,this._trackElement!==void 0&&(this._trackElement.innerHTML="")}};var _n=Ao;function en(n,e,t){if(n>=e)return p.warn("text","Invalid cue times: start after end.",{startTime:n,endTime:e}),null;if(_(Z.VTTCue)){if(_(Z.TextTrackCue))throw new Error("VTT cues not supported in your target");return new TextTrackCue(n,e,t)}else return new VTTCue(n,e,t)}var oS=/&#([0-9]+);/g,aS=/<br>/gi,sS=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,dS=/\s*<p (?:class=([^>]+))?>(.*)/i,uS=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function lS(n){let e=[];for(let t=0;t<n.length;t++){let{start:r,end:i,text:o}=n[t];if(x(o)&&!_(i)){let a=en(r,i,o);a!==null&&e.push(a)}}return e}function cS(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;Array.isArray(r);){let i=r[1],o=fS(r[2],"lang");!_(i)&&!_(o)&&(t[o]=i),r=e.exec(n)}return t}function fS(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function mS(n){return n.replace(aS,`
|
|
15
|
+
`).replace(oS,(e,t)=>String.fromCharCode(Number(t)))}function pS(n,{language:e},t){let r;typeof n!="string"?r=he(Ue(n)):r=n;let i=/<sync[ >]/gi,o=/<sync[ >]|<\/body>/gi,a=[],s=sS.exec(r),d=s!==null?s[1]:"",u,c;o.exec(r);let l=cS(d),f;if(x(e)&&(f=l[e],f===void 0))throw new Error(`sami: could not find lang ${e} in CSS`);for(;u=i.exec(r),c=o.exec(r),!(u===null&&c===null);){if(u===null||c===null||u.index>=c.index)throw new Error("parse error");let g=r.slice(u.index,c.index),I=uS.exec(g);if(I===null)throw new Error("parse error (sync time attribute)");let h=+I[1];if(isNaN(h))throw new Error("parse error (sync time attribute NaN)");m(g.split(`
|
|
16
|
+
`),h/1e3)}return lS(a);function m(g,I){let h=g.length,y;for(;--h>=0;){if(y=dS.exec(g[h]),y===null)continue;let[,T,v]=y;f===T&&(v===" "?a[a.length-1].end=I:a.push({text:mS(v),start:I+t}))}}}var xp=pS;function jl(n){n.nativeTextTracksParsers.sami=xp,n.nativeTextDisplayer=_n}function Yl(n,e,t){let r;typeof n!="string"?r=he(Ue(n)):r=n;let i=r.split(/\r\n|\n|\r/),o=To(i),a=[];for(let s=0;s<o.length;s++){let d=_o(o[s],t);if(d!==null){let u=gS(d);u!==null&&a.push(u)}}return a}function gS(n){let{start:e,end:t,payload:r}=n,i=r.join(`
|
|
17
|
+
`);return en(e,t,i)}function Ql(n){n.nativeTextTracksParsers.srt=Yl,n.nativeTextDisplayer=_n}function xo(n){return typeof Z.VTTCue=="function"&&n instanceof Z.VTTCue}var hS={left:"start",center:"center",right:"end",start:"start",end:"end"},IS={left:"line-left",center:"center",right:"line-right"};function $l(n){let{paragraph:e,timeOffset:t,paragraphStyle:r,ttParams:i,shouldTrimWhiteSpace:o}=n;if(!e.hasAttribute("begin")&&!e.hasAttribute("end")&&/^\s*$/.test(e.textContent===null?"":e.textContent))return null;let{start:a,end:s}=vo(e,i),d=yS(e,o),u=en(a+t,s+t,d);return u===null?null:(xo(u)&&bS(u,r),u)}function yS(n,e){function t(r,i){let o=r.childNodes,a="";for(let s=0;s<o.length;s++){let d=o[s];if(d.nodeName==="#text"){let u=d.textContent;if(u===null&&(u=""),i){let l=u.trim();l=l.replace(/\s+/g," "),u=l}let c=u.replace(/&|\u0026/g,"&").replace(/<|\u003C/g,"<").replace(/>|\u2265/g,">").replace(/\u200E/g,"‎").replace(/\u200F/g,"‏").replace(/\u00A0/g," ");a+=c}else if(is(d))a+=`
|
|
18
|
+
`;else if(os(d)&&d.nodeType===Node.ELEMENT_NODE&&d.childNodes.length>0){let u=d.getAttribute("xml:space"),c=x(u)?u==="default":i;a+=t(d,c)}}return a}return t(n,e)}function bS(n,e){let t=e.extent;if(x(t)){let a=El.exec(t);_(a)||(n.size=Number(a[1]))}switch(e.writingMode){case"tb":case"tblr":n.vertical="lr";break;case"tbrl":n.vertical="rl";break;default:break}let i=e.origin;if(x(i)){let a=El.exec(i);_(a)}let o=e.align;if(x(o)){n.align=o,o==="center"&&(n.align!=="center"&&(n.align="middle"),n.position="auto");let a=IS[o];n.positionAlign=a===void 0?"":a;let s=hS[o];n.lineAlign=s===void 0?"":s}}function Xl(n,e,t){let r;typeof n!="string"?r=he(Ue(n)):r=n;let i=Eo(r,t),o=[];for(let a of i){let s=$l(a);s!==null&&o.push(s)}return o}var wp=Xl;function Zl(n){n.nativeTextTracksParsers.ttml=wp,n.nativeTextDisplayer=_n}function Jl(n,e){if(x(n.vertical)&&(n.vertical==="rl"||n.vertical==="lr")&&(e.vertical=n.vertical),x(n.line)){let r=/^(\d+(\.\d+)?)%(,([a-z]+))?/.exec(n.line);if(Array.isArray(r))e.line=Number(r[1]),e.snapToLines=!1,J(["start","center","end"],r[4])&&(e.lineAlign=r[4]);else{let o=/^(-?\d+)(,([a-z]+))?/.exec(n.line);Array.isArray(o)&&(e.line=Number(o[1]),e.snapToLines=!0,J(["start","center","end"],o[3])&&(e.lineAlign=o[3]))}}if(x(n.position)){let r=/^([\d.]+)%(?:,(line-left|line-right|center))?$/.exec(n.position);if(Array.isArray(r)&&r.length>=2){let i=parseInt(r[1],10);isNaN(i)||(e.position=i,r[2]!==void 0&&(e.positionAlign=r[2]))}}x(n.size)&&(e.size=n.size),typeof n.align=="string"&&J(["start","center","end","left"],n.align)&&(e.align=n.align)}function kr(n,e){let{start:t,end:r,payload:i}=n,o=i.join(`
|
|
19
|
+
`);return en(t,r,o)}function cs(n,e,t){let r;typeof n=="string"?r=n:r=he(Ue(n));let i=r.split(/\r\n|\n|\r/);if(!/^WEBVTT($| |\t)/.test(i[0]))throw new Error("Can't parse WebVTT: Invalid file.");let o=us(i),a=Co(i,o),s=Po(i,o),d=Mo(s),u=[];for(let c of a){let l=Ro(c,t);if(l!==null){let f=kr(l,d);f!==null&&(xo(f)&&Jl(l.settings,f),u.push(f))}}return u}function fs(n,{initTimescale:e},t){return typeof n=="string"?$n(Re(n),e!=null?e:1,t,kr):$n(Ue(n),e!=null?e:1,t,kr)}function ec(n){n.nativeTextTracksParsers.vtt=cs,n.nativeTextTracksParsers.mp4vtt=fs,n.nativeTextDisplayer=_n}function Cr(n){let e=[];n.periods.forEach(t=>{let r=t.id;if(J(e,r)){p.warn("utils","Two periods with the same ID found. Updating.",{periodID:r});let a=r+"-dup";t.id=a,Cr(n),e.push(a)}else e.push(r);let{adaptations:i}=t,o=[];Object.keys(i).forEach(a=>{let s=i[a];s!==void 0&&s.forEach(d=>{let u=d.id;if(J(o,u)){p.warn("utils","Two adaptations with the same ID found. Updating.",{adaptationID:u});let l=u+"-dup";d.id=l,Cr(n),o.push(l)}else o.push(u);let c=[];d.representations.forEach(l=>{let f=l.id;if(J(c,f)){p.warn("utils","Two representations with the same ID found. Updating.",{representationID:f});let m=`${f}-dup`;l.id=m,Cr(n),c.push(m)}else c.push(f)})})})})}function Op(n,e){let t;return e==="AACH"?t=5:t=x(n)?(parseInt(n.substring(0,2),16)&248)>>3:2,t===0?"mp4a.40.2":`mp4a.40.${t}`}function Dp(n){let e=/00000001\d7([0-9a-fA-F]{6})/.exec(n);return e===null||!x(e[1])?"avc1.4D401E":"avc1."+e[1]}function tc(n){return n.reduce((e,t,r)=>{var c,l,f,m;if(typeof t=="string")return e;let i=(c=t.attributes.d)!=null?c:null,o=(l=t.attributes.t)!=null?l:null,a=(f=t.attributes.r)!=null?f:null,s=a!==null?+a-1:0,d=o!==null?+o:void 0,u=i!==null?+i:void 0;if(r===0)d=d===void 0||isNaN(d)?0:d;else{let g=e[r-1];if(d===void 0||isNaN(d)){if(g.duration===void 0||isNaN(g.duration))throw new Error("Smooth: Invalid CNodes. Missing timestamp.");d=g.start+g.duration*(g.repeatCount+1)}}if(u===void 0||isNaN(u)){let g=r,I;do g++,I=n[g];while(I!==void 0&&typeof I=="string");if(I!==void 0){let h=(m=I.attributes.t)!=null?m:null,y=x(h)?+h:null;if(y===null)throw new Error("Can't build index timeline from Smooth Manifest.");u=y-d}else return e}return e.push({duration:u,start:d,repeatCount:s}),e},[])}function SS(n){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:le([8,1,18,16],n)}]}function nc(n,e=SS){var u;let t;for(let c of n.children)if(typeof c!="string"&&c.tagName==="ProtectionHeader"){t=c;break}if(t===void 0)throw new Error("Protection should have ProtectionHeader child");let r=Ct(typeof t.children[0]=="string"?t.children[0]:""),i=$r(r),o=st(i),a=(u=t.attributes.SystemID)!=null?u:null,s=(a!==null?a:"").toLowerCase().replace(/\{|\}/g,""),d=e(o);return{keyId:o,keySystems:[{systemId:s,privateData:r}].concat(d)}}function Lp(n,e,t){return n.replace(/\{bitrate\}/g,String(e)).replace(/{CustomAttributes}/g,t.length>0?t[0]:"")}function Np(n,e){return n.replace(/\{start time\}/g,String(e))}function TS(n,e,t){let r=e-n;return r>0?Math.floor(r/t):0}function _S(n,e,t){let r=n===void 0||n===0?1:n;return{up:e*r,to:(e+t)*r}}function ES(n,e){let t=n.repeatCount;if(n.duration!==void 0&&t<0){let r=e!==void 0?e.start:1/0;t=Math.ceil((r-n.start)/n.duration)-1}return t}var wo=class{constructor(e){let{isLive:t,segmentPrivateInfos:r,media:i,sharedSmoothTimeline:o}=e;if(this._sharedSmoothTimeline=o,this._initSegmentInfos={bitsPerSample:r.bitsPerSample,channels:r.channels,codecPrivateData:r.codecPrivateData,packetSize:r.packetSize,samplingRate:r.samplingRate,timescale:o.timescale,height:r.height,width:r.width,protection:r.protection},this._isLive=t,this._media=i,o.timeline.length!==0&&t){let{timeline:a,validityTime:s}=o,d=a[a.length-1],u=Ne(d,null),c=s/1e3*o.timescale;this._scaledLiveGap=c-u}}getInitSegment(){return{id:"init",isInit:!0,privateInfos:{smoothInitSegment:this._initSegmentInfos},url:null,time:0,end:0,duration:0,timescale:1,complete:!0}}getSegments(e,t){this._refreshTimeline();let{timescale:r,timeline:i}=this._sharedSmoothTimeline,{up:o,to:a}=_S(r,e,t),s=this._media,d,u=[],c=i.length,l=this._scaledLiveGap===void 0?void 0:z()/1e3*r-this._scaledLiveGap;for(let f=0;f<c;f++){let m=i[f],{duration:g,start:I}=m,h=ES(m,i[f+1]),y=TS(I,o,g),T=I+y*g,v=g;for(;T<a&&y<=h&&(l===void 0||T+v<=l);){let E=T,R=d!==void 0?d+y:void 0,k={id:String(T),isInit:!1,time:E/r,end:(E+g)/r,duration:g/r,timescale:1,number:R,url:Np(s,E),complete:!0,privateInfos:{smoothMediaSegment:{time:E,duration:g}}};u.push(k),y++,T=I+y*g}if(T>=a)return u;d!==void 0&&(d+=h+1)}return u}shouldRefresh(e,t){if(this._refreshTimeline(),!this._isLive)return!1;let{timeline:r,timescale:i}=this._sharedSmoothTimeline,o=r[r.length-1];if(o===void 0)return!1;let a=o.repeatCount,s=o.start+(a+1)*o.duration;if(t*i<s)return!1;if(e*i>=s)return!0;let d=o.start+a*o.duration;return e*i>d}getFirstAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;return e.length===0?null:e[0].start/t}getLastAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;if(this._scaledLiveGap===void 0){let r=e[e.length-1];return Ne(r,null)/t}for(let r=e.length-1;r>=0;r--){let i=e[r],o=z()/1e3*t,{start:a,duration:s,repeatCount:d}=i;for(let u=d;u>=0;u--){let c=a+s*(u+1);if(c<=o-this._scaledLiveGap)return c/t}}}getEnd(){if(!this._isLive)return this.getLastAvailablePosition()}awaitSegmentBetween(e,t){var i;if(ee(e<=t),this.isStillAwaitingFutureSegments())return!1;let r=this.getLastAvailablePosition();return r!==void 0&&t<r?!1:t>((i=this.getFirstAvailablePosition())!=null?i:0)?void 0:!1}checkDiscontinuity(e){return this._refreshTimeline(),qa(this._sharedSmoothTimeline,e,void 0)}isSegmentStillAvailable(e){if(e.isInit)return!0;this._refreshTimeline();let{timeline:t,timescale:r}=this._sharedSmoothTimeline;for(let i=0;i<t.length;i++){let o=t[i],a=o.start/r;if(a>e.time)return!1;if(a===e.time)return!0;if(o.repeatCount>=0&&o.duration!==void 0){let d=(a-o.start)/o.duration-1;return d%1===0&&d<=o.repeatCount}}return!1}canBeOutOfSyncError(e){return this._isLive?e instanceof at&&(e.isHttpError(404)||e.isHttpError(412)):!1}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}_replace(e){this._initialScaledLastPosition=e._initialScaledLastPosition,this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.replace(e._sharedSmoothTimeline)}_update(e){this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.update(e._sharedSmoothTimeline)}isStillAwaitingFutureSegments(){return this._isLive}isInitialized(){return!0}initialize(){p.error("smooth","A `SmoothRepresentationIndex` does not need to be initialized")}addPredictedSegments(e,t){this._sharedSmoothTimeline.addPredictedSegments(e,t)}_refreshTimeline(){this._sharedSmoothTimeline.refresh()}};function rc(n,e,t,r){let i=n.length,o=n[i-1],a=t.timescale===e?{time:t.time,duration:t.duration}:{time:t.time/t.timescale*e,duration:t.duration/t.timescale*e};return r.time===a.time?!1:a.time>=Ne(o,null)?(o.duration===a.duration?o.repeatCount++:n.push({duration:a.duration,start:a.time,repeatCount:0}),!0):!1}var Oo=class{constructor(e){let{timeline:t,timescale:r,timeShiftBufferDepth:i,manifestReceivedTime:o}=e;this.timeline=t,this.timescale=r;let a=o!=null?o:z();if(this.validityTime=a,this._timeShiftBufferDepth=i,t.length!==0){let s=t[t.length-1],d=Ne(s,null);this._initialScaledLastPosition=d}}refresh(){if(this._initialScaledLastPosition===void 0)return;let e=this._timeShiftBufferDepth,r=(z()-this.validityTime)/1e3+this._initialScaledLastPosition/this.timescale;if(e!==void 0){let i=(r-e)*this.timescale;ro(this.timeline,i)}}replace(e){let t=this.timeline,r=e.timeline,i=this.timescale,o=e.timescale;if(this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime,t.length===0||r.length===0||i!==o)return;let a=t[t.length-1],s=r[r.length-1],d=Ne(s,null);if(!(Ne(a,null)<=d))for(let u=0;u<t.length;u++){let c=t[u],l=Ne(c,null);if(l===d){this.timeline=this.timeline.concat(t.slice(u+1));return}if(l>d){if(c.duration!==s.duration)return;let f=d-c.start;if(f===0){p.warn("smooth","a discontinuity detected in the previous manifest has been resolved."),this.timeline=this.timeline.concat(t.slice(u));return}if(f<0||f%c.duration!==0)return;let m=f/c.duration-1,g=c.repeatCount-m;if(g<0)return;s.repeatCount+=g;let I=t.slice(u+1);this.timeline=this.timeline.concat(I);return}}}update(e){io(this.timeline,e.timeline),this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime}addPredictedSegments(e,t){var r;if(((r=t.privateInfos)==null?void 0:r.smoothMediaSegment)===void 0){p.warn("smooth","should only encounter SmoothRepresentationIndex");return}this.refresh();for(let i of e)rc(this.timeline,this.timescale,i,t.privateInfos.smoothMediaSegment)}};function ic(n){return typeof n=="boolean"?n:typeof n=="string"?n.toUpperCase()==="TRUE":!1}function Pr(n,e,t){let r=t;for(let i of n.children)typeof i!="string"&&(r=e(r,i.tagName,i));return r}var vS={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},Do={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4",DFXP:"application/ttml+xml+mp4"};function RS(n={}){let e=n.referenceDateTime===void 0?Date.UTC(1970,0,1,0,0,0,0)/1e3:n.referenceDateTime,t=n.minRepresentationBitrate===void 0?0:n.minRepresentationBitrate,{serverSyncInfos:r}=n,i=r!==void 0?r.serverTimestamp-r.clientTime:void 0;function o(d,u){let c=Pr(d,(f,m,g)=>(m==="CustomAttributes"&&f.push(...Pr(g,(I,h,y)=>{if(h==="Attribute"){let T=y.attributes.Name,v=y.attributes.Value;!_(T)&&!_(v)&&I.push(T+"="+v)}return I},[])),f),[]);function l(f){let m=d.attributes[f];return m===null?void 0:m}switch(u){case"audio":{let f=l("AudioTag"),m=l("BitsPerSample"),g=l("Channels"),I=l("CodecPrivateData"),h=l("FourCC"),y=l("PacketSize"),T=l("SamplingRate"),v=l("Bitrate"),E=v===void 0?0:parseInt(v,10);if(E=isNaN(E)?0:E,h!==void 0&&Do[h]===void 0||I===void 0)return p.warn("smooth","Unsupported audio codec. Ignoring quality level.",{fourCC:h}),null;let R=Op(I,h);return{audiotag:f!==void 0?parseInt(f,10):f,bitrate:E,bitsPerSample:m!==void 0?parseInt(m,10):m,channels:g!==void 0?parseInt(g,10):g,codecPrivateData:I,codecs:R,customAttributes:c,mimeType:h!==void 0?Do[h]:h,packetSize:y!==void 0?parseInt(y,10):y,samplingRate:T!==void 0?parseInt(T,10):T}}case"video":{let f=l("CodecPrivateData"),m=l("FourCC"),g=l("MaxWidth"),I=l("MaxHeight"),h=l("Bitrate"),y=h===void 0?0:parseInt(h,10);if(y=isNaN(y)?0:y,m!==void 0&&Do[m]===void 0||f===void 0)return p.warn("smooth","Unsupported video codec. Ignoring quality level.",{fourCC:m}),null;let T=Dp(f);return{bitrate:y,customAttributes:c,mimeType:m!==void 0?Do[m]:m,codecPrivateData:f,codecs:T,width:g!==void 0?parseInt(g,10):void 0,height:I!==void 0?parseInt(I,10):void 0}}case"text":{let f=l("CodecPrivateData"),m=l("FourCC"),g=l("Bitrate"),I=g===void 0?0:parseInt(g,10);return I=isNaN(I)?0:I,{bitrate:I,customAttributes:c,mimeType:m!==void 0?Do[m]:m,codecPrivateData:f!=null?f:""}}default:return p.error("smooth","Unrecognized StreamIndex type: "+u),null}}function a(d){let{root:u,timescale:c,baseUrl:l,protections:f,timeShiftBufferDepth:m,manifestReceivedTime:g,isLive:I}=d,h=u.attributes.Timescale,y=x(h)?+h:c;isNaN(y)&&(y=c);let T=u.attributes.Type;if(_(T))throw new Error("StreamIndex without type.");J(an,T)||p.warn("smooth","Unrecognized adaptation type:",T);let v=T,E=u.attributes.Subtype,R=u.attributes.Language,k=u.attributes.Url,A=k!=null?k:"";ee(A!=="");let{qualityLevels:P,cNodes:M}=Pr(u,(C,w,F)=>{switch(w){case"QualityLevel":{let K=o(F,v);if(K===null)return C;(v!=="video"||K.bitrate>t)&&C.qualityLevels.push(K);break}case"c":C.cNodes.push(F);break}return C},{qualityLevels:[],cNodes:[]}),N=new Oo({timeline:tc(M),timescale:y,timeShiftBufferDepth:m,manifestReceivedTime:g});ee(P.length!==0,"Adaptation should have at least one playable representation.");let U=v+(x(R)?"_"+R:""),L=P.map(C=>{let w=Lp(A,C.bitrate,C.customAttributes),F=x(C.mimeType)?C.mimeType:vS[v],K=C.codecs,Y=U+"_"+(_(v)?"":v+"-")+(_(F)?"":F+"-")+(_(K)?"":K+"-")+String(C.bitrate),ie=[],j;f.length>0&&(j=f[0],f.forEach(de=>{ie.push(de.keyId)}));let Q={bitsPerSample:C.bitsPerSample,channels:C.channels,codecPrivateData:C.codecPrivateData,packetSize:C.packetSize,samplingRate:C.samplingRate,height:C.height,width:C.width,protection:_(j)?void 0:{keyId:j.keyId}},ne=new wo({isLive:I,sharedSmoothTimeline:N,media:w,segmentPrivateInfos:Q}),X=G({},C,{index:ne,cdnMetadata:[{baseUrl:l}],mimeType:F,codecs:K,id:Y});if(ie.length>0||j!==void 0){let de=j===void 0?[]:j.keySystems.map(ue=>{let{systemId:ve,privateData:ce}=ue,ye=ve.replace(/-/g,""),ct=kS(ye,ce);return{systemId:ye,data:ct}});if(de.length>0){let ue=[{type:"cenc",values:de}];X.contentProtections={keyIds:ie,initData:ue}}else X.contentProtections={keyIds:ie,initData:[]}}return X});if(E==="ADVT")return null;let B={id:U,type:v,representations:L,language:R===null?void 0:R};return v==="text"&&E==="DESC"&&(B.closedCaption=!0),B}function s(d,u,c){let l=to(d),f=l[l.length-1],m="";if(u!==void 0){let X=Li(u);m=u.substring(0,X)}if(_(f)||typeof f=="string"||f.tagName!=="SmoothStreamingMedia")throw new Error("document root should be SmoothStreamingMedia");let g=f.attributes.MajorVersion,I=f.attributes.MinorVersion;if(_(g)||_(I)||!/^[2]-[0-2]$/.test(g+"-"+I))throw new Error("Version should be 2.0, 2.1 or 2.2");let h=f.attributes.Timescale,y=x(h)?+h:1e7;isNaN(y)&&(y=1e7);let{protections:T,adaptationNodes:v}=Pr(f,(X,de,ue)=>{switch(de){case"Protection":{X.protections.push(nc(ue,n.keySystems));break}case"StreamIndex":X.adaptationNodes.push(ue);break}return X},{adaptationNodes:[],protections:[]}),E={},R=ic(f.attributes.IsLive),k;if(R){let X=f.attributes.DVRWindowLength;!_(X)&&!isNaN(+X)&&+X!=0&&(k=+X/y)}let A=v.reduce((X,de)=>{let ue=a({root:de,baseUrl:m,timescale:y,protections:T,isLive:R,timeShiftBufferDepth:k,manifestReceivedTime:c});if(ue===null)return X;let ve=ue.type,ce=X[ve];return ce===void 0?X[ve]=[ue]:ce.push(ue),X},E),P,M,N,U=null,L,B=A.video!==void 0?A.video[0]:void 0,C=A.audio!==void 0?A.audio[0]:void 0,w,F,K;if(B!==void 0||C!==void 0){let X=[],de=[];if(B!==void 0){let ue=B.representations[0];if(ue!==void 0){let ve=ue.index.getFirstAvailablePosition(),ce=ue.index.getLastAvailablePosition();_(ve)||X.push(ve),_(ce)||de.push(ce)}}if(C!==void 0){let ue=C.representations[0];if(ue!==void 0){let ve=ue.index.getFirstAvailablePosition(),ce=ue.index.getLastAvailablePosition();_(ve)||X.push(ve),_(ce)||de.push(ce)}}X.length>0&&(w=Math.max(...X)),de.length>0&&(F=Math.min(...de),K=Math.max(...de))}let Y=f.attributes.Duration,ie=!_(Y)&&+Y!=0?+Y/y:void 0;if(R){P=n.suggestedPresentationDelay,M=e,N=w!=null?w:M;let X=K;X===void 0&&(X=Date.now()/1e3-M);let de=F;de===void 0&&(de=X),L={isLinear:!0,maximumSafePosition:de,livePosition:X,time:z()},U=k!=null?k:null}else{N=w!=null?w:0;let X=F;X===void 0&&(X=ie!==void 0?N+ie:1/0),L={isLinear:!1,maximumSafePosition:X,livePosition:void 0,time:z()}}let j=R?0:N,Q=R?void 0:L.maximumSafePosition,ne={availabilityStartTime:M===void 0?0:M,clockOffset:i,isLive:R,isDynamic:R,isLastPeriodKnown:!0,timeBounds:{minimumSafePosition:N,timeshiftDepth:U,maximumTimeData:L},periods:[{adaptations:A,duration:Q!==void 0?Q-j:ie,end:Q,id:"gen-smooth-period-0",start:j,thumbnailTracks:[]}],suggestedPresentationDelay:P,transportType:"smooth",uris:_(u)?[]:[u]};return Cr(ne),ne}return s}function kS(n,e){if(n.length!==32)throw new Error("HSS: wrong system id length");return Ie("pssh",le([0,0,0,0],st(n),Ce(e.length),e))}var Bp=RS;var Up=Bp;function Fp(n,e,t,r,i,o,a){return Ie("avc1",le(6,Se(1),16,Se(n),Se(e),Se(t),2,Se(r),6,[0,1,i.length],Re(i),31-i.length,Se(o),[255,255],a))}function Kp(n,e,t,r,i,o,a,s){return Ie("encv",le(6,Se(1),16,Se(n),Se(e),Se(t),2,Se(r),6,[0,1,i.length],Re(i),31-i.length,Se(o),[255,255],a,s))}function Vp(n,e,t,r,i,o){return Ie("mp4a",le(6,Se(n),8,Se(e),Se(t),2,Se(r),Se(i),2,o))}function zp(n,e,t,r,i,o,a){return Ie("enca",le(6,Se(n),8,Se(e),Se(t),2,Se(r),Se(i),2,o,a))}function Wp(n){return Ie("dref",le(7,[1],n))}function Hp(n,e){let t=le(...[Re(n),[0,0,0,1]].concat(e.map(Re)));return Ie("ftyp",t)}function ms(n,e){return Ie("schm",le(4,Re(n),Ce(e)))}function qp(n){return Ie("tfdt",le([1,0,0,0],cn(n)))}function Gp(){let n=new Uint8Array(12);return n[3]=1,Ie("vmhd",n)}function jp(n){return Ie("trex",le(4,Ce(n),[0,0,0,1],12))}function Yp(n){return Ie("free",new Uint8Array(n-8))}function Qp(n,e){return Ie("esds",le(4,[3,25],Se(n),[0,4,17,64,21],11,[5,2],st(e),[6,1,2]))}function ps(n){return Ie("frma",Re(n))}function $p(n,e,t){let r;t===2?r=1:t===4?r=3:r=0;let i=n[1],o=n[2],a=n[3];return Ie("avcC",le([1,i,o,a,252|r,225],Se(n.length),n,[1],Se(e.length),e))}function Xp(n){let e,t;switch(n){case"video":e="vide",t="VideoHandler";break;case"audio":e="soun",t="SoundHandler";break;default:e="hint",t="";break}return Ie("hdlr",le(8,Re(e),12,Re(t),1))}function Zp(n){return Ie("mdhd",le(12,Ce(n),8))}function Jp(n,e){return Ie("mvhd",le(12,Ce(n),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,Se(e+1)))}function eg(n,e,t,r){return Ie("saio",le(4,[0,0,0,1],Ce(n.length+e.length+t.length+r.length+8+8+8+8)))}function tg(n){if(n.length===0)return Ie("saiz",new Uint8Array(0));let e=te(n,0),t=te(n,4),r=new Uint8Array(t+9);r.set(Ce(t),5);let i=9,o=8,a,s;for(;o<n.length;)o+=8,(e&2)===2?(s=2,a=fa(n,o),o+=a*6+2):(a=0,s=0),r[i]=a*6+8+s,i++;return Ie("saiz",r)}function ng(){return Ie("smhd",new Uint8Array(8))}function Mr(n){let e=[7,[n.length]];return Ie("stsd",le(...e.concat(n)))}function rg(n,e,t){return Ie("tkhd",le(Ce(7),8,Ce(t),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],Se(n),2,Se(e),2))}function gs(n,e,t){return Ie("tenc",le(6,[n,e],t))}function CS(n,e,t){return ze("moov",[n,e,t])}function Lo(n,e,t,r,i,o){let a=ze("stbl",[t,Ie("stts",new Uint8Array(8)),Ie("stsc",new Uint8Array(8)),Ie("stsz",new Uint8Array(12)),Ie("stco",new Uint8Array(8))]),s=Ie("url ",new Uint8Array([0,0,0,1])),d=Wp(s),u=ze("dinf",[d]),c=ze("minf",[r,u,a]),l=Xp(e),f=Zp(n),m=ze("mdia",[f,l,c]),g=rg(i,o,1),I=ze("trak",[g,m]),h=jp(1),y=ze("mvex",[h]),T=Jp(n,1),v=CS(T,y,I),E=Hp("isom",["isom","iso2","iso6","avc1","dash"]);return le(E,v)}var PS=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];function oc(n,e,t){let r=PS.indexOf(e),i;return i=(n&63)<<4,i=(i|r&31)<<4,i=(i|t&31)<<3,Ve(Se(i))}function hs(n,e,t,r,i,o,a){let s=o.length===0?oc(2,i,e):o,d=Qp(1,s),u=(()=>{if(a===void 0){let h=Vp(1,e,t,r,i,d);return Mr([h])}let c=gs(1,8,a),l=ze("schi",[c]),f=ms("cenc",65536),m=ps("mp4a"),g=ze("sinf",[m,f,l]),I=zp(1,e,t,r,i,d,g);return Mr([I])})();return Lo(n,"audio",u,ng(),0,0)}function Is(n,e,t,r,i,o,a,s){let[,d,u]=a.split("00000001");if(d===void 0||u===void 0)throw new Error("Smooth: unsupported codec private data.");let c=st(d),l=st(u),f=$p(c,l,o),m;if(s===void 0){let g=Fp(e,t,r,i,"AVC Coding",24,f);m=Mr([g])}else{let g=gs(1,8,s),I=ze("schi",[g]),h=ms("cenc",65536),y=ps("avc1"),T=ze("sinf",[y,h,I]),v=Kp(e,t,r,i,"AVC Coding",24,f,T);m=Mr([v])}return Lo(n,"video",m,Gp(),e,t)}function ys(n){let e=On(n,3565190898,3392751253,2387879627,2655430559);if(e===void 0)return[];let t=[],r=e[0],i=e[4];for(let o=0;o<i;o++){let a,s;r===1?(s=$e(e,o*16+5),a=$e(e,o*16+5+8)):(s=te(e,o*8+5),a=te(e,o*8+5+4)),t.push({time:s,duration:a})}return t}function bs(n){let e=On(n,1830656773,1121273062,2162299933,2952222642);if(e!==void 0)return{duration:$e(e,12),time:$e(e,4)}}function ac(){return V.browser!==V.BROWSERS.Ie11&&V.browser!==V.BROWSERS.OtherIeOrEdgePreEdgeChromium}function sc(n,e,t,r,i){let o=[n,e,t];return i!==void 0&&o.push(Ie("senc",i),tg(i),eg(r,n,e,t)),ze("traf",o)}function Ss(n,e){let t=Xe(n,1836019558);if(t===null)throw new Error("Smooth: Invalid ISOBMFF given");let r=n.subarray(t[1],t[2]),i=$s(r,1835427940),o=ke(r,1953653094);if(o===null||i===null)throw new Error("Smooth: Invalid ISOBMFF given");let a=Xe(o,1952868452),s=Xe(o,1953658222);if(a===null||s===null)throw new Error("Smooth: Invalid ISOBMFF given");let d=o.subarray(a[0],a[2]),u=o.subarray(s[0],s[2]);d.set([0,0,0,1],a[1]-a[0]+4);let c=qp(e),l=MS(u,s[1]-s[0]),f=On(o,2721664850,1520127764,2722393154,2086964724),m=sc(d,c,l,i,f),g=ze("moof",[i,m]),I=Xe(g,1836019558),h=Xe(m,1953653094),y=Xe(l,1953658222);if(I===null||h===null||y===null)throw new Error("Smooth: Invalid moof, trun or traf generation");let T=I[1]-I[0]+i.length+(h[1]-h[0])+d.length+c.length+(y[1]-y[0])+8,v=t[2]-t[0],E=g.length-v,R=Xe(n,1835295092);if(R===null)throw new Error("Smooth: Invalid ISOBMFF given");if(ac()&&(E===0||E<=-8)){let k=R[1];return g.set(Ce(k),T),n.set(g,t[0]),E<=-8&&n.set(Yp(-E),g.length),n}else{let k=R[1]+E;g.set(Ce(k),T);let A=new Uint8Array(n.length+E),P=n.subarray(0,t[0]),M=n.subarray(t[2],n.length);return A.set(P,0),A.set(g,P.length),A.set(M,P.length+g.length),A}}function MS(n,e){if((n[e+3]&1)>0)return n;let r=new Uint8Array(n.length+4);return r.set(n.subarray(0,e+8),0),r[e+3]=r[e+3]|1,r.set([0,0,0,0],e+8),r.set(n.subarray(e+8,n.length),e+12),td(r)}function Ts(n,e,t,r,i){var m;let o=[],a,s,d;if(i){let g=Qr(n);g!==null?(d=ys(g),s=bs(g)):p.warn("smooth","could not find traf atom")}if(d!==void 0)for(let g of d)o.push({time:g.time,duration:g.duration,timescale:t});if(s!==void 0)return a={time:s.time/t,duration:s.duration/t},{nextSegments:o,chunkInfos:a,scaledSegmentTime:s.time};if(e||!r.complete)return{nextSegments:o,chunkInfos:null,scaledSegmentTime:void 0};let u=r.duration*t,c=Math.min(t*.9,u/4),l=Jr(n),f=((m=r.privateInfos)==null?void 0:m.smoothMediaSegment)!==void 0?r.privateInfos.smoothMediaSegment.time:Math.round(r.time*t);return l!==void 0&&Math.abs(l-u)<=c?a={time:r.time,duration:l/t}:a={time:r.time,duration:r.duration},{nextSegments:o,chunkInfos:a,scaledSegmentTime:f}}function Xn(n){return typeof n=="string"&&n.indexOf("mp4")>=0}async function ig(n,e,t,r,i,o){var m,g;let a=((m=r.cmcdPayload)==null?void 0:m.type)==="headers"?r.cmcdPayload.value:void 0,s=e.segment.range,d;Array.isArray(s)?d=me(oe({},a),{Range:lt(s)}):a!==void 0&&(d=a);let u=((g=r.cmcdPayload)==null?void 0:g.type)==="query"?Ze(n,r.cmcdPayload.value):n,c=await xe({url:u,responseType:"arraybuffer",headers:d,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i,onProgress:t.onProgress});if(!Xn(e.mimeType)||o!==!0)return{resultType:"segment-loaded",resultData:c};let f=new Uint8Array(c.responseData);return yn(f,e.segment.isInit),{resultType:"segment-loaded",resultData:me(oe({},c),{responseData:f})}}var AS=({checkMediaSegmentIntegrity:n,segmentLoader:e})=>(t,r,i,o,a)=>{let{segment:s}=r;if(s.isInit){if(s.privateInfos===void 0||s.privateInfos.smoothInitSegment===void 0)throw new Error("Smooth: Invalid segment format");let d=s.privateInfos.smoothInitSegment,u,{codecPrivateData:c,timescale:l,height:f,width:m,protection:g={keyId:void 0,keySystems:void 0}}=d;if(c===void 0)throw new Error("Smooth: no codec private data.");switch(r.type){case"video":{u=Is(l,m!=null?m:0,f!=null?f:0,72,72,4,c,g.keyId);break}case"audio":{let{channels:I=0,bitsPerSample:h=0,packetSize:y=0,samplingRate:T=0}=d;u=hs(l,I,h,y,T,c,g.keyId);break}default:b.CURRENT_ENV===b.DEV&&ee(!1,"responseData should have been set"),u=new Uint8Array(0)}return Promise.resolve({resultType:"segment-created",resultData:u})}else return t===null?Promise.resolve({resultType:"segment-created",resultData:null}):typeof e!="function"?ig(t,r,a,i,o,n):new Promise((d,u)=>{let c=!1,I={reject:E=>{var P,M;if(c||o.isCancelled())return;c=!0,o.deregister(v);let R=E,k=(P=R==null?void 0:R.message)!=null?P:"Unknown error when fetching a Smooth segment through a custom segmentLoader.",A=new gt(k,(M=R==null?void 0:R.canRetry)!=null?M:!1,R==null?void 0:R.xhr);u(A)},resolve:E=>{if(c||o.isCancelled())return;c=!0,o.deregister(v);let R;E.data instanceof Uint8Array?E.data.buffer instanceof ArrayBuffer?R=E.data:R=E.data.slice():R=E.data,(!Xn(r.mimeType)||n!==!0)&&d({resultType:"segment-loaded",resultData:{responseData:R,size:E.size,requestDuration:E.duration}});let A=R instanceof Uint8Array?R:new Uint8Array(R);yn(A,r.segment.isInit),d({resultType:"segment-loaded",resultData:{responseData:A,size:E.size,requestDuration:E.duration}})},fallback:()=>{c||o.isCancelled()||(c=!0,o.deregister(v),ig(t,r,a,i,o,n).then(d,u))},progress:E=>{c||o.isCancelled()||a.onProgress({duration:E.duration,size:E.size,totalSize:E.totalSize})}},h;r.segment.range!==void 0&&(h=[r.segment.range],r.segment.indexRange!==void 0&&h.push(r.segment.indexRange));let y={isInit:r.segment.isInit,timeout:i.timeout,byteRanges:h,trackType:r.type,url:t,cmcdPayload:i.cmcdPayload},T=e(y,I);o.register(v);function v(E){c||(c=!0,!c&&typeof T=="function"&&T(),u(E))}})},og=AS;function dc(n,e){return n===null?null:e.url===null?n.baseUrl:Un(n.baseUrl,e.url)}function ag(n){let e=Up(n),t=og(n),r={customManifestLoader:n.manifestLoader},o={loadManifest:fo(r,"text",null),parseManifest(d,u){var h;let c=(h=d.url)!=null?h:u.originalUrl,{receivedTime:l,responseData:f}=d,m=xS(f),g=e(m,c,l);return{manifest:new pn(g,{representationFilter:n.representationFilter}),url:c}}},a={loadSegment(d,u,c,l,f){let m=dc(d,u.segment);return t(m,u,c,l,f)},parseSegment(d,u,c){var R,k;let{segment:l}=u,{data:f,isChunked:m}=d;if(f===null)return l.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let g=f instanceof Uint8Array?f:new Uint8Array(f);if(l.isInit){let A=(k=(R=l.privateInfos)==null?void 0:R.smoothInitSegment)==null?void 0:k.timescale;return{segmentType:"init",initializationData:f,initializationDataSize:f.byteLength,initTimescale:A,protectionData:[]}}let I=c!==void 0?Ts(g,m,c,l,u.isLive):null;if(I===null||I.chunkInfos===null||I.scaledSegmentTime===void 0)throw new Error("Smooth Segment without time information");let{nextSegments:h,chunkInfos:y,scaledSegmentTime:T}=I,v=Ss(g,T),E=h.length>0?h:void 0;return{segmentType:"media",chunkData:v,chunkInfos:y,chunkOffset:0,chunkSize:v.length,protectionData:[],predictedSegments:E,appendWindow:[void 0,void 0]}}};return{transportName:"smooth",manifest:o,audio:a,video:a,text:{loadSegment(d,u,c,l,f){var h,y,T,v;let{segment:m}=u,g=dc(d,m);return m.isInit||g===null?Promise.resolve({resultType:"segment-created",resultData:null}):Xn(u.mimeType)?xe({url:((T=c.cmcdPayload)==null?void 0:T.type)==="query"?Ze(g,c.cmcdPayload.value):g,headers:((v=c.cmcdPayload)==null?void 0:v.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"arraybuffer",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(E=>{if(n.checkMediaSegmentIntegrity!==!0)return{resultType:"segment-loaded",resultData:E};let R=new Uint8Array(E.responseData);return yn(R,u.segment.isInit),{resultType:"segment-loaded",resultData:me(oe({},E),{responseData:R})}}):xe({url:((h=c.cmcdPayload)==null?void 0:h.type)==="query"?Ze(g,c.cmcdPayload.value):g,headers:((y=c.cmcdPayload)==null?void 0:y.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"text",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(E=>({resultType:"segment-loaded",resultData:E}))},parseSegment(d,u,c){var U;let{segment:l,language:f,mimeType:m="",codecs:g=""}=u,I=Xn(u.mimeType),{data:h,isChunked:y}=d,T;if(l.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};if(h===null)return{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let v,E=null,R,k,A,P;if(I){let L;typeof h=="string"?L=Re(h):L=h instanceof Uint8Array?h:new Uint8Array(h),T=L.length;let B=c!==void 0?Ts(L,y,c,l,u.isLive):null;v=B==null?void 0:B.nextSegments,E=(U=B==null?void 0:B.chunkInfos)!=null?U:null,E===null?y?p.warn("smooth","Unavailable time data for current text track."):(R=l.time,k=l.end):(R=E.time,k=E.duration!==void 0?E.time+E.duration:l.end);let C=g.toLowerCase();if(m==="application/ttml+xml+mp4"||C==="stpp"||C==="stpp.ttml"||C==="stpp.ttml.im1t")P="ttml";else if(C==="wvtt")P="vtt";else throw new Error(`could not find a text-track parser for the type ${m}`);let w=Dn(L);A=w===null?"":he(w)}else{R=l.time,k=l.end;let L;if(typeof h!="string"){let B=h instanceof Uint8Array?h:new Uint8Array(h);T=B.length,L=he(B)}else L=h;switch(m){case"application/x-sami":case"application/smil":P="sami";break;case"application/ttml+xml":P="ttml";break;case"text/vtt":P="vtt";break}if(P===void 0)if(g.toLowerCase()==="srt")P="srt";else throw new Error(`could not find a text-track parser for the type ${m}`);A=L}let M=Array.isArray(v)&&v.length>0?v:void 0,N=R!=null?R:0;return{segmentType:"media",chunkData:{type:P,data:A,start:R,end:k,initTimescale:c!=null?c:null,language:f},chunkSize:T,chunkInfos:E,chunkOffset:N,protectionData:[],predictedSegments:M,appendWindow:[void 0,void 0]}}},thumbnails:{loadThumbnail:()=>Promise.reject(new Error("Thumbnail tracks aren't implemented with smooth")),parseThumbnail:()=>{throw new Error("Thumbnail tracks aren't implemented with smooth")}}}}function xS(n){if(n instanceof ArrayBuffer)return he(new Uint8Array(n));if(typeof n=="string")return n;if(!_(Z.Document)&&n instanceof Z.Document)return n.documentElement.outerHTML;throw new Error("Smooth Manifest Parser: Unrecognized Manifest format")}var sg=ag;function uc(n){n.transports.smooth===void 0&&(n.transports.smooth=sg),n.monothread={init:Vn,coreInterface:hr,initializeCoreEntry:Ka}}function dg(){if(V.browser!==V.BROWSERS.Firefox)return p.warn("utils","getFirefoxVersion: Can't access Firefox version. Not a firefox browser."),null;let n=navigator.userAgent,e=/Firefox\/([0-9]+)\./.exec(n);if(e===null)return-1;let t=parseInt(e[1],10);return isNaN(t)?-1:t}function lc(){if(V.browser!==V.BROWSERS.Firefox)return!0;let n=dg();if(n===null||n<67)return!0;let e=HTMLVideoElement==null?void 0:HTMLVideoElement.prototype;return(e==null?void 0:e.requirePictureInPicture)!==void 0}function No(n){let e=n;if(typeof e.getStartDate=="function"){let t=e.getStartDate();if(typeof t=="object"&&t!==null){let r=+t;if(!isNaN(r))return r/1e3}else if(typeof t=="number"&&!isNaN(t))return t}}function cc(){return V.device===V.DEVICES.PlayStation4&&typeof Worker=="object"||typeof Worker=="function"}var En=class n extends Error{constructor(e,t){super(mt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="WorkerInitializationError",this.type="WORKER_INITIALIZATION_ERROR",this.code=e}};var wS=["canplay","ended","play","pause","seeking","seeked","loadedmetadata","ratechange"],Bo=class{constructor(e,t){this._internalSeeksIncoming=[],this._mediaElement=e,this._withMediaSource=t.withMediaSource,this._lowLatencyMode=t.lowLatencyMode,this._canceller=new D,this._observationRef=this._createSharedReference(),this._expectedSeekingPosition=null,this._pendingSeek=null,this._isSeekBlocked=!1;let r=()=>{if(this._pendingSeek!==null&&!this._isSeekBlocked){let{position:i,isInternal:o}=this._pendingSeek;this._pendingSeek=null,this._actuallySetCurrentTime(i,o)}};e.addEventListener("loadedmetadata",r),this._canceller.signal.register(()=>{e.removeEventListener("loadedmetadata",r)})}stop(){this._canceller.cancel()}getCurrentTime(){return this._mediaElement.currentTime}getPlaybackRate(){return this._mediaElement.playbackRate}getIsPaused(){return this._mediaElement.paused}blockSeeking(){this._isSeekBlocked=!0}unblockSeeking(){if(this._isSeekBlocked&&(this._isSeekBlocked=!1,this._pendingSeek!==null&&this._mediaElement.readyState>=1)){let{position:e,isInternal:t}=this._pendingSeek;this._pendingSeek=null,this._actuallySetCurrentTime(e,t)}}isSeekingBlocked(){return this._isSeekBlocked}getPendingSeekInformation(){return this._pendingSeek}setCurrentTime(e,t=!0){!this._isSeekBlocked&&this._mediaElement.readyState>=1?this._actuallySetCurrentTime(e,t):(this._pendingSeek={position:e,isInternal:t},this._internalSeeksIncoming=[],this._isSeekBlocked||this._generateObservationForEvent("manual"))}setPlaybackRate(e){this._mediaElement.playbackRate=e}getReadyState(){return this._mediaElement.readyState}getReference(){return this._observationRef}listen(e,t){if(this._canceller.isUsed()||t.clearSignal.isCancelled())return ae;this._observationRef.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return lr(this,e,this._canceller.signal)}_actuallySetCurrentTime(e,t){p.info("media","Actually seeking.",{time:e,isInternal:t}),t&&this._internalSeeksIncoming.push(e),this._mediaElement.currentTime=e}_createSharedReference(){if(this._observationRef!==void 0)return this._observationRef;let{SAMPLING_INTERVAL_MEDIASOURCE:e,SAMPLING_INTERVAL_LOW_LATENCY:t,SAMPLING_INTERVAL_NO_MEDIASOURCE:r}=O.getCurrent(),i=new W(this._getCurrentObservation("init"),this._canceller.signal),o;this._lowLatencyMode?o=t:this._withMediaSource?o=e:o=r;let a=()=>{this._generateObservationForEvent("timeupdate")},s=setInterval(a,o);return wS.map(u=>{let c=()=>{d(),this._generateObservationForEvent(u)};this._mediaElement.addEventListener(u,c),this._canceller.signal.register(()=>{this._mediaElement.removeEventListener(u,c)})}),this._canceller.signal.register(()=>{clearInterval(s),i.finish()}),i;function d(){clearInterval(s),s=setInterval(a,o)}}_getCurrentObservation(e){var v,E,R,k;let t=e,r=this._observationRef===void 0?BS(this._mediaElement):this._observationRef.getValue(),i=!1,o=(E=(v=this._pendingSeek)==null?void 0:v.position)!=null?E:null,a=lg(this._mediaElement),{buffered:s,readyState:d,position:u,seeking:c}=a;if(t==="seeking")if(this._internalSeeksIncoming.length>0){i=!0,t="internal-seeking";let A=this._internalSeeksIncoming.shift();this._expectedSeekingPosition=Fn()?Math.max(u,A!=null?A:0):u}else this._expectedSeekingPosition=u;else c?this._expectedSeekingPosition=Math.max(u,(R=this._expectedSeekingPosition)!=null?R:0):Fn()&&this._expectedSeekingPosition!==null&&u<this._expectedSeekingPosition?o=this._expectedSeekingPosition:this._expectedSeekingPosition=null;c&&r.seeking===1&&e!=="seeking"&&(i=!0);let l=(k=this._expectedSeekingPosition)!=null?k:u,f,m;!this._withMediaSource&&s.length===0&&d>=3?(f=void 0,m=void 0):(f=_d(s,l),m=f!==null?f.end-l:1/0);let g=OS(l,f,a.ended,a.duration,this._lowLatencyMode),I=DS({previousObservation:r,currentObservation:a,basePosition:l,observationEvent:t,lowLatencyMode:this._lowLatencyMode,withMediaSource:this._withMediaSource,bufferGap:m,fullyLoaded:g}),h=LS(r,a,t,m),y;i?y=1:c?y=2:y=0;let T=G({},a,{position:new Bt(a.position,o),event:t,seeking:y,rebuffering:I,freezing:h,bufferGap:m,currentRange:f,fullyLoaded:g});return p.hasLevel("DEBUG")&&p.debug("media","Current media element state tick.",{evt:T.event,position:T.position.getPolled(),seeking:T.seeking,internalSeek:i,rebuffering:T.rebuffering!==null,freezing:T.freezing!==null,ended:T.ended,paused:T.paused,playbackRate:T.playbackRate,readyState:T.readyState,pendingPosition:o}),T}_generateObservationForEvent(e){let t=this._getCurrentObservation(e);p.hasLevel("DEBUG")&&p.debug("media",`current playback timeline:
|
|
20
|
+
`+NS(t.buffered,t.position.getPolled()),`
|
|
21
|
+
${e}`),this._observationRef.setValue(t)}};function ug(n,e){if(n===null)return 0;let t=e?"LOW_LATENCY":"DEFAULT",{RESUME_GAP_AFTER_SEEKING:r,RESUME_GAP_AFTER_NOT_ENOUGH_DATA:i,RESUME_GAP_AFTER_BUFFERING:o}=O.getCurrent();switch(n.reason){case"seeking":return r[t];case"not-ready":return i[t];case"buffering":return o[t]}}function OS(n,e,t,r,i){let{REBUFFERING_GAP:o}=O.getCurrent(),a=i?"LOW_LATENCY":"DEFAULT";return e===void 0?t&&Math.abs(r-n)<=o[a]:e!==null&&r-e.end<=o[a]}function lg(n){let{buffered:e,currentTime:t,duration:r,ended:i,paused:o,playbackRate:a,readyState:s,seeking:d}=n;return{buffered:e,position:t,duration:r,ended:i,paused:o,playbackRate:a,readyState:s,seeking:d}}function DS({previousObservation:n,currentObservation:e,basePosition:t,observationEvent:r,withMediaSource:i,lowLatencyMode:o,bufferGap:a,fullyLoaded:s}){let{REBUFFERING_GAP:d}=O.getCurrent(),{position:u,paused:c,readyState:l,ended:f}=e,{rebuffering:m,event:g,position:I}=n,h=m===null&&!(s||f),y=null,T,v,E=o?d.LOW_LATENCY:d.DEFAULT;if(i){if(h)a===1/0?(T=!0,y=t):a===void 0?l<3&&(T=!0,y=void 0):a<=E&&(T=!0,y=t+a);else if(m!==null){let R=ug(m,o);T!==!0&&m!==null&&l>1&&(s||f||a!==void 0&&isFinite(a)&&a>R)||a===void 0&&l>=3?v=!0:a===void 0?y=void 0:a===1/0?y=t:a<=R&&(y=t+a)}}else h&&(!c&&r==="timeupdate"&&g==="timeupdate"&&u===I.getPolled()||r==="seeking"&&(a===1/0||a===void 0&&l<3))?T=!0:m!==null&&(r!=="seeking"&&u!==I.getPolled()||r==="canplay"||a===void 0&&l>=3||a!==void 0&&a<1/0&&(a>ug(m,o)||s||f))&&(v=!0);if(v===!0)return null;if(T===!0||m!==null){let R;return r==="seeking"||m!==null&&m.reason==="seeking"||e.seeking?R="seeking":l===1?R="not-ready":R="buffering",m!==null&&m.reason===R?{reason:m.reason,timestamp:m.timestamp,position:y}:{reason:R,timestamp:z(),position:y}}return null}function LS(n,e,t,r){let{MINIMUM_BUFFER_AMOUNT_BEFORE_FREEZING:i}=O.getCurrent();return n.freezing!==null?e.ended||e.paused||e.readyState===0||e.playbackRate===0||n.position.getPolled()!==e.position?null:n.freezing:t==="timeupdate"&&r!==void 0&&r>i&&!e.ended&&!e.paused&&e.readyState>=1&&e.playbackRate!==0&&e.position===n.position.getPolled()?{timestamp:z()}:null}function NS(n,e){let t="",r="";for(let i=0;i<n.length;i++){let o=n.start(i),a=n.end(i),s=o.toFixed(2),d=a.toFixed(2),u=(a-o).toFixed(2),c=`${s}|==${u}==|${d}`;if(t+=c,r.length===0&&a>e){let l=t.length-Math.floor(c.length/2);r=" ".repeat(l)+`^${e}`}if(i<n.length-1){let l=n.start(i+1),m=` ~${(l-a).toFixed(2)}~ `;if(t+=m,r.length===0&&e<l){let g=t.length-Math.floor(m.length/2);r=" ".repeat(g)+`^${e}`}}}return r.length===0&&(r=" ".repeat(t.length)+`^${e}`),t+`
|
|
22
|
+
`+r}function BS(n){let e=lg(n);return G(e,{rebuffering:null,event:"init",seeking:0,position:new Bt(e.position,null),freezing:null,bufferGap:0,currentRange:null,fullyLoaded:!1})}async function fc(n,e){let{time:t,container:r}=e;if(n===null||n.fetchThumbnailDataCallback===null||n.manifest===null)return Promise.reject(new _t("NO_CONTENT","Cannot get thumbnail: no content loaded"));let{thumbnailRequestsInfo:i,currentContentCanceller:o}=n,a=new D,s=a.linkToSignal(o.signal),d,u=i.pendingRequests.get(r);u==null||u.cancel(),i.pendingRequests.set(r,a);let c=()=>{s(),a.cancel(),i.pendingRequests.delete(r),setTimeout(()=>{d!==void 0&&URL.revokeObjectURL(d)},0)};try{let f=tr(n.manifest,t);if(f===void 0)throw new _t("NO_THUMBNAIL","Wanted Period not found.");let m=f.thumbnailTracks,g=e.thumbnailTrackId!==void 0?q(m,k=>k.id===e.thumbnailTrackId):m[0];if(g===void 0)throw e.thumbnailTrackId!==void 0?new _t("NO_THUMBNAIL","Given `thumbnailTrackId` not found"):new _t("NO_THUMBNAIL","Wanted Period has no thumbnail track.");let{lastResponse:I}=i,h;if(I!==null&&I.thumbnailTrackId===g.id&&I.periodId===f.id){let k=I.response.thumbnails;k.length>0&&t>=k[0].start&&t<k[k.length-1].end&&(h=I.response)}if(h===void 0&&(h=await n.fetchThumbnailDataCallback(f.id,g.id,t),i.lastResponse={response:h,periodId:f.id,thumbnailTrackId:g.id}),a.signal.cancellationError!==null)throw a.signal.cancellationError;let y=document.createElement("canvas"),T=y.getContext("2d");if(T===null)throw new _t("RENDERING","Cannot display thumbnail: cannot create canvas context");let v=Te(h.thumbnails,k=>k.start<=t&&k.end>t);if(v<0)throw new Error("Cannot display thumbnail: time not found in fetched data");let E=new Image,R=new Blob([h.data],{type:h.mimeType});return d=URL.createObjectURL(R),E.src=d,y.height=h.thumbnails[v].height,y.width=h.thumbnails[v].width,new Promise((k,A)=>{E.onload=()=>{if(a.signal.cancellationError!==null){A(a.signal.cancellationError),c();return}try{T.drawImage(E,h.thumbnails[v].offsetX,h.thumbnails[v].offsetY,h.thumbnails[v].width,h.thumbnails[v].height,0,0,h.thumbnails[v].width,h.thumbnails[v].height),y.style.width="100%",y.style.height="100%",y.className="__rx-thumbnail__",l(),r.appendChild(y),k()}catch(P){A(new _t("RENDERING","Could not draw the image in a canvas:"+(P instanceof Error?P.toString():"Unknown Error")))}c()},E.onerror=()=>{if(a.signal.cancellationError!==null){A(a.signal.cancellationError),c();return}e.keepPreviousThumbnailOnError!==!0&&l(),A(new _t("RENDERING","Could not load the corresponding image in the DOM")),c()}})}catch(f){if(e.keepPreviousThumbnailOnError!==!0&&l(),f!==null&&f===a.signal.cancellationError)throw new _t("ABORTED","Thumbnail rendering has been aborted");let m=Ae(f,{defaultCode:"NONE",defaultReason:"Unknown error"}),g;throw m.type==="NETWORK_ERROR"?g=new _t("LOADING",m.message):g=new _t("NOT_FOUND",m.message),c(),g}function l(){for(let f=r.children.length-1;f>=0;f--){let m=r.children[f];m.className==="__rx-thumbnail__"&&r.removeChild(m)}}}var _t=class n extends Error{constructor(e,t){super(mt(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="ThumbnailRenderingError",this.code=e}};var Uo=class extends se{constructor(e){super(),this._canceller=new D,this._adaptationRef=e,this._updateToken=!1,this._lastEmitted=void 0,this.refresh=ae}hasSetTrack(){return this._adaptationRef.getValue()!==void 0}updateTrack(e){if(this._updateToken=!0,e===null){if(this._lastEmitted===null)return;this._updateToken=!1,this._canceller.cancel(),this._canceller=new D,this._lastEmitted=null,this._adaptationRef.setValue(null);return}let{adaptation:t,switchingMode:r,relativeResumingPosition:i}=e;this._canceller.cancel(),this._canceller=new D;let o=this._constructLockedRepresentationsReference(e);this._updateToken&&(this._lastEmitted={adaptation:t,switchingMode:r,lockedRepresentations:null},this._updateToken=!1,this._adaptationRef.setValue({adaptationId:t.id,switchingMode:r,representations:o,relativeResumingPosition:i}))}_constructLockedRepresentationsReference(e){let t=new W({representationIds:[],switchingMode:"lazy"}),r=this;return this.refresh=i,this._canceller.signal.register(o),e.lockedRepresentations.onUpdate(i,{clearSignal:this._canceller.signal,emitCurrentValue:!1}),i(),t;function i(){let a=e.lockedRepresentations.getValue(),s,d;if(a===null)d=e.adaptation.representations.filter(l=>wt(l)===!0),s="lazy";else{let{representationIds:l}=a;if(s=a.switchingMode,d=e.adaptation.representations.filter(m=>J(l,m.id)).filter(m=>wt(m)===!0),d.length===0){r.trigger("noPlayableLockedRepresentation",null);return}}if(d.length<=0){r.trigger("noPlayableRepresentation",null);return}let u=t.getValue(),c=d.map(l=>l.id).slice().sort();if(c.length!==u.representationIds.length){t.setValue({representationIds:c,switchingMode:s});return}for(let l=0;l<c.length;l++)if(u.representationIds[l]!==c[l]){t.setValue({representationIds:c,switchingMode:s});return}}function o(){r.refresh=ae}}dispose(){this.removeEventListener(),this._canceller.cancel(),this._adaptationRef.finish()}};var Fo=class extends se{constructor(e){var t;super(),this._storedPeriodInfo=[],this._isDisposed=!1,this._cachedPeriodInfo=new WeakMap,this._isTrickModeTrackEnabled=e.preferTrickModeTracks,this._defaultAudioTrackSwitchingMode=(t=e.defaultAudioTrackSwitchingMode)!=null?t:O.getCurrent().DEFAULT_AUDIO_TRACK_SWITCHING_MODE,this.onTracksNotPlayableForType=e.onTracksNotPlayableForType}getAvailablePeriods(){return this._storedPeriodInfo.reduce((e,t)=>(t.isPeriodAdvertised&&e.push(tn(t.period)),e),[])}onManifestCodecSupportUpdate(){this._selectInitialTrackIfNeeded()}checkPeriodHasSupportedTrack(e,t){var d,u;let r=e.adaptations[t],i=[...(d=e.adaptations.audio)!=null?d:[],...(u=e.adaptations.video)!=null?u:[]];if(!(r!==void 0&&r.length>0))return;let a=r.every(c=>c.supportStatus.hasSupportedCodec===!1),s=i.every(c=>c.supportStatus.hasSupportedCodec===!1);if(a){let c=new re("MANIFEST_INCOMPATIBLE_CODECS_ERROR","No supported "+t+" adaptations",{tracks:void 0});if(s){if(this.trigger("error",c),this._isDisposed)return;this.dispose();return}else if(this.onTracksNotPlayableForType[t]==="continue")this.trigger("warning",c);else{if(this.trigger("error",c),this._isDisposed)return;this.dispose();return}}}onManifestUpdate(e){var o,a,s;let{periods:t}=e;if(b.CURRENT_ENV===b.DEV)for(let d=1;d<t.length;d++)ee(t[d-1].start<=t[d].start);let r=[];for(let d of t)if(["audio","video"].forEach(u=>{this.checkPeriodHasSupportedTrack(d,u)}),this._isDisposed)return;let i=0;for(let d=0;d<this._storedPeriodInfo.length;d++){let u=this._storedPeriodInfo[d].period,c=t[i];if(c===void 0)for(let l=this._storedPeriodInfo.length-1;l>=d;l--)this._storedPeriodInfo[l].inManifest=!1,mc(this._storedPeriodInfo[l])&&this._removePeriodObject(l);else if(u===c)i++,this.resetSelectedTrackIfNotAvailableAnymore(this._storedPeriodInfo[d],c,"video"),this.resetSelectedTrackIfNotAvailableAnymore(this._storedPeriodInfo[d],c,"audio"),this.resetSelectedTrackIfNotAvailableAnymore(this._storedPeriodInfo[d],c,"text");else if(u.start<=c.start)this._storedPeriodInfo[d].inManifest=!1,mc(this._storedPeriodInfo[d])&&(this._removePeriodObject(d),d--);else{let l=pc(c,!0);this._storedPeriodInfo.splice(d,0,l),r.push(l),i++}}if(i<t.length){let d=t.slice(i).map(u=>pc(u,!0));this._storedPeriodInfo.push(...d),r.push(...d)}for(let d of this._storedPeriodInfo)(o=d.audio.dispatcher)==null||o.refresh(),(a=d.video.dispatcher)==null||a.refresh(),(s=d.text.dispatcher)==null||s.refresh()}onDecipherabilityUpdates(){var e,t,r;for(let i of this._storedPeriodInfo)(e=i.audio.dispatcher)==null||e.refresh(),(t=i.video.dispatcher)==null||t.refresh(),(r=i.text.dispatcher)==null||r.refresh()}resetSelectedTrackIfNotAvailableAnymore(e,t,r){var d;let i=e[r].storedSettings;if(_(i))return;let o=Vt(t,r);if(o.some(u=>u.id===i.adaptation.id)||(p.warn("Track",`Chosen ${r} Adaptation not available anymore`),r==="video"?e.video.storedSettings=this.getDefaultStoredSettingsForAdaptation(o,"video"):r==="audio"?e.audio.storedSettings=this.getDefaultStoredSettingsForAdaptation(o,"audio"):r==="text"&&(e.text.storedSettings=this.getDefaultStoredSettingsForAdaptation(o,"text")),this.trigger("trackUpdate",{period:tn(t),trackType:r,reason:"missing"}),this._isDisposed))return;let s=Kt(this._storedPeriodInfo,e.period.id);s!==void 0&&s.isPeriodAdvertised&&s[r].storedSettings===null&&((d=s[r].dispatcher)==null||d.updateTrack(null))}getDefaultStoredSettingsForAdaptation(e,t){let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:r}=O.getCurrent();if(t==="text"||e.length===0)return null;switch(t){case"text":return null;case"video":{let i=e[0],o=_s(i,this._isTrickModeTrackEnabled),a=new W(null);return{adaptationBase:i,adaptation:o,switchingMode:r,lockedRepresentations:a}}case"audio":return{adaptation:e[0],switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new W(null)};default:we(t)}}addTrackReference(e,t,r){p.debug("Track","Adding Track Reference",{bufferType:e,periodId:t.id});let i=Kt(this._storedPeriodInfo,t.id);if(i===void 0){i=pc(t,!1);let s=!1;for(let d=0;d<this._storedPeriodInfo.length;d++)this._storedPeriodInfo[d].period.start>t.start&&(this._storedPeriodInfo.splice(d,0,i),s=!0);s||this._storedPeriodInfo.push(i)}i[e].dispatcher!==null&&(p.error("Track","Subject already added for type and Period",{bufferType:e,periodId:t.id}),i[e].dispatcher.dispose());let o=new Uo(r);if(i[e].dispatcher=o,o.addEventListener("noPlayableRepresentation",()=>{this.handleMissingOrUnplayableTrack(t,e,!1)}),o.addEventListener("noPlayableLockedRepresentation",()=>{i!==void 0&&(this.unlockVideoRepresentations(i),this.trigger("brokenRepresentationsLock",{period:{id:t.id,start:t.start,end:t.end},trackType:e}))}),this._selectInitialTrackIfNeeded(),this._shouldAdvertisePeriod(i)&&(i.isPeriodAdvertised=!0,this.trigger("newAvailablePeriods",[{id:t.id,start:t.start,end:t.end}]),this._isDisposed))return;let a=["audio","video","text"];for(let s of a){let d=i[s];if(i.isPeriodAdvertised&&d.dispatcher!==null&&!d.dispatcher.hasSetTrack()&&d.storedSettings!==void 0&&d.dispatcher.updateTrack(d.storedSettings),this._isDisposed)return}}throwIfTracksAreNotSetForPeriod(e){let t=Kt(this._storedPeriodInfo,e.id);if(t!==void 0&&["audio","video"].every(i=>t[i].storedSettings===null)){let i=new re("NO_AUDIO_VIDEO_TRACKS","No audio and no video tracks are set.");this.trigger("error",i),this.dispose()}}handleMissingOrUnplayableTrack(e,t,r){var u,c,l,f;let{fallbackTrack:i,noSourceMedia:o}=US(e,t),a=(u=Kt(this._storedPeriodInfo,e.id))==null?void 0:u[t];if(a===void 0){p.warn("Track","Could not find period",{periodId:e.id});return}let s=a.storedSettings,d=()=>a.storedSettings!==s;if(i!==null){let m;t==="audio"?m=this._defaultAudioTrackSwitchingMode:t==="text"?m="direct":m="reload";let g={adaptation:i,switchingMode:m,lockedRepresentations:new W(null)};if(a.storedSettings=g,r||this.trigger("trackUpdate",{period:tn(e),trackType:t,reason:"no-playable-representation"}),this._isDisposed)return;a.storedSettings===g&&((c=a.dispatcher)==null||c.updateTrack(g))}else if(i===null&&!o){if(this.trigger("noPlayableTrack",{trackType:t,period:{id:e.id,start:e.start,end:e.end}}),this._isDisposed)return;let m=this.onTracksNotPlayableForType[t];if(!d()){if(m==="continue")p.warn("Track",`No playable ${t}, continuing without ${t}`),a.storedSettings=null,r||this.trigger("trackUpdate",{period:tn(e),trackType:t,reason:"no-playable-representation"}),a.storedSettings!==null||this._isDisposed||(l=a.dispatcher)==null||l.updateTrack(null);else if(m==="error"){let g=new re("NO_PLAYABLE_REPRESENTATION",`No ${t} Representation can be played`,{tracks:void 0});this.trigger("error",g)}}}else i===null&&o&&(p.debug("Track",`The period does not have adaptation for ${t} there is no track to choose`),a.storedSettings=null,r||this.trigger("trackUpdate",{period:tn(e),trackType:t,reason:"no-playable-representation"}),a.storedSettings!==null||this._isDisposed||(f=a.dispatcher)==null||f.updateTrack(null));this._isDisposed||t!=="text"&&this.throwIfTracksAreNotSetForPeriod(e)}removeTrackReference(e,t){p.debug("Track","Removing Track Reference",{bufferType:e,periodId:t});let r;for(let a=0;a<this._storedPeriodInfo.length;a++)if(this._storedPeriodInfo[a].period.id===t){r=a;break}if(r===void 0){p.warn("Track","type not found for period",{bufferType:e,periodId:t});return}let i=this._storedPeriodInfo[r],o=i[e];if((o==null?void 0:o.dispatcher)===null){p.warn("Track","TrackDispatcher already removed for type and Period",{bufferType:e,periodId:t});return}o.dispatcher.dispose(),o.dispatcher=null,mc(i)&&this._removePeriodObject(r)}getPeriodObjectFromPeriod(e){let t=Kt(this._storedPeriodInfo,e.id);return t===void 0&&e!==void 0?this._cachedPeriodInfo.get(e):t}getPeriodObjectFromId(e){return Kt(this._storedPeriodInfo,e)}disableVideoTrickModeTracks(){this._isTrickModeTrackEnabled&&(this._isTrickModeTrackEnabled=!1,this._resetVideoTrackChoices("trickmode-disabled"))}enableVideoTrickModeTracks(){this._isTrickModeTrackEnabled||(this._isTrickModeTrackEnabled=!0,this._resetVideoTrackChoices("trickmode-enabled"))}resetPeriodObjects(){var e,t,r;p.debug("Track","Resetting Period Objects");for(let i=this._storedPeriodInfo.length-1;i>=0;i--){let o=this._storedPeriodInfo[i];(e=o.audio.dispatcher)==null||e.dispose(),o.audio.dispatcher=null,(t=o.video.dispatcher)==null||t.dispose(),o.video.dispatcher=null,(r=o.text.dispatcher)==null||r.dispose(),o.text.dispatcher=null,o.inManifest||this._removePeriodObject(i)}}isTrickModeEnabled(){return this._isTrickModeTrackEnabled}setAudioTrack(e){let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;return this._setAudioOrTextTrack({bufferType:"audio",periodRef:t,trackId:r,switchingMode:i!=null?i:this._defaultAudioTrackSwitchingMode,lockedRepresentations:o,relativeResumingPosition:a})}setTextTrack(e,t){return this._setAudioOrTextTrack({bufferType:"text",periodRef:e,trackId:t,switchingMode:"direct",lockedRepresentations:null,relativeResumingPosition:void 0})}_setAudioOrTextTrack({bufferType:e,periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}){var m,g;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=q((m=s.adaptations[e])!=null?m:[],({id:I,supportStatus:h})=>h.hasSupportedCodec!==!1&&h.isDecipherable!==!1&&I===r);if(d===void 0)throw new Error(`Wanted ${e} track not found.`);let u=t[e],c;if(o===null)c=new W(null);else{let I=this._getRepresentationsToLock(d,o),h=e==="audio"?this._defaultAudioTrackSwitchingMode:"direct";c=new W({representationIds:I,switchingMode:h})}let l={adaptation:d,switchingMode:i,lockedRepresentations:c,relativeResumingPosition:a};if(u.storedSettings=l,this.trigger("trackUpdate",{period:tn(s),trackType:e,reason:"manual"}),this._isDisposed)return;let f=Kt(this._storedPeriodInfo,s.id);f!==void 0&&f[e].storedSettings===l&&((g=f[e].dispatcher)==null||g.updateTrack(l))}setVideoTrack(e){var I,h;let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=q((I=s.adaptations.video)!=null?I:[],({id:y,supportStatus:T})=>T.isDecipherable!==!1&&T.hasSupportedCodec!==!1&&y===r);if(d===void 0)throw new Error("Wanted video track not found.");let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:u}=O.getCurrent(),c=t.video,l=_s(d,this._isTrickModeTrackEnabled),f;if(o===null)f=new W(null);else{let y=this._getRepresentationsToLock(d,o),T=u;f=new W({representationIds:y,switchingMode:T})}let m={adaptationBase:d,switchingMode:i!=null?i:u,adaptation:l,relativeResumingPosition:a,lockedRepresentations:f};if(c.storedSettings=m,this.trigger("trackUpdate",{period:tn(s),trackType:"video",reason:"manual"}),this._isDisposed)return;let g=Kt(this._storedPeriodInfo,s.id);g!==void 0&&g.video.storedSettings===m&&((h=g.video.dispatcher)==null||h.updateTrack(m))}disableTrack(e,t){var o,a;if(!e.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let r=e[t];if(r.storedSettings===null||(t!=="text"&&((o=e[t].storedSettings)==null||o.lockedRepresentations.finish()),r.storedSettings=null,this.trigger("trackUpdate",{period:tn(e.period),trackType:t,reason:"manual"}),this._isDisposed))return;let i=Kt(this._storedPeriodInfo,e.period.id);if(i!==void 0&&i[t].storedSettings===null&&((a=i[t].dispatcher)==null||a.updateTrack(null)),i!==void 0&&["audio","video"].every(d=>i[d].storedSettings===null)){let d=new re("NO_AUDIO_VIDEO_TRACKS","No audio and no video tracks are set.");this.trigger("error",d),this.dispose();return}}getChosenAudioTrack(e,t){return _(e.audio.storedSettings)?null:Yo(e.audio.storedSettings.adaptation,t)}getChosenTextTrack(e){return _(e.text.storedSettings)?null:Qo(e.text.storedSettings.adaptation)}getChosenVideoTrack(e,t){return _(e.video.storedSettings)?null:$o(e.video.storedSettings.adaptation,t)}getAvailableAudioTracks(e,t){let r=e.audio.storedSettings,i=_(r)?null:r.adaptation.id;return Vt(e.period,"audio").map(a=>{let s=i===null?!1:i===a.id;return G(Yo(a,t),{active:s})})}getAvailableTextTracks(e){let t=e.text.storedSettings,r=_(t)?null:t.adaptation.id;return Vt(e.period,"text").map(o=>{let a=r===null?!1:r===o.id;return G(Qo(o),{active:a})})}getAvailableVideoTracks(e,t){let r=e.video.storedSettings,i=_(r)?void 0:r.adaptation.id;return Vt(e.period,"video").map(a=>{let s=i===null?!1:i===a.id,d=$o(a,t),u=d.trickModeTracks!==void 0?d.trickModeTracks.map(l=>{let f=i===null?!1:i===l.id;return G(l,{active:f})}):[],c=G(d,{active:s});return u!==void 0&&(c.trickModeTracks=u),c})}getLockedAudioRepresentations(e){let{storedSettings:t}=e.audio;if(_(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}getLockedVideoRepresentations(e){let{storedSettings:t}=e.video;if(_(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}lockAudioRepresentations(e,t){var s;let{storedSettings:r}=e.audio;if(_(r))return;let{DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:i}=O.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}lockVideoRepresentations(e,t){var s;let{storedSettings:r}=e.video;if(_(r))return;let{DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:i}=O.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}unlockAudioRepresentations(e){let{storedSettings:t}=e.audio;_(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}unlockVideoRepresentations(e){let{storedSettings:t}=e.video;_(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}dispose(){for(this._isDisposed=!0;;){let e=this._storedPeriodInfo.pop();if(e===void 0)return;e.isRemoved=!0}}_resetVideoTrackChoices(e){var r;for(let i=0;i<this._storedPeriodInfo.length;i++){let o=this._storedPeriodInfo[i];if(!_(o.video.storedSettings)){let a=o.video.storedSettings.adaptationBase;if(a!==null){let s=_s(a,this._isTrickModeTrackEnabled);o.video.storedSettings.adaptationBase=a,o.video.storedSettings.adaptation=s}}}let t=this._storedPeriodInfo.slice();for(let i=0;i<t.length;i++){let o=t[i].period,s=t[i].video.storedSettings;if(s!==void 0){if(this.trigger("trackUpdate",{period:tn(o),trackType:"video",reason:e}),this._isDisposed)return;let d=Kt(this._storedPeriodInfo,o.id);d!==void 0&&d.isPeriodAdvertised&&d.video.storedSettings===s&&((r=d.video.dispatcher)==null||r.updateTrack(s))}}}_removePeriodObject(e){ee(e<this._storedPeriodInfo.length);let t=this._storedPeriodInfo[e];this._storedPeriodInfo[e].isRemoved=!0,this._storedPeriodInfo.splice(e,1),this._cachedPeriodInfo.set(t.period,t)}_getRepresentationsToLock(e,t){let r=t.reduce((i,o)=>{let a=q(e.representations,s=>s.id===o);return a===void 0?p.warn("Track","Wanted locked Representation not found."):i.push(a.id),i},[]);if(r.length===0)throw new Error("Cannot lock Representations: None of the given Representation id are found");return r}_selectInitialTrackIfNeeded(){var i,o,a,s;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:e}=O.getCurrent(),t=[],r=[];for(let d of this._storedPeriodInfo){let{period:u}=d;if(d.audio.storedSettings!==void 0&&d.video.storedSettings!==void 0&&d.text.storedSettings!==void 0)continue;let c=[...(i=u.adaptations.audio)!=null?i:[],...(o=u.adaptations.video)!=null?o:[]],l=c.every(h=>h.supportStatus.hasCodecWithUndefinedSupport);if(c.length>0&&l)continue;let f=Vt(u,"audio")[0];if(f===void 0){if(d.audio.storedSettings=null,this.handleMissingOrUnplayableTrack(u,"audio",!0),this._isDisposed)return}else d.audio.storedSettings={adaptation:f,switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new W(null)};let m=Vt(u,"video")[0];if(m===void 0){if(d.video.storedSettings=null,this.handleMissingOrUnplayableTrack(u,"video",!0),this._isDisposed)return}else{let h=_s(m,this._isTrickModeTrackEnabled);d.video.storedSettings={adaptation:h,adaptationBase:m,switchingMode:e,lockedRepresentations:new W(null)}}let g=null,I=((a=u.adaptations.text)!=null?a:[]).filter(h=>h.isForcedSubtitles===!0);if(I.length>0){if(f!=null){let h=q(I,y=>y.normalizedLanguage===f.normalizedLanguage);h!==void 0&&(g=h)}g===null&&(g=(s=q(I,h=>h.normalizedLanguage===void 0))!=null?s:null)}d.text.storedSettings=g===null?null:{adaptation:g,switchingMode:"direct",lockedRepresentations:new W(null)},r.push(d),this._shouldAdvertisePeriod(d)&&(d.isPeriodAdvertised=!0,t.push({id:u.id,start:u.start,end:u.end}))}if(!(t.length>0&&(this.trigger("newAvailablePeriods",t),this._isDisposed)))for(let d of r){if(!d.isPeriodAdvertised)continue;let u=["audio","video","text"];for(let c of u){let l=d[c];if(l.dispatcher!==null&&l.storedSettings!==void 0&&!l.dispatcher.hasSetTrack()&&(l.dispatcher.updateTrack(l.storedSettings),this._isDisposed))return}}}_shouldAdvertisePeriod(e){return!e.isPeriodAdvertised&&e.text.dispatcher!==null&&e.video.dispatcher!==null&&e.audio.dispatcher!==null}};function Kt(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.period.id===e)return r}}function mc(n){var e,t,r;return!n.inManifest&&((e=n.text)==null?void 0:e.dispatcher)===null&&((t=n.audio)==null?void 0:t.dispatcher)===null&&((r=n.video)==null?void 0:r.dispatcher)===null}function _s(n,e){var t;return e&&((t=n.trickModeTracks)==null?void 0:t[0])!==void 0?n.trickModeTracks[0]:n}function pc(n,e){return{period:n,inManifest:e,isPeriodAdvertised:!1,isRemoved:!1,audio:{storedSettings:void 0,dispatcher:null},video:{storedSettings:void 0,dispatcher:null},text:{storedSettings:void 0,dispatcher:null}}}function tn(n){return{start:n.start,end:n.end,id:n.id}}function US(n,e){if(!(n.adaptations[e]!==void 0&&n.adaptations[e].length>0))return{fallbackTrack:null,noSourceMedia:!0};let r=FS(n,e);return{fallbackTrack:r!=null?r:null,noSourceMedia:!1}}function FS(n,e){var r;return q((r=n.adaptations[e])!=null?r:[],i=>i.supportStatus.hasSupportedCodec===!1||i.supportStatus.isDecipherable===!1?!1:i.representations.filter(a=>wt(a)===!0).length>0)}var cg=Fo;function fg(n){let e,t,r,i,o,a,{DEFAULT_BASE_BANDWIDTH:s,DEFAULT_VIDEO_RESOLUTION_LIMIT:d,DEFAULT_MAX_BUFFER_AHEAD:u,DEFAULT_MAX_BUFFER_BEHIND:c,DEFAULT_MAX_VIDEO_BUFFER_SIZE:l,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:f,DEFAULT_WANTED_BUFFER_AHEAD:m}=O.getCurrent();if(_(n.maxBufferAhead))e=u;else if(e=Number(n.maxBufferAhead),isNaN(e))throw new Error("Invalid maxBufferAhead parameter. Should be a number.");if(_(n.maxBufferBehind))t=c;else if(t=Number(n.maxBufferBehind),isNaN(t))throw new Error("Invalid maxBufferBehind parameter. Should be a number.");if(_(n.wantedBufferAhead))r=m;else if(r=Number(n.wantedBufferAhead),isNaN(r))throw new Error("Invalid wantedBufferAhead parameter. Should be a number.");if(_(n.maxVideoBufferSize))i=l;else if(i=Number(n.maxVideoBufferSize),isNaN(i))throw new Error("Invalid maxVideoBufferSize parameter. Should be a number.");let g=_(n.videoResolutionLimit)?d:n.videoResolutionLimit,I=_(n.throttleVideoBitrateWhenHidden)?f:!!n.throttleVideoBitrateWhenHidden;if(_(n.videoElement))o=document.createElement("video");else if(n.videoElement.nodeName.toLowerCase()==="video"||n.videoElement.nodeName.toLowerCase()==="audio")o=n.videoElement;else throw new Error("Invalid videoElement parameter. Should be a HTMLMediaElement.");if(_(n.baseBandwidth))a=s;else if(a=Number(n.baseBandwidth),isNaN(a))throw new Error("Invalid baseBandwidth parameter. Should be a number.");return{maxBufferAhead:e,maxBufferBehind:t,videoResolutionLimit:g,videoElement:o,wantedBufferAhead:r,maxVideoBufferSize:i,throttleVideoBitrateWhenHidden:I,baseBandwidth:a}}function mg(n){var e,t,r,i;if(n===null||typeof n!="object"&&n!==void 0)throw new Error("API: reload - Invalid options format.");if((n==null?void 0:n.reloadAt)===null||typeof(n==null?void 0:n.reloadAt)!="object"&&(n==null?void 0:n.reloadAt)!==void 0)throw new Error("API: reload - Invalid 'reloadAt' option format.");if(typeof((e=n==null?void 0:n.reloadAt)==null?void 0:e.position)!="number"&&((t=n==null?void 0:n.reloadAt)==null?void 0:t.position)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.position' option format.");if(typeof((r=n==null?void 0:n.reloadAt)==null?void 0:r.relative)!="number"&&((i=n==null?void 0:n.reloadAt)==null?void 0:i.relative)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.relative' option format.");if(!Array.isArray(n==null?void 0:n.keySystems)&&(n==null?void 0:n.keySystems)!==void 0)throw new Error("API: reload - Invalid 'keySystems' option format.");if((n==null?void 0:n.autoPlay)!==void 0&&typeof n.autoPlay!="boolean")throw new Error("API: reload - Invalid 'autoPlay' option format.")}function pg(n){var P,M,N,U;let e,t,r,i,o,a,s,{DEFAULT_AUTO_PLAY:d,DEFAULT_CODEC_SWITCHING_BEHAVIOR:u,DEFAULT_ENABLE_FAST_SWITCHING:c,DEFAULT_TEXT_TRACK_MODE:l,DEFAULT_AUDIO_TRACKS_NOT_PLAYABLE_BEHAVIOR:f,DEFAULT_VIDEO_TRACKS_NOT_PLAYABLE_BEHAVIOR:m}=O.getCurrent();if(_(n))throw new Error("No option set on loadVideo");if(!_(n.url))e=String(n.url);else if(_(n.initialManifest)&&_(n.manifestLoader))throw new Error("Unable to load a content: no url set on loadVideo.\nPlease provide at least either an `url` argument, a `initialManifest` option or a `manifestLoader` option so the RxPlayer can load the content.");if(_(n.transport))throw new Error("No transport set on loadVideo");t=String(n.transport);let g=_(n.autoPlay)?d:!!n.autoPlay;if(_(n.keySystems))r=[];else{r=Array.isArray(n.keySystems)?n.keySystems:[n.keySystems];for(let L of r)if(typeof L.type!="string"||typeof L.getLicense!="function")throw new Error("Invalid key system given: Missing type string or getLicense callback")}let I=n.lowLatencyMode===void 0?!1:!!n.lowLatencyMode,h=n.initialManifest,y=(P=n.minimumManifestUpdateInterval)!=null?P:0,T=(M=n.defaultAudioTrackSwitchingMode)!=null?M:void 0;T!==void 0&&!J(["seamless","direct","reload"],T)&&(p.warn("API","The `defaultAudioTrackSwitchingMode` loadVideo option must match one of the following strategy name:\n- `seamless`\n- `direct`\n- `reload`"),T=void 0);let v=_(n.onCodecSwitch)?u:n.onCodecSwitch;J(["continue","reload"],v)||(p.warn("API","The `onCodecSwitch` loadVideo option must match one of the following string:\n- `continue`\n- `reload`\nIf badly set, "+u+" will be used as default"),v=u);let E=_(n.onAudioTracksNotPlayable)?f:n.onAudioTracksNotPlayable;J(["continue","error"],E)||(p.warn("API","The `onAudioTracksNotPlayable` loadVideo option must match one of the following string:\n- `continue`\n- `error`\nIf badly set, "+f+" will be used as default"),E=f);let R=_(n.onVideoTracksNotPlayable)?m:n.onVideoTracksNotPlayable;if(J(["continue","error"],R)||(p.warn("API","The `onVideoTracksNotPlayable` loadVideo option must match one of the following string:\n- `continue`\n- `error`\nIf badly set, "+m+" will be used as default"),R=m),_(n.textTrackMode))i=l;else{if(n.textTrackMode!=="native"&&n.textTrackMode!=="html")throw new Error("Invalid textTrackMode.");i=n.textTrackMode}if(i==="html"){if(_(n.textTrackElement))throw new Error('You have to provide a textTrackElement in "html" textTrackMode.');if(n.textTrackElement instanceof HTMLElement)a=n.textTrackElement;else throw new Error("textTrackElement should be an HTMLElement.")}else _(n.textTrackElement)||p.warn("API",'You have set a textTrackElement without being in an "html" textTrackMode. It will be ignored.');if(_(n.mode))o="auto";else{if(!J(["auto","multithread","main"],n.mode))throw new Error("Invalid `mode` option.");o=n.mode}let k=_(n.enableFastSwitching)?c:n.enableFastSwitching;if(!_(n.startAt))if("wallClockTime"in n.startAt&&n.startAt.wallClockTime instanceof Date){let L=n.startAt.wallClockTime.getTime()/1e3;s=G({},n.startAt,{wallClockTime:L})}else s=n.startAt;let A=(N=n.requestConfig)!=null?N:{};return{__priv_patchLastSegmentInSidx:n.__priv_patchLastSegmentInSidx,__priv_manifestUpdateUrl:n.__priv_manifestUpdateUrl,checkMediaSegmentIntegrity:n.checkMediaSegmentIntegrity,checkManifestIntegrity:n.checkManifestIntegrity,autoPlay:g,defaultAudioTrackSwitchingMode:T,enableFastSwitching:k,initialManifest:h,keySystems:r,lowLatencyMode:I,manifestLoader:n.manifestLoader,minimumManifestUpdateInterval:y,requestConfig:A,onCodecSwitch:v,onAudioTracksNotPlayable:E,onVideoTracksNotPlayable:R,referenceDateTime:n.referenceDateTime,representationFilter:n.representationFilter,segmentLoader:n.segmentLoader,serverSyncInfos:n.serverSyncInfos,startAt:s,textTrackElement:a,textTrackMode:i,transport:t,mode:o,url:e,cmcd:n.cmcd,experimentalOptions:{enableRepresentationAvoidance:((U=n.experimentalOptions)==null?void 0:U.enableRepresentationAvoidance)===!0}}}function gc(n){return!(n&&(V.browser===V.BROWSERS.SafariMobile||V.browser===V.BROWSERS.SafariDesktop))}function gg(n,e,t,r){if(r.isCancelled())return;let i=n.getReference().getValue().seeking===2;i&&(e(),r.isCancelled())||n.listen(o=>{o.event==="seeking"?(i=!0,e()):i&&o.event==="seeked"&&(i=!1,t())},{includeLastObservation:!0,clearSignal:r})}function hg(n,e,t,r){r.isCancelled()||n===null||(n.addEventListener("play",e),n.addEventListener("pause",t),r.register(()=>{n.removeEventListener("play",e),n.removeEventListener("pause",t)}))}function Ig(n,e,t,r,i){let o=new W("LOADING",i);n.addEventListener("loaded",()=>{if(o.getValue()==="LOADING"){if(o.setValue("LOADED"),!i.isCancelled()){let d=hc(e,null,r,o.getValue());d!=="PAUSED"&&o.setValue(d)}}else o.getValue()==="RELOADING"?o.setValue(hc(e,null,r,o.getValue())):s(null)},i),n.addEventListener("reloadingMediaSource",()=>{Ar(o.getValue())&&o.setValueIfChanged("RELOADING")},i);let a=null;return n.addEventListener("stalled",d=>{d!==a&&(s(d),a=d)},i),n.addEventListener("unstalled",()=>{a!==null&&(s(null),a=null)},i),t.listen(d=>{J(["seeking","ended","play","pause"],d.event)&&s(a)},{clearSignal:i}),o;function s(d){if(!Ar(o.getValue()))return;let u=hc(e,d,r,o.getValue());o.getValue()==="LOADED"&&u==="PAUSED"||o.setValueIfChanged(u)}}function hc(n,e,t,r){let{FORCED_ENDED_THRESHOLD:i}=O.getCurrent();if(n.ended)return"ENDED";if(e!==null){let o=Math.abs(n.duration-n.currentTime);return!_(i)&&o<i?"ENDED":e==="seeking"?"SEEKING":e==="freezing"?"FREEZING":r==="LOADED"&&!gc(t)?"LOADED":"BUFFERING"}return n.paused?"PAUSED":"PLAYING"}function Ar(n){return n!=="LOADING"&&n!=="RELOADING"&&n!=="STOPPED"}var Ic=Z,Ko=typeof Ic.__RX_PLAYER_DEBUG_MODE__=="boolean"&&Ic.__RX_PLAYER_DEBUG_MODE__;try{Object.defineProperty(Ic,"__RX_PLAYER_DEBUG_MODE__",{get(){return Ko},set(n){Ko=n,n&&(xr.LogLevel="DEBUG",xr.LogFormat="full")}})}catch(n){}Ko?p.setLevel("DEBUG","full"):b.CURRENT_ENV===b.DEV&&p.setLevel(S.CURRENT_LEVEL,"standard");var KS=Fe(),VS=["manifestLoader","segmentLoader"],nn=class nn extends se{static get ErrorTypes(){return ft}static get ErrorCodes(){return Ms}static get LogLevel(){return p.getLevel()}static set LogLevel(e){p.setLevel(e,p.getFormat())}static get LogFormat(){return p.getFormat()}static set LogFormat(e){p.setLevel(p.getLevel(),e)}static addFeatures(e){Go(e)}static _priv_registerVideoElement(e){nn._priv_currentlyUsedVideoElements.has(e)&&console.warn(`The video element is already attached to another RxPlayer instance.
|
|
23
|
+
Make sure to dispose the previous instance with player.dispose() before creating a new player instance attaching that video element.`),nn._priv_currentlyUsedVideoElements.add(e)}static _priv_deregisterVideoElement(e){nn._priv_currentlyUsedVideoElements.has(e)&&nn._priv_currentlyUsedVideoElements.delete(e)}constructor(e={}){super();let{baseBandwidth:t,videoResolutionLimit:r,maxBufferAhead:i,maxBufferBehind:o,throttleVideoBitrateWhenHidden:a,videoElement:s,wantedBufferAhead:d,maxVideoBufferSize:u}=fg(e);s.preload="auto",this.version="4.4.1-dev.2025101500",this.log=p,this.state="STOPPED",this.videoElement=s,nn._priv_registerVideoElement(this.videoElement);let c=new D;this._destroyCanceller=c,this._priv_pictureInPictureRef=Xc(s,c.signal),this._priv_speed=new W(s.playbackRate,this._destroyCanceller.signal),this._priv_preferTrickModeTracks=!1,this._priv_contentLock=new W(!1,this._destroyCanceller.signal),this._priv_bufferOptions={wantedBufferAhead:new W(d,this._destroyCanceller.signal),maxBufferAhead:new W(i,this._destroyCanceller.signal),maxBufferBehind:new W(o,this._destroyCanceller.signal),maxVideoBufferSize:new W(u,this._destroyCanceller.signal)},this._priv_bitrateInfos={lastBitrates:{audio:t,video:t}},this._priv_throttleVideoBitrateWhenHidden=a,this._priv_videoResolutionLimit=r,this._priv_currentError=null,this._priv_contentInfos=null,this._priv_contentEventsMemory={},this._priv_reloadingMetadata={},this._priv_lastAutoPlay=!1,this._priv_worker=null;let l=()=>{this.trigger("volumeChange",{volume:s.volume,muted:s.muted})};s.addEventListener("volumechange",l),c.signal.register(()=>{s.removeEventListener("volumechange",l)})}attachWorker(e){return new Promise((t,r)=>{var a;if(!cc())return p.warn("API","Cannot rely on a WebWorker: Worker API unavailable"),r(new En("INCOMPATIBLE_ERROR","Worker unavailable"));if(this._priv_worker!==null){if(this.state!=="STOPPED")return p.warn("API","Cannot attach a new worker while a content is playing, please stop the player first."),r(new En("SETUP_ERROR","Cannot attach a new worker while a content is playing"));this._priv_worker.terminate()}if(typeof e.workerUrl=="string")this._priv_worker=new Worker(e.workerUrl);else{let s=URL.createObjectURL(e.workerUrl);this._priv_worker=new Worker(s),URL.revokeObjectURL(s)}this._priv_worker.onerror=s=>{this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null),p.error("API","Unexpected worker error",s.error instanceof Error?s.error:void 0),r(new En("UNKNOWN_ERROR",'Unexpected Worker "error" event'))};let i=s=>{let d=s.data;d.type==="init-error"?(p.warn("API","Processing InitError worker message: detaching worker"),this._priv_worker!==null&&(this._priv_worker.removeEventListener("message",i),this._priv_worker.terminate(),this._priv_worker=null),r(new En("SETUP_ERROR","Worker parser initialization failed: "+d.value.errorMessage))):d.type==="init-success"&&(p.info("API","InitSuccess received from worker."),this._priv_worker!==null&&this._priv_worker.removeEventListener("message",i),t())};this._priv_worker.addEventListener("message",i),p.debug("M-->C","Sending message",{name:"init"}),this._priv_worker.postMessage({type:"init",value:{dashWasmUrl:e.dashWasmUrl,logLevel:p.getLevel(),logFormat:p.getFormat(),sendBackLogs:Ko,date:Date.now(),timestamp:z(),hasVideo:((a=this.videoElement)==null?void 0:a.nodeName.toLowerCase())==="video"}}),p.addEventListener("onLogLevelChange",s=>{this._priv_worker!==null&&(p.debug("M-->C","Sending message",{name:"log-level-update"}),this._priv_worker.postMessage({type:"log-level-update",value:{logLevel:s.level,logFormat:s.format,sendBackLogs:Ko}}))},this._destroyCanceller.signal);let o=s=>{this._priv_worker!==null&&(p.debug("M-->C","Sending message:",{name:"config-update"}),this._priv_worker.postMessage({type:"config-update",value:s}))};O.updated&&o(O.getCurrent()),O.addEventListener("update",o,this._destroyCanceller.signal)})}getCurrentModeInformation(){return this._priv_contentInfos===null?null:{isDirectFile:this._priv_contentInfos.isDirectFile,useWorker:this._priv_contentInfos.useWorker}}addEventListener(e,t){return super.addEventListener(e,t)}stop(){this._priv_contentInfos!==null&&this._priv_contentInfos.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this.state!=="STOPPED"&&this._priv_setPlayerState("STOPPED")}dispose(){this.stop(),this.videoElement!==null&&(nn._priv_deregisterVideoElement(this.videoElement),nr(this.videoElement).catch(e=>{let t=e instanceof Error?e.message:"Unknown error";p.error("API","Could not dispose decryption resources: "+t)})),this._destroyCanceller.cancel(),this._priv_reloadingMetadata={},this.videoElement=null,this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null)}loadVideo(e){let t=pg(e);p.info("API","Calling loadvideo",{url:t.url,transport:t.transport}),this._priv_reloadingMetadata={options:t},this._priv_initializeContentPlayback(t),this._priv_lastAutoPlay=t.autoPlay}reload(e){var c,l,f;let{options:t,manifest:r,reloadPosition:i,reloadInPause:o}=this._priv_reloadingMetadata;if(t===void 0)throw new Error("API: Can't reload without having previously loaded a content.");mg(e);let a;if(((c=e==null?void 0:e.reloadAt)==null?void 0:c.position)!==void 0)a={position:e.reloadAt.position};else if(((l=e==null?void 0:e.reloadAt)==null?void 0:l.relative)!==void 0){if(i===void 0)throw new Error("Can't reload to a relative position when previous content was not loaded.");a={position:e.reloadAt.relative+i}}else i!==void 0&&(a={position:i});let s;(e==null?void 0:e.autoPlay)!==void 0?s=e.autoPlay:o!==void 0&&(s=!o);let d;(e==null?void 0:e.keySystems)!==void 0?d=e.keySystems:((f=this._priv_reloadingMetadata.options)==null?void 0:f.keySystems)!==void 0&&(d=this._priv_reloadingMetadata.options.keySystems);let u=me(oe({},t),{initialManifest:r});a!==void 0&&(u.startAt=a),s!==void 0&&(u.autoPlay=s),d!==void 0&&(u.keySystems=d),this._priv_initializeContentPlayback(u)}createDebugElement(e){if(pe.createDebugElement===null)throw new Error("Feature `DEBUG_ELEMENT` not added to the RxPlayer");let t=new D;return pe.createDebugElement(e,this,t.signal),{dispose(){t.cancel()}}}getAvailableThumbnailTracks({time:e,periodId:t}={}){if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return[];let{manifest:r}=this._priv_contentInfos,i;if(e!==void 0){if(i=tr(this._priv_contentInfos.manifest,e),i===void 0||i.thumbnailTracks.length===0)return[]}else if(t!==void 0){if(i=q(r.periods,o=>o.id===t),i===void 0)return p.error("API","getAvailableThumbnailTracks: periodId not found",{periodId:t}),[]}else{let{currentPeriod:o}=this._priv_contentInfos;if(o===null)return[];i=o}return i.thumbnailTracks.map(o=>({id:o.id,width:Math.floor(o.width/o.horizontalTiles),height:Math.floor(o.height/o.verticalTiles),mimeType:o.mimeType}))}async renderThumbnail(e){if(_(e.time))throw new Error("You have to provide a `time` property to `renderThumbnail`, indicating the wanted thumbnail time in seconds.");if(_(e.container))throw new Error("You have to provide a `container` property to `renderThumbnail`, specifying the HTML Element in which the thumbnail should be inserted.");return fc(this._priv_contentInfos,e)}_priv_initializeContentPlayback(e){var de,ue,ve,ce,ye,ct,Et;let{autoPlay:t,cmcd:r,defaultAudioTrackSwitchingMode:i,enableFastSwitching:o,initialManifest:a,keySystems:s,lowLatencyMode:d,minimumManifestUpdateInterval:u,requestConfig:c,onCodecSwitch:l,startAt:f,transport:m,checkMediaSegmentIntegrity:g,checkManifestIntegrity:I,manifestLoader:h,referenceDateTime:y,segmentLoader:T,serverSyncInfos:v,mode:E,experimentalOptions:R,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:A,url:P,onAudioTracksNotPlayable:M,onVideoTracksNotPlayable:N}=e;if(this.videoElement===null)throw new Error("the attached video element is disposed");let U=m==="directfile",L=new D,B=this.videoElement,C,w=!1,F=null;if(U){if(pe.directfile===null)throw this.stop(),this._priv_currentError=null,new Error("DirectFile feature not activated in your build.");if(_(P))throw new Error("No URL for a DirectFile content");if(p.info("API","Initializing DirectFile mode in the main thread"),F=this._priv_initializeMediaElementTracksStore(L.signal),L.isUsed())return;C=new pe.directfile.initDirectFile({autoPlay:t,keySystems:s,speed:this._priv_speed,startAt:f,url:P})}else{let $={lowLatencyMode:d,maxRetry:(de=c.manifest)==null?void 0:de.maxRetry,requestTimeout:(ue=c.manifest)==null?void 0:ue.timeout,connectionTimeout:(ve=c.manifest)==null?void 0:ve.connectionTimeout,minimumManifestUpdateInterval:u,initialManifest:a},Be=lc(),rt={throttleBitrate:{},limitResolution:{}};this._priv_throttleVideoBitrateWhenHidden&&(Be?rt.throttleBitrate={video:vn(Zc(this._priv_pictureInPictureRef,L.signal),At=>At?1/0:0,L.signal)}:p.warn("API","Can't apply throttleVideoBitrateWhenHidden because browser can't be trusted for visibility.")),this._priv_videoResolutionLimit==="videoElement"?Be?rt.limitResolution={video:ef(B,this._priv_pictureInPictureRef,L.signal)}:p.warn("API","Can't apply videoResolutionLimit because browser can't be trusted for video size."):this._priv_videoResolutionLimit==="screen"&&(rt.limitResolution={video:Jc(L.signal)});let it={initialBitrates:this._priv_bitrateInfos.lastBitrates,lowLatencyMode:d,throttlers:rt},ot=e.textTrackMode==="native"?{textTrackMode:"native"}:{textTrackMode:"html",textTrackElement:e.textTrackElement},wr=G({enableFastSwitching:o,onCodecSwitch:l},this._priv_bufferOptions),Or={lowLatencyMode:d,maxRetry:(ce=c.segment)==null?void 0:ce.maxRetry,requestTimeout:(ye=c.segment)==null?void 0:ye.timeout,connectionTimeout:(ct=c.segment)==null?void 0:ct.connectionTimeout},Dr={lowLatencyMode:d,checkMediaSegmentIntegrity:g,checkManifestIntegrity:I,referenceDateTime:y,serverSyncInfos:v,manifestLoader:h,segmentLoader:T,representationFilter:e.representationFilter,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:A},Vo=pe.multithread!==null&&this._priv_worker!==null&&this.videoElement.FORCED_MEDIA_SOURCE===void 0&&m==="dash"&&VS.every(At=>_(e[At]))&&typeof e.representationFilter!="function";if(E==="main"||E==="auto"&&!Vo){if(pe.monothread===null)throw new Error("Cannot load video, neither in a WebWorker nor with the `MEDIA_SOURCE_MAIN` feature");p.info("API","Initializing MediaSource mode in the main thread");let At=new pe.monothread.coreInterface,Lr=At.getCallbacks();pe.monothread.initializeCoreEntry(Lr.setCoreMessageReceiver,Lr.sendCoreMessage),At.sendMessage({type:"init",value:{dashWasmUrl:void 0,hasVideo:((Et=this.videoElement)==null?void 0:Et.nodeName.toLowerCase())==="video",logLevel:p.getLevel(),logFormat:p.getFormat(),sendBackLogs:!1,date:Date.now(),timestamp:z()}}),C=new pe.monothread.init({coreInterface:At,adaptiveOptions:it,autoPlay:t,bufferOptions:wr,cmcd:r,enableRepresentationAvoidance:R.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transport:m,transportOptions:Dr,manifestRequestSettings:$,segmentRequestOptions:Or,speed:this._priv_speed,startAt:f,textTrackOptions:ot,url:P,useMseInWorker:!1})}else{if(pe.multithread===null)throw new Error("Cannot load video in multithread mode: `MULTI_THREAD` feature not imported.");if(this._priv_worker===null)throw new Error("Cannot load video in multithread mode: `attachWorker` method not called.");ee(typeof e.representationFilter!="function"),w=!0,p.info("API","Initializing MediaSource mode in a WebWorker"),C=new pe.multithread.init({coreInterface:new pe.multithread.coreInterface(this._priv_worker),adaptiveOptions:it,autoPlay:t,bufferOptions:wr,cmcd:r,enableRepresentationAvoidance:R.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transport:m,transportOptions:Dr,manifestRequestSettings:$,segmentRequestOptions:Or,speed:this._priv_speed,startAt:f,textTrackOptions:ot,url:P,useMseInWorker:dp})}}let K=new Bo(B,{withMediaSource:!U,lowLatencyMode:d});K.blockSeeking(),L.signal.register(()=>{K.stop()});let Y={contentId:KS(),originalUrl:P,playbackObserver:K,currentContentCanceller:L,defaultAudioTrackSwitchingMode:i,initializer:C,isDirectFile:U,manifest:null,currentPeriod:null,activeAdaptations:null,activeRepresentations:null,tracksStore:null,mediaElementTracksStore:F,useWorker:w,segmentSinkMetricsCallback:null,fetchThumbnailDataCallback:null,thumbnailRequestsInfo:{pendingRequests:new WeakMap,lastResponse:null},onAudioTracksNotPlayable:M,onVideoTracksNotPlayable:N};C.addEventListener("error",$=>{this._priv_onFatalError($,Y)}),C.addEventListener("warning",$=>{let Be=Ae($,{defaultCode:"NONE",defaultReason:"An unknown error happened."});p.warn("API","Sending warning:",Be),this.trigger("warning",Be)}),C.addEventListener("reloadingMediaSource",$=>{Y.tracksStore!==null&&Y.tracksStore.resetPeriodObjects(),this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=null),this._priv_lastAutoPlay=$.autoPlay}),C.addEventListener("inbandEvents",$=>this.trigger("inbandEvents",$)),C.addEventListener("streamEvent",$=>this.trigger("streamEvent",$)),C.addEventListener("streamEventSkip",$=>this.trigger("streamEventSkip",$)),C.addEventListener("activePeriodChanged",$=>this._priv_onActivePeriodChanged(Y,$)),C.addEventListener("periodStreamReady",$=>this._priv_onPeriodStreamReady(Y,$)),C.addEventListener("periodStreamCleared",$=>this._priv_onPeriodStreamCleared(Y,$)),C.addEventListener("representationChange",$=>this._priv_onRepresentationChange(Y,$)),C.addEventListener("adaptationChange",$=>this._priv_onAdaptationChange(Y,$)),C.addEventListener("bitrateEstimateChange",$=>this._priv_onBitrateEstimateChange($)),C.addEventListener("manifestReady",$=>this._priv_onManifestReady(Y,$)),C.addEventListener("manifestUpdate",$=>this._priv_onManifestUpdate(Y,$)),C.addEventListener("codecSupportUpdate",()=>this._priv_onCodecSupportUpdate(Y)),C.addEventListener("decipherabilityUpdate",$=>this._priv_onDecipherabilityUpdate(Y,$)),C.addEventListener("loaded",$=>{this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=$.getSegmentSinkMetrics,this._priv_contentInfos.fetchThumbnailDataCallback=$.getThumbnailData)}),C.prepare(),this.stop();let ie=Ig(C,B,K,U,L.signal);L.signal.register(()=>{C.dispose()});let j=$=>{switch($){case"STOPPED":case"RELOADING":case"LOADING":break;case"ENDED":this._priv_reloadingMetadata.reloadInPause=!0,this._priv_reloadingMetadata.reloadPosition=K.getReference().getValue().position.getPolled();break;default:{let Be=K.getReference().getValue();this._priv_reloadingMetadata.reloadInPause=Be.paused,this._priv_reloadingMetadata.reloadPosition=Be.position.getWanted();break}}},Q=null,ne=$=>{Q!==null&&(Q.cancel(),Q=null),ie.onUpdate((Be,rt)=>{Ar(Be)&&(rt(),Q!==null&&Q.cancel(),Q=new D,Q.linkToSignal(L.signal),$!==!B.paused&&(B.paused?this.trigger("pause",null):this.trigger("play",null)),hg(B,()=>this.trigger("play",null),()=>this.trigger("pause",null),L.signal))},{emitCurrentValue:!1,clearSignal:L.signal})};ne(t),C.addEventListener("reloadingMediaSource",$=>{ne($.autoPlay)}),this._priv_currentError=null,this._priv_contentInfos=Y;let X=null;ie.onUpdate($=>{j($),this._priv_setPlayerState($),!L.isUsed()&&(X!==null?Ar(this.state)||(X.cancel(),X=null):Ar(this.state)&&(X=new D,X.linkToSignal(L.signal),gg(K,()=>this.trigger("seeking",null),()=>this.trigger("seeked",null),X.signal)))},{emitCurrentValue:!0,clearSignal:L.signal}),K.listen($=>{j(this.state),this._priv_triggerPositionUpdate(Y,$)},{clearSignal:L.signal}),L.signal.register(()=>{C.removeEventListener()}),this._priv_contentLock.onUpdate(($,Be)=>{$||(Be(),C.start(B,K))},{emitCurrentValue:!0,clearSignal:L.signal})}getError(){return this._priv_currentError}getVideoElement(){return this.videoElement}getPlayerState(){return this.state}isContentLoaded(){return!J(["LOADING","RELOADING","STOPPED"],this.state)}isBuffering(){return J(["BUFFERING","SEEKING","LOADING","RELOADING"],this.state)}isPaused(){return this.videoElement!==null?J(["LOADING","RELOADING"],this.state)?!this._priv_lastAutoPlay:this.videoElement.paused:!0}isLive(){if(this._priv_contentInfos===null)return!1;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;return e||t===null?!1:t.isLive}areTrickModeTracksEnabled(){return this._priv_preferTrickModeTracks}getContentUrls(){if(this._priv_contentInfos===null)return;let{isDirectFile:e,manifest:t,originalUrl:r}=this._priv_contentInfos;if(e)return r===void 0?void 0:[r];if(t!==null)return t.uris}updateContentUrls(e,t){if(this._priv_contentInfos===null)throw new Error("No content loaded");let r=(t==null?void 0:t.refresh)===!0;this._priv_contentInfos.initializer.updateContentUrls(e,r)}getMediaDuration(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}getCurrentBufferGap(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement,t=jf(e.buffered,e.currentTime);return t===1/0?0:t}getWallClockTime(){if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)return this.videoElement.currentTime;let e=this.getWallClockOffset();return this.videoElement.currentTime+e}getWallClockOffset(){var r;if(this.videoElement===null||this._priv_contentInfos===null)return 0;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){let i=No(this.videoElement);return i!=null?i:0}return t!==null&&(r=t.availabilityStartTime)!=null?r:0}getPosition(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.currentTime}getLastStoredContentPosition(){return this._priv_reloadingMetadata.reloadPosition}getPlaybackRate(){return this._priv_speed.getValue()}setPlaybackRate(e,t){var o;e!==this._priv_speed.getValue()&&this._priv_speed.setValue(e);let r=t==null?void 0:t.preferTrickModeTracks;if(typeof r!="boolean")return;this._priv_preferTrickModeTracks=r;let i=(o=this._priv_contentInfos)==null?void 0:o.tracksStore;_(i)||(r&&!i.isTrickModeEnabled()?i.enableVideoTrickModeTracks():!r&&i.isTrickModeEnabled()&&i.disableVideoTrickModeTracks())}getVideoRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return _(e.video)?e.video:kn(e.video)}getAudioRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return _(e.audio)?e.video:Xo(e.audio)}play(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement.play();return _(e)||typeof e.catch!="function"?Promise.resolve():e.catch(t=>{if(t.name==="NotAllowedError"){let r=new re("MEDIA_ERR_PLAY_NOT_ALLOWED",t.toString());this.trigger("warning",r)}throw t})}pause(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.pause()}seekTo(e){var o;if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)throw new Error("player: no content loaded");let{isDirectFile:t,manifest:r}=this._priv_contentInfos,i;if(typeof e=="number")i=e;else if(typeof e=="object"){let a=e,s=this.videoElement.currentTime;if(!_(a.relative))i=s+a.relative;else if(!_(a.position))i=a.position;else{if(_(a.wallClockTime))throw new Error('invalid time object. You must set one of the following properties: "relative", "position" or "wallClockTime"');if(r!==null)i=a.wallClockTime-((o=r.availabilityStartTime)!=null?o:0);else if(t){if(this.videoElement!==null){let d=No(this.videoElement);d!==void 0&&(i=a.wallClockTime-d)}}else throw new Error("Cannot seek: wallClockTime asked but Manifest not yet loaded.");i===void 0&&(i=a.wallClockTime)}}if(i===void 0)throw new Error("invalid time given");return p.info("API","API seekTo",{positionWanted:i}),this._priv_contentInfos.playbackObserver.setCurrentTime(i,!1),i}getVolume(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.volume}setVolume(e){if(this.videoElement===null)throw new Error("Disposed player");let t=this.videoElement;e!==t.volume&&(t.volume=e)}isMute(){var e;return((e=this.videoElement)==null?void 0:e.muted)===!0}mute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted||(this.videoElement.muted=!0)}unMute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted&&(this.videoElement.muted=!1)}setMaxBufferBehind(e){this._priv_bufferOptions.maxBufferBehind.setValue(e)}setMaxBufferAhead(e){this._priv_bufferOptions.maxBufferAhead.setValue(e)}setWantedBufferAhead(e){this._priv_bufferOptions.wantedBufferAhead.setValue(e)}setMaxVideoBufferSize(e){this._priv_bufferOptions.maxVideoBufferSize.setValue(e)}getMaxBufferBehind(){return this._priv_bufferOptions.maxBufferBehind.getValue()}getMaxBufferAhead(){return this._priv_bufferOptions.maxBufferAhead.getValue()}getWantedBufferAhead(){return this._priv_bufferOptions.wantedBufferAhead.getValue()}getMaxVideoBufferSize(){return this._priv_bufferOptions.maxVideoBufferSize.getValue()}getCurrentPeriod(){var t;let e=(t=this._priv_contentInfos)==null?void 0:t.currentPeriod;return _(e)?null:{id:e.id,start:e.start,end:e.end}}getKeySystemConfiguration(){if(this.videoElement===null)throw new Error("Disposed player");let e=ur(this.videoElement);return e===null?null:{keySystem:e[0],configuration:e[1]}}getAvailablePeriods(){if(this._priv_contentInfos===null)return[];let{isDirectFile:e,tracksStore:t}=this._priv_contentInfos;return e?[]:t===null?[]:t.getAvailablePeriods().slice()}getAvailableAudioTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableAudioTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var c;return(c=d.getAvailableAudioTracks(u,o))!=null?c:[]})}getAvailableTextTracks(e){var i;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?(i=r==null?void 0:r.getAvailableTextTracks())!=null?i:[]:this._priv_callTracksStoreGetterSetter(e,[],(o,a)=>{var s;return(s=o.getAvailableTextTracks(a))!=null?s:[]})}getAvailableVideoTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableVideoTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var c;return(c=d.getAvailableVideoTracks(u,o))!=null?c:[]})}getAudioTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenAudioTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenAudioTrack(d,o))}getTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?r===null?void 0:r.getChosenTextTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.getChosenTextTrack(o))}getVideoTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenVideoTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenVideoTrack(d,o))}setAudioTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let c=typeof e=="string"?e:e.trackId;r==null||r.setAudioTrackById(c);return}catch(c){throw new Error("player: unknown audio track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(c,l)=>c.setAudioTrack({periodRef:l,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}setTextTrack(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let a=typeof e=="string"?e:e.trackId;r==null||r.setTextTrackById(a);return}catch(a){throw new Error("player: unknown text track")}let i,o;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.setTextTrack(s,o))}disableTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t){r==null||r.disableTextTrack();return}return this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"text"))}setVideoTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let c=typeof e=="string"?e:e.trackId;r==null||r.setVideoTrackById(c);return}catch(c){throw new Error("player: unknown video track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(c,l)=>c.setVideoTrack({periodRef:l,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}disableVideoTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t&&r!==null?r.disableVideoTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"video"))}lockVideoRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock video Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockVideoRepresentations(s,{representations:r,switchingMode:o}))}disableAudioTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t&&r!==null?r.disableAudioTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"audio"))}lockAudioRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock audio Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockAudioRepresentations(s,{representations:r,switchingMode:o}))}getLockedVideoRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedVideoRepresentations(i))}getLockedAudioRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedAudioRepresentations(i))}unlockVideoRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockVideoRepresentations(i))}unlockAudioRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockAudioRepresentations(i))}getMinimumPosition(){if(this._priv_contentInfos===null)return null;if(this._priv_contentInfos.isDirectFile)return 0;let{manifest:e}=this._priv_contentInfos;return e!==null?Cn(e):null}getLivePosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(!e)return(t==null?void 0:t.isLive)!==!0?null:Pn(t)}getMaximumPosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}return t!==null?!t.isDynamic&&this.videoElement!==null?this.videoElement.duration:Ot(t):null}async __priv_getSegmentSinkMetrics(){var e,t;return(t=(e=this._priv_contentInfos)==null?void 0:e.segmentSinkMetricsCallback)==null?void 0:t.call(e)}__priv_getManifest(){return this._priv_contentInfos===null?null:this._priv_contentInfos.manifest}__priv_getCurrentAdaptation(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeAdaptations:t}=this._priv_contentInfos;return e===null||t===null||_(t[e.id])?null:t[e.id]}__priv_getCurrentRepresentations(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeRepresentations:t}=this._priv_contentInfos;return e===null||t===null||_(t[e.id])?null:t[e.id]}_priv_cleanUpCurrentContentState(){var t,r,i,o;p.debug("API","Locking `contentLock` to clean-up the current content."),this._priv_contentLock.setValue(!0),(r=(t=this._priv_contentInfos)==null?void 0:t.tracksStore)==null||r.dispose(),(o=(i=this._priv_contentInfos)==null?void 0:i.mediaElementTracksStore)==null||o.dispose(),this._priv_contentInfos=null,this._priv_contentEventsMemory={};let e=()=>{this.videoElement!==null&&(p.debug("API","Unlocking `contentLock`. Next content can begin."),this._priv_contentLock.setValue(!1))};_(this.videoElement)?e():ra(this.videoElement).then(()=>{p.debug("API","DRM session cleaned-up with success!"),e()},a=>{p.error("API","An error arised when trying to clean-up the DRM session:"+(a instanceof Error?a.toString():"Unknown Error")),e()})}_priv_onManifestReady(e,t){var i;if(e.contentId!==((i=this._priv_contentInfos)==null?void 0:i.contentId))return;e.manifest=t,t.manifestFormat===0&&(this._priv_reloadingMetadata.manifest=t);let r=new cg({preferTrickModeTracks:this._priv_preferTrickModeTracks,defaultAudioTrackSwitchingMode:e.defaultAudioTrackSwitchingMode,onTracksNotPlayableForType:{audio:e.onAudioTracksNotPlayable,video:e.onVideoTracksNotPlayable,text:"continue"}});e.tracksStore=r,r.addEventListener("newAvailablePeriods",o=>{this.trigger("newAvailablePeriods",o)}),r.addEventListener("brokenRepresentationsLock",o=>{this.trigger("brokenRepresentationsLock",o)}),r.addEventListener("trackUpdate",o=>{var s,d;this.trigger("trackUpdate",o);let a=(d=(s=this._priv_contentInfos)==null?void 0:s.currentPeriod)!=null?d:void 0;o.reason==="no-playable-representation"&&o.period.id===(a==null?void 0:a.id)&&this._priv_onAvailableTracksMayHaveChanged(o.trackType)}),r.addEventListener("warning",o=>{this.trigger("warning",o)}),r.addEventListener("error",o=>{this._priv_onFatalError(o,e)}),r.addEventListener("noPlayableTrack",o=>{this.trigger("noPlayableTrack",o)}),r.onManifestUpdate(t)}_priv_onManifestUpdate(e,t){var o,a,s;if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return;_(e==null?void 0:e.tracksStore)||e.tracksStore.onManifestUpdate(this._priv_contentInfos.manifest);let r=(a=(o=this._priv_contentInfos)==null?void 0:o.currentPeriod)!=null?a:void 0,i=(s=this._priv_contentInfos)==null?void 0:s.tracksStore;if(!(r===void 0||_(i))){for(let d of t.updatedPeriods)if(d.period.id===r.id&&(d.result.addedAdaptations.length>0||d.result.removedAdaptations.length>0)){if(i.getPeriodObjectFromPeriod(r)===void 0)return;this._priv_onAvailableTracksMayHaveChanged("audio"),this._priv_onAvailableTracksMayHaveChanged("text"),this._priv_onAvailableTracksMayHaveChanged("video")}}}_priv_onCodecSupportUpdate(e){let t=e==null?void 0:e.tracksStore;_(t)||t.onManifestCodecSupportUpdate()}_priv_onDecipherabilityUpdate(e,t){if(e===null||e.manifest===null)return;_(e==null?void 0:e.tracksStore)||e.tracksStore.onDecipherabilityUpdates();let r=t.reduce((i,o)=>{var s,d,u;if(!(q(i,c=>c[0].id===o.period.id&&c[1]===o.adaptation.type)!==void 0)){let c=e.tracksStore;if(c===null)return i;let l=!1,f=c.getPeriodObjectFromPeriod(o.period);if(f===void 0)return i;switch(o.adaptation.type){case"audio":l=((s=c.getChosenAudioTrack(f,!1))==null?void 0:s.id)===o.adaptation.id;break;case"video":l=((d=c.getChosenVideoTrack(f,!1))==null?void 0:d.id)===o.adaptation.id;break;case"text":l=((u=c.getChosenTextTrack(f))==null?void 0:u.id)===o.adaptation.id;break}l&&i.push([o.period,o.adaptation.type])}return i},[]);for(let[i,o]of r)this._priv_triggerEventIfNotStopped("representationListUpdate",{period:{start:i.start,end:i.end,id:i.id},trackType:o,reason:"decipherability-update"},e.currentContentCanceller.signal)}_priv_onActivePeriodChanged(e,{period:t}){var s,d,u,c,l,f;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;e.currentPeriod=t;let r=e.currentContentCanceller.signal;this._priv_contentEventsMemory.periodChange!==t&&(this._priv_contentEventsMemory.periodChange=t,this._priv_triggerEventIfNotStopped("periodChange",{start:t.start,end:t.end,id:t.id},r)),this._priv_triggerEventIfNotStopped("availableAudioTracksChange",this.getAvailableAudioTracks(),r),this._priv_triggerEventIfNotStopped("availableTextTracksChange",this.getAvailableTextTracks(),r),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",this.getAvailableVideoTracks(),r);let i=(d=this._priv_contentInfos)==null?void 0:d.tracksStore;if(_(i))this._priv_triggerEventIfNotStopped("audioTrackChange",null,r),this._priv_triggerEventIfNotStopped("textTrackChange",null,r),this._priv_triggerEventIfNotStopped("videoTrackChange",null,r);else{let m=i.getPeriodObjectFromPeriod(t);if(m!==void 0){let g=i.getChosenAudioTrack(m,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",g,r);let I=i.getChosenTextTrack(m);this._priv_triggerEventIfNotStopped("textTrackChange",I,r);let h=i.getChosenVideoTrack(m,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",h,r)}}let o=(c=(u=this.__priv_getCurrentRepresentations())==null?void 0:u.audio)!=null?c:null;this._priv_triggerEventIfNotStopped("audioRepresentationChange",_(o)?o:kn(o),r);let a=(f=(l=this.__priv_getCurrentRepresentations())==null?void 0:l.video)!=null?f:null;this._priv_triggerEventIfNotStopped("videoRepresentationChange",_(a)?a:kn(a),r)}_priv_onPeriodStreamReady(e,t){var s;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{type:r,period:i,adaptationRef:o}=t,a=e.tracksStore;switch(r){case"video":case"audio":case"text":_(a)?(p.error("API",`TracksStore not instanciated for a new ${r} period`),o.setValue(null)):a.addTrackReference(r,i,o);break;default:we(r)}}_priv_onPeriodStreamCleared(e,t){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;let{type:r,periodId:i}=t,o=e.tracksStore;switch(r){case"audio":case"text":case"video":_(o)||o.removeTrackReference(r,i);break}let{activeAdaptations:a,activeRepresentations:s}=e;if(!_(a)&&!_(a[i])){let u=a[i];delete u[r],Object.keys(u).length===0&&delete a[i]}if(!_(s)&&!_(s[i])){let u=s[i];delete u[r],Object.keys(u).length===0&&delete s[i]}}_priv_onAdaptationChange(e,{type:t,adaptation:r,period:i}){var c;if(e.contentId!==((c=this._priv_contentInfos)==null?void 0:c.contentId))return;e.activeAdaptations===null&&(e.activeAdaptations={});let{activeAdaptations:o,currentPeriod:a}=e,s=o[i.id];_(s)?o[i.id]={[t]:r}:s[t]=r;let{tracksStore:d}=e,u=e.currentContentCanceller.signal;if(d!==null&&a!==null&&!_(i)&&i.id===a.id){let l=d.getPeriodObjectFromPeriod(i);if(l===void 0)return;switch(t){case"audio":{let f=d.getChosenAudioTrack(l,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",f,u);break}case"text":{let f=d.getChosenTextTrack(l);this._priv_triggerEventIfNotStopped("textTrackChange",f,u);break}case"video":{let f=d.getChosenVideoTrack(l,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",f,u);break}}}}_priv_onRepresentationChange(e,{type:t,period:r,representation:i}){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;e.activeRepresentations===null&&(e.activeRepresentations={});let{activeRepresentations:o,currentPeriod:a}=e,s=o[r.id];if(_(s)?o[r.id]={[t]:i}:s[t]=i,!_(r)&&a!==null&&a.id===r.id){let u=this._priv_contentInfos.currentContentCanceller.signal;t==="video"?this._priv_triggerEventIfNotStopped("videoRepresentationChange",_(i)?i:kn(i),u):t==="audio"&&this._priv_triggerEventIfNotStopped("audioRepresentationChange",_(i)?i:Xo(i),u)}}_priv_onBitrateEstimateChange({type:e,bitrate:t}){t!==void 0&&(this._priv_bitrateInfos.lastBitrates[e]=t),this.trigger("__priv_bitrateEstimateChange",{type:e,bitrate:t})}_priv_setPlayerState(e){this.state!==e&&(this.state=e,p.info("API","playerStateChange event",{newState:e}),this.trigger("playerStateChange",e))}_priv_triggerPositionUpdate(e,t){var s,d;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{isDirectFile:r,manifest:i}=e;if(!r&&i===null||_(t))return;let o=i!==null?Ot(i):void 0,a={position:t.position.getPolled(),duration:t.duration,playbackRate:t.playbackRate,maximumPosition:o,bufferGap:t.bufferGap===void 0||!isFinite(t.bufferGap)?0:t.bufferGap};if(i!==null&&i.isLive&&t.position.getPolled()>0){let u=(d=i.availabilityStartTime)!=null?d:0;a.wallClockTime=t.position.getPolled()+u;let c=Pn(i);c!==void 0&&(a.liveGap=c-t.position.getPolled())}else if(r&&this.videoElement!==null){let u=No(this.videoElement);u!==void 0&&(a.wallClockTime=u+t.position.getPolled())}this.trigger("positionUpdate",a)}_priv_triggerEventIfNotStopped(e,t,r){r.isCancelled()||this.trigger(e,t)}_priv_initializeMediaElementTracksStore(e){var r,i,o;ee(pe.directfile!==null,"Initializing `MediaElementTracksStore` without Directfile feature"),ee(this.videoElement!==null,"Initializing `MediaElementTracksStore` on a disposed RxPlayer");let t=new pe.directfile.mediaElementTracksStore(this.videoElement);return this._priv_triggerEventIfNotStopped("availableAudioTracksChange",t.getAvailableAudioTracks(),e),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",t.getAvailableVideoTracks(),e),this._priv_triggerEventIfNotStopped("availableTextTracksChange",t.getAvailableTextTracks(),e),this._priv_triggerEventIfNotStopped("audioTrackChange",(r=t.getChosenAudioTrack())!=null?r:null,e),this._priv_triggerEventIfNotStopped("textTrackChange",(i=t.getChosenTextTrack())!=null?i:null,e),this._priv_triggerEventIfNotStopped("videoTrackChange",(o=t.getChosenVideoTrack())!=null?o:null,e),t.addEventListener("availableVideoTracksChange",a=>this.trigger("availableVideoTracksChange",a)),t.addEventListener("availableAudioTracksChange",a=>this.trigger("availableAudioTracksChange",a)),t.addEventListener("availableTextTracksChange",a=>this.trigger("availableTextTracksChange",a)),t.addEventListener("audioTrackChange",a=>this.trigger("audioTrackChange",a)),t.addEventListener("videoTrackChange",a=>this.trigger("videoTrackChange",a)),t.addEventListener("textTrackChange",a=>this.trigger("textTrackChange",a)),t}_priv_callTracksStoreGetterSetter(e,t,r){var d,u;if(this._priv_contentInfos===null||this._priv_contentInfos.tracksStore===null)return p.warn("API","Trying to call track API too soon"),t;let{tracksStore:i}=this._priv_contentInfos,o=(u=(d=this._priv_contentInfos)==null?void 0:d.currentPeriod)!=null?u:void 0,a=e!=null?e:o==null?void 0:o.id;if(a===void 0)return t;let s=a===(o==null?void 0:o.id)?i.getPeriodObjectFromPeriod(o):i.getPeriodObjectFromId(a);return s===void 0?t:r(i,s)}_priv_onAvailableTracksMayHaveChanged(e,t){let r=this._priv_contentInfos;if(r===null)return;let{currentPeriod:i,tracksStore:o,currentContentCanceller:a}=r,s=a.signal;if(_(i)||o===null)return;let d=t!=null?t:o.getPeriodObjectFromPeriod(i);if(d!==void 0)switch(e){case"video":{let u=o.getAvailableVideoTracks(d,!0);this._priv_triggerEventIfNotStopped("availableVideoTracksChange",u!=null?u:[],s);break}case"audio":{let u=o.getAvailableAudioTracks(d,!0);this._priv_triggerEventIfNotStopped("availableAudioTracksChange",u!=null?u:[],s);break}case"text":{let u=o.getAvailableTextTracks(d);this._priv_triggerEventIfNotStopped("availableTextTracksChange",u!=null?u:[],s);break}default:we(e)}}_priv_onFatalError(e,t){let r=Ae(e,{defaultCode:"NONE",defaultReason:"An unknown error stopped content playback."});r.fatal=!0,t.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this._priv_currentError=r,p.error("API","The player stopped because of an error",r),this._priv_setPlayerState("STOPPED"),this._priv_currentError===r&&this.trigger("error",r)}};nn._priv_currentlyUsedVideoElements=new WeakSet;var xr=nn;xr.version="4.4.1-dev.2025101500";var yg=xr;var Es=yg;vs();Es.addFeatures([uc,Zu,il,ol,Zl,jl,ec,Ql,Dl,ll,Wl,ml]);var lce=Es;Z.RxPlayer=Es;})();
|