@openlist-frontend/openlist-frontend 4.0.8 → 4.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VERSION +1 -1
- package/dist/assets/2fa-2cc2atzU.js +1 -0
- package/dist/assets/2fa-legacy-Bv6NDiiZ.js +1 -0
- package/dist/assets/About-Cu11TW0D.js +1 -0
- package/dist/assets/About-legacy-QsfCSVxq.js +1 -0
- package/dist/assets/AddOrEdit-B2PSnD-9.js +1 -0
- package/dist/assets/AddOrEdit-B7sPaR10.js +1 -0
- package/dist/assets/AddOrEdit-DKPH7EZ_.js +1 -0
- package/dist/assets/AddOrEdit-legacy-BLNrBEUZ.js +1 -0
- package/dist/assets/AddOrEdit-legacy-COHYBFCt.js +1 -0
- package/dist/assets/AddOrEdit-legacy-DxIDnAk7.js +1 -0
- package/dist/assets/Common-CrTYhaeL.js +1 -0
- package/dist/assets/Common-legacy-CYNGdYU-.js +1 -0
- package/dist/assets/Copy-CENvweJK.js +1 -0
- package/dist/assets/Copy-legacy-D_8otiMK.js +1 -0
- package/dist/assets/Decompress-CzLWbcw1.js +1 -0
- package/dist/assets/Decompress-legacy-Dv_Jku2u.js +1 -0
- package/dist/{lite/assets/DeletePopover-3f4b6f0c.js → assets/DeletePopover-BFBUMopn.js} +1 -1
- package/dist/assets/DeletePopover-legacy-BEDnzn-m.js +1 -0
- package/dist/assets/File-DOBK5V8m.js +2 -0
- package/dist/assets/File-legacy-D1ODACuv.js +1 -0
- package/dist/assets/Folder-CGWdNP6D.js +115 -0
- package/dist/assets/Folder-legacy-YsG9JF-C.js +43 -0
- package/dist/assets/{Folder-6651c4e8.css → Folder-pZUjROFs.css} +1 -1
- package/dist/assets/FolderTree-BopfuzE_.js +1 -0
- package/dist/assets/FolderTree-legacy-DH3Vf9XJ.js +1 -0
- package/dist/assets/Grid-DPqNI8Qb.js +1 -0
- package/dist/assets/Grid-legacy-BgCqAxPk.js +1 -0
- package/dist/assets/GridItem-DKsYPXRd.js +1 -0
- package/dist/assets/GridItem-legacy-B5BlOcYb.js +1 -0
- package/dist/assets/{ImageWithError-68cd8f3d.js → ImageWithError-gG_AK8KG.js} +1 -1
- package/dist/assets/ImageWithError-legacy-B07XhroH.js +1 -0
- package/dist/assets/Images-OiLzswiq.js +1 -0
- package/dist/assets/Images-legacy-ByM1mPR1.js +1 -0
- package/dist/assets/Layout-CyS6jJ_b.js +6 -0
- package/dist/assets/Layout-legacy-D9Zk98K6.js +6 -0
- package/dist/assets/List-CZc2zrbB.js +1 -0
- package/dist/assets/List-legacy-CFAZAIBP.js +1 -0
- package/dist/assets/Messenger-Dmz66wIv.js +1 -0
- package/dist/assets/Messenger-legacy-DEa2mtGl.js +1 -0
- package/dist/assets/Metas-BV8fZzUC.js +1 -0
- package/dist/assets/Metas-legacy-Dsed9U0b.js +1 -0
- package/dist/assets/Move-CjmsQ4oK.js +1 -0
- package/dist/assets/Move-legacy-BJYFMCwm.js +1 -0
- package/dist/assets/Other-DXc0kpSC.js +1 -0
- package/dist/assets/Other-legacy-38X7w6nZ.js +1 -0
- package/dist/assets/PackageDownload-CwKBLgrB.js +1 -0
- package/dist/assets/PackageDownload-legacy-DghWe59X.js +1 -0
- package/dist/{lite/assets/Paginator-c3098d6c.js → assets/Paginator-CfTq8QGy.js} +1 -1
- package/dist/assets/Paginator-legacy-BBwW9rLz.js +1 -0
- package/dist/assets/Password-_jCVU1BX.js +1 -0
- package/dist/assets/Password-legacy-B7VWpO0t.js +1 -0
- package/dist/{lite/assets/Profile-8a8de2b5.js → assets/Profile-DQqzso6r.js} +1 -1
- package/dist/assets/Profile-legacy-DxHXHWHS.js +1 -0
- package/dist/assets/PublicKeys-BUewmKb-.js +1 -0
- package/dist/assets/PublicKeys-legacy-L19QKXEm.js +1 -0
- package/dist/assets/ResponsiveGrid-DBqpPiu2.js +1 -0
- package/dist/assets/ResponsiveGrid-legacy-io27eqXp.js +1 -0
- package/dist/assets/S3-Ue8_AwRX.js +1 -0
- package/dist/assets/S3-legacy-BEIExV0a.js +1 -0
- package/dist/assets/SettingItem-CoyA-wst.js +1 -0
- package/dist/assets/SettingItem-legacy-FkrTuUbn.js +1 -0
- package/dist/assets/Storages-B0zOmRwd.js +1 -0
- package/dist/assets/Storages-legacy-CBl6TdCy.js +1 -0
- package/dist/assets/Upload-9DDOLajr.js +1 -0
- package/dist/assets/Upload-legacy-BX35PWMt.js +1 -0
- package/dist/assets/Upload-legacy-uISx3f64.js +6 -0
- package/dist/assets/Upload-y6lHsBbS.js +5 -0
- package/dist/assets/Users-BNQGZuWH.js +1 -0
- package/dist/assets/Users-legacy-BINPeiuk.js +1 -0
- package/dist/assets/Wether-enRDnS5x.js +1 -0
- package/dist/assets/Wether-legacy-CUYxMAIK.js +1 -0
- package/dist/assets/aliyun_office-4kFcJSQ7.js +1 -0
- package/dist/assets/aliyun_office-legacy-CeoV_l42.js +1 -0
- package/dist/assets/aliyun_video-CwA2k3Pu.js +1 -0
- package/dist/assets/aliyun_video-legacy-BpsCIyHp.js +1 -0
- package/dist/assets/archive-96T1hx83.js +1 -0
- package/dist/assets/archive-legacy-DNLQfLr5.js +1 -0
- package/dist/assets/asciinema-CyHXgEN-.js +1 -0
- package/dist/assets/asciinema-legacy-t3iZqcax.js +1 -0
- package/dist/assets/audio-DSt_Oo19.js +1 -0
- package/dist/assets/{audio-43f4c02b.css → audio-DVCFhzL6.css} +1 -1
- package/dist/assets/audio-legacy-BhsBrhkI.js +1 -0
- package/dist/assets/{backup-restore-29d85261.js → backup-restore-C5uaukNL.js} +1 -1
- package/dist/assets/backup-restore-legacy-BNzSREad.js +1 -0
- package/dist/assets/entry-8adOMWDV.js +1 -0
- package/dist/assets/entry-CzYCw4_c.js +1 -0
- package/dist/assets/entry-legacy-BJi3IsKO.js +1 -0
- package/dist/assets/entry-legacy-CPgG9LS1.js +1 -0
- package/dist/assets/flash-Be81XNne.js +1 -0
- package/dist/assets/flash-legacy-CPqjLHQp.js +1 -0
- package/dist/assets/heic-DpvwRot7.js +1 -0
- package/dist/assets/heic-legacy-BoU2N_4X.js +1 -0
- package/dist/assets/helper-CJdkogiC.js +1 -0
- package/dist/assets/helper-Ha9z54Sm.js +1 -0
- package/dist/assets/helper-legacy-B4Xut8Z5.js +1 -0
- package/dist/assets/helper-legacy-CiLX6aDH.js +1 -0
- package/dist/assets/hls-CdGSrFYh.js +6 -0
- package/dist/assets/hls-legacy-BR5PAXA5.js +8 -0
- package/dist/{lite/assets/html-d9eda13c.js → assets/html-CBeb2Gu_.js} +1 -1
- package/dist/assets/html-legacy-DS9vIClh.js +1 -0
- package/dist/{lite/assets/icon-8ed847e0.js → assets/icon-CgK9sKtW.js} +1 -1
- package/dist/assets/icon-legacy-jbuQXJrW.js +1 -0
- package/dist/assets/image-DK0tWDig.js +1 -0
- package/dist/assets/image-legacy-BpyMVaKK.js +1 -0
- package/dist/assets/index-BClBcNEu.js +1 -0
- package/dist/assets/index-BJaZW_cl.js +1 -0
- package/dist/assets/index-BS5bVjs5.js +14 -0
- package/dist/{lite/assets/index-33b93a25.js → assets/index-C7ih00qx.js} +1 -1
- package/dist/assets/index-CSwg5QXS.js +21 -0
- package/dist/assets/index-D0sWo-se.js +2 -0
- package/dist/{lite/assets/index-b9aeabe6.js → assets/index-DNDW0loe.js} +1 -1
- package/dist/assets/{index-28621b75.js → index-DOY4u_GJ.js} +1 -1
- package/dist/{lite/assets/index-20d85525.js → assets/index-DV8SB530.js} +1 -1
- package/dist/assets/{index-1c55bc21.js → index-DqW5xUnX.js} +1 -1
- package/dist/assets/index-legacy-BYcwzmYP.js +1 -0
- package/dist/assets/index-legacy-C5X1tU4Z.js +1 -0
- package/dist/assets/index-legacy-CDfFAMGs.js +18 -0
- package/dist/assets/index-legacy-CtC7fn6O.js +28 -0
- package/dist/assets/index-legacy-Ctuk5AXi.js +1 -0
- package/dist/assets/index-legacy-CwvCVg8-.js +1 -0
- package/dist/assets/index-legacy-DIduvs2M.js +1 -0
- package/dist/assets/index-legacy-DkZZKHvO.js +1 -0
- package/dist/assets/index-legacy-nH7bmAdo.js +1 -0
- package/dist/assets/index-legacy-zjwrrR91.js +1 -0
- package/dist/assets/indexes-Ba0IqlDk.js +1 -0
- package/dist/assets/indexes-legacy-DOV4Irpp.js +1 -0
- package/dist/assets/ipa-CThENlHd.js +1 -0
- package/dist/assets/ipa-legacy-ruQ-749T.js +1 -0
- package/dist/assets/item_type-legacy-NfhfVKtF.js +1 -0
- package/dist/assets/markdown-DAEQr1YU.js +1 -0
- package/dist/assets/markdown-legacy-DtXqlrxB.js +1 -0
- package/dist/assets/markdown_with_word_wrap-D_gGyBgt.js +1 -0
- package/dist/assets/markdown_with_word_wrap-legacy-D-tfNhGw.js +1 -0
- package/dist/assets/offline_download--qix7jck.js +1 -0
- package/dist/assets/offline_download-legacy-TAKRiM_z.js +1 -0
- package/dist/assets/pdf-ClWVlnx_.css +1 -0
- package/dist/assets/pdf-DS1TLqP2.js +1 -0
- package/dist/assets/pdf-legacy-BF9lSw5M.js +45 -0
- package/dist/assets/pdf.worker.min--PgD6g2g.mjs +29 -0
- package/dist/assets/plist-BdQrMloW.js +1 -0
- package/dist/assets/plist-legacy-Dzyq_tdc.js +1 -0
- package/dist/assets/polyfills-legacy-BPfokQaO.js +4 -0
- package/dist/assets/style-QIM1DiTv.js +1 -0
- package/dist/assets/style-legacy-DqRFDAwL.js +1 -0
- package/dist/assets/text-editor-BvoSciLk.js +1 -0
- package/dist/assets/text-editor-legacy-AXNOcpgF.js +1 -0
- package/dist/assets/url-BdlNs2qR.js +1 -0
- package/dist/assets/url-legacy-BObEvUIa.js +1 -0
- package/dist/assets/useTitle-DVdBzpBf.js +1 -0
- package/dist/assets/useTitle-legacy-CeyL-0_E.js +1 -0
- package/dist/assets/video-legacy-DYsnLlgJ.js +9 -0
- package/dist/assets/video-oPytqEM3.js +7 -0
- package/dist/assets/video360-Ceo5Bzr3.js +14 -0
- package/dist/assets/video360-legacy-DKyKnnjk.js +16 -0
- package/dist/assets/video_box-BSgDB9Qt.js +6 -0
- package/dist/assets/video_box-legacy-OIbbmS-k.js +8 -0
- package/dist/assets/webauthn-json.browser-ponyfill-legacy-8XJfKV2b.js +1 -0
- package/dist/i18n.tar.gz +0 -0
- package/dist/index.html +5 -12
- package/dist/lite/VERSION +1 -1
- package/dist/{assets/2fa-a72b4715.js → lite/assets/2fa-d2e88785.js} +1 -1
- package/dist/lite/assets/{2fa-legacy-f4a3c66e.js → 2fa-legacy-300dfa68.js} +1 -1
- package/dist/lite/assets/{About-c3533dad.js → About-e76de340.js} +1 -1
- package/dist/lite/assets/{About-legacy-b3d32972.js → About-legacy-79773dac.js} +1 -1
- package/dist/{assets/AddOrEdit-2fb78319.js → lite/assets/AddOrEdit-3d3353a8.js} +1 -1
- package/dist/{assets/AddOrEdit-ebf26454.js → lite/assets/AddOrEdit-807696e5.js} +1 -1
- package/dist/{assets/AddOrEdit-6afe733d.js → lite/assets/AddOrEdit-d6caff63.js} +1 -1
- package/dist/{assets/AddOrEdit-legacy-2e67af62.js → lite/assets/AddOrEdit-legacy-8f86f1ff.js} +1 -1
- package/dist/{assets/AddOrEdit-legacy-9f2cfa89.js → lite/assets/AddOrEdit-legacy-9983f6e1.js} +1 -1
- package/dist/{assets/AddOrEdit-legacy-c911adf1.js → lite/assets/AddOrEdit-legacy-d0c7c380.js} +1 -1
- package/dist/{assets/Common-08508a3b.js → lite/assets/Common-9c9167f7.js} +1 -1
- package/dist/{assets/Common-legacy-a3575a78.js → lite/assets/Common-legacy-d52fea2b.js} +1 -1
- package/dist/{assets/Copy-c2117fe7.js → lite/assets/Copy-104d7d48.js} +1 -1
- package/dist/{assets/Copy-legacy-e39ace5c.js → lite/assets/Copy-legacy-e1bce4e6.js} +1 -1
- package/dist/lite/assets/Decompress-62fd7241.js +1 -0
- package/dist/{assets/Decompress-legacy-2ff979ff.js → lite/assets/Decompress-legacy-bd78eb4f.js} +1 -1
- package/dist/{assets/DeletePopover-c03b1fef.js → lite/assets/DeletePopover-239d6d9d.js} +1 -1
- package/dist/{assets/DeletePopover-legacy-8685d821.js → lite/assets/DeletePopover-legacy-f4764c72.js} +1 -1
- package/dist/{assets/File-264b5b16.js → lite/assets/File-9bb7b3b6.js} +1 -1
- package/dist/{assets/File-legacy-e47607a5.js → lite/assets/File-legacy-dbaad256.js} +1 -1
- package/dist/{assets/Folder-d756e407.js → lite/assets/Folder-80505a0c.js} +2 -2
- package/dist/lite/assets/{Folder-legacy-70662013.js → Folder-legacy-dbe7957d.js} +2 -2
- package/dist/{assets/FolderTree-38bc15c1.js → lite/assets/FolderTree-a7545b65.js} +1 -1
- package/dist/{assets/FolderTree-legacy-89560a13.js → lite/assets/FolderTree-legacy-cc6e2591.js} +1 -1
- package/dist/lite/assets/Grid-2ea09356.js +1 -0
- package/dist/{assets/Grid-legacy-ee498cc7.js → lite/assets/Grid-legacy-7e146882.js} +1 -1
- package/dist/{assets/GridItem-bfb91371.js → lite/assets/GridItem-a16cc1c5.js} +1 -1
- package/dist/{assets/GridItem-legacy-4d40ae3a.js → lite/assets/GridItem-legacy-3d2048e2.js} +1 -1
- package/dist/lite/assets/{ImageWithError-d807b9e7.js → ImageWithError-7a45dab8.js} +1 -1
- package/dist/{assets/ImageWithError-legacy-ebd17802.js → lite/assets/ImageWithError-legacy-c2f680e8.js} +1 -1
- package/dist/{assets/Images-6acc10fb.js → lite/assets/Images-137f7509.js} +1 -1
- package/dist/{assets/Images-legacy-45ded7bb.js → lite/assets/Images-legacy-a43b6098.js} +1 -1
- package/dist/lite/assets/{Layout-3c582817.js → Layout-ac0937fd.js} +2 -2
- package/dist/lite/assets/{Layout-legacy-375987e2.js → Layout-legacy-0be654c6.js} +2 -2
- package/dist/lite/assets/{List-4ad75e81.js → List-64c7752c.js} +1 -1
- package/dist/{assets/List-legacy-632eca8c.js → lite/assets/List-legacy-913c133e.js} +1 -1
- package/dist/{assets/Messenger-d815729f.js → lite/assets/Messenger-254abffb.js} +1 -1
- package/dist/{assets/Messenger-legacy-c3d8cd3d.js → lite/assets/Messenger-legacy-97283620.js} +1 -1
- package/dist/{assets/Metas-0f480616.js → lite/assets/Metas-1bad1832.js} +1 -1
- package/dist/{assets/Metas-legacy-f0b124bf.js → lite/assets/Metas-legacy-7042cb89.js} +1 -1
- package/dist/lite/assets/{Other-00b9930f.js → Other-29b70647.js} +1 -1
- package/dist/{assets/Other-legacy-b460fc03.js → lite/assets/Other-legacy-607dbff6.js} +1 -1
- package/dist/{assets/PackageDownload-7f578964.js → lite/assets/PackageDownload-e264bfda.js} +1 -1
- package/dist/{assets/PackageDownload-legacy-593caa26.js → lite/assets/PackageDownload-legacy-55a29bc7.js} +1 -1
- package/dist/{assets/Paginator-98de1ee2.js → lite/assets/Paginator-c6bbb723.js} +1 -1
- package/dist/{assets/Paginator-legacy-10b3fbff.js → lite/assets/Paginator-legacy-612bab7f.js} +1 -1
- package/dist/{assets/Password-5ce6c2ad.js → lite/assets/Password-647ac2f5.js} +1 -1
- package/dist/{assets/Password-legacy-7e0b2348.js → lite/assets/Password-legacy-2e2010d5.js} +1 -1
- package/dist/{assets/Profile-17861eac.js → lite/assets/Profile-8e13fe60.js} +1 -1
- package/dist/{assets/Profile-legacy-4989c4d9.js → lite/assets/Profile-legacy-93d7fe2b.js} +1 -1
- package/dist/{assets/PublicKeys-0e4bffac.js → lite/assets/PublicKeys-7daab5c3.js} +1 -1
- package/dist/{assets/PublicKeys-legacy-6d0843b9.js → lite/assets/PublicKeys-legacy-83570ba5.js} +1 -1
- package/dist/{assets/ResponsiveGrid-5a4c915d.js → lite/assets/ResponsiveGrid-f263846b.js} +1 -1
- package/dist/{assets/ResponsiveGrid-legacy-80e737b7.js → lite/assets/ResponsiveGrid-legacy-a8200443.js} +1 -1
- package/dist/{assets/S3-fe6c8346.js → lite/assets/S3-40b2a439.js} +1 -1
- package/dist/{assets/S3-legacy-3c0dad4a.js → lite/assets/S3-legacy-310983e4.js} +1 -1
- package/dist/{assets/SettingItem-adba4a3c.js → lite/assets/SettingItem-72aa2179.js} +1 -1
- package/dist/lite/assets/{SettingItem-legacy-8fa7ceee.js → SettingItem-legacy-91ff3c53.js} +1 -1
- package/dist/lite/assets/{Storages-7d1f6f4c.js → Storages-90b21781.js} +1 -1
- package/dist/lite/assets/{Storages-legacy-87c1aeaf.js → Storages-legacy-49b7b995.js} +1 -1
- package/dist/{assets/Upload-eeaf4087.js → lite/assets/Upload-9447b1be.js} +1 -1
- package/dist/lite/assets/Upload-98dd51d8.js +1 -0
- package/dist/{assets/Upload-legacy-3bf6195e.js → lite/assets/Upload-legacy-3b92717c.js} +1 -1
- package/dist/{assets/Upload-legacy-9f558368.js → lite/assets/Upload-legacy-ac99e541.js} +1 -1
- package/dist/{assets/Users-23b18c29.js → lite/assets/Users-30333127.js} +1 -1
- package/dist/{assets/Users-legacy-e730c73c.js → lite/assets/Users-legacy-0719c277.js} +1 -1
- package/dist/{assets/Wether-3da294bf.js → lite/assets/Wether-b430b024.js} +1 -1
- package/dist/{assets/Wether-legacy-2e3f281c.js → lite/assets/Wether-legacy-274cd4f2.js} +1 -1
- package/dist/{assets/aliyun_office-f5fe6e23.js → lite/assets/aliyun_office-b0b45663.js} +1 -1
- package/dist/{assets/aliyun_office-legacy-8a2e05ca.js → lite/assets/aliyun_office-legacy-2d148972.js} +1 -1
- package/dist/lite/assets/{aliyun_video-ee95dc8b.js → aliyun_video-b2790a1e.js} +1 -1
- package/dist/lite/assets/{aliyun_video-legacy-31115588.js → aliyun_video-legacy-6a647909.js} +1 -1
- package/dist/{assets/archive-ae46c357.js → lite/assets/archive-25c8ef3b.js} +1 -1
- package/dist/{assets/archive-legacy-b3ff5d8d.js → lite/assets/archive-legacy-348dc806.js} +1 -1
- package/dist/lite/assets/{asciinema-fe43c4de.js → asciinema-03a03960.js} +1 -1
- package/dist/lite/assets/{asciinema-legacy-26fe007d.js → asciinema-legacy-1917d686.js} +1 -1
- package/dist/{assets/audio-0f7aceb6.js → lite/assets/audio-ea14d1c5.js} +1 -1
- package/dist/lite/assets/{audio-legacy-aa1eb5e2.js → audio-legacy-303c3bd9.js} +1 -1
- package/dist/lite/assets/{backup-restore-9f749076.js → backup-restore-a1922c8b.js} +1 -1
- package/dist/{assets/backup-restore-legacy-caa2e5b5.js → lite/assets/backup-restore-legacy-d4b0f25c.js} +1 -1
- package/dist/lite/assets/entry-27030f25.js +1 -0
- package/dist/lite/assets/{entry-0fbc9799.js → entry-f2e52067.js} +1 -1
- package/dist/lite/assets/entry-legacy-a1d93529.js +1 -0
- package/dist/lite/assets/{entry-legacy-239f65b7.js → entry-legacy-fd98eab3.js} +1 -1
- package/dist/lite/assets/{flash-dcb20462.js → flash-9e68a05e.js} +1 -1
- package/dist/lite/assets/{flash-legacy-f9cc246b.js → flash-legacy-80373572.js} +1 -1
- package/dist/lite/assets/{heic-356e8ae5.js → heic-2554ec65.js} +1 -1
- package/dist/lite/assets/{heic-legacy-7de73348.js → heic-legacy-2c1c78ca.js} +1 -1
- package/dist/lite/assets/{helper-6892d285.js → helper-59016ddf.js} +1 -1
- package/dist/lite/assets/{helper-e0625279.js → helper-af29c315.js} +1 -1
- package/dist/lite/assets/{helper-legacy-444fd020.js → helper-legacy-25bddff0.js} +1 -1
- package/dist/lite/assets/{helper-legacy-786f548e.js → helper-legacy-94b49e67.js} +1 -1
- package/dist/lite/assets/{hls-ff8f0581.js → hls-e031156d.js} +1 -1
- package/dist/lite/assets/{hls-legacy-220a34f1.js → hls-legacy-20bdc1ee.js} +1 -1
- package/dist/{assets/html-d76a8825.js → lite/assets/html-a748c03a.js} +1 -1
- package/dist/lite/assets/{html-legacy-cb4900ab.js → html-legacy-619368c0.js} +1 -1
- package/dist/{assets/icon-f5684a02.js → lite/assets/icon-cb9eb834.js} +1 -1
- package/dist/lite/assets/{icon-legacy-f861f3b7.js → icon-legacy-eb0f5143.js} +1 -1
- package/dist/{assets/image-1f93bea5.js → lite/assets/image-c8b0bac2.js} +1 -1
- package/dist/{assets/image-legacy-1e62d306.js → lite/assets/image-legacy-7afc3d49.js} +1 -1
- package/dist/{assets/index-3e5fce2e.js → lite/assets/index-3f395f83.js} +1 -1
- package/dist/lite/assets/{index-08c85108.js → index-53a1dd81.js} +2 -2
- package/dist/lite/assets/{index-36b137eb.js → index-67a90f4f.js} +1 -1
- package/dist/lite/assets/{index-b7fdfaa2.js → index-6a28cbb7.js} +1 -1
- package/dist/lite/assets/{index-7c360a8c.js → index-83750b21.js} +1 -1
- package/dist/lite/assets/{index-92115809.js → index-9d2d674f.js} +1 -1
- package/dist/{assets/index-38e5ef5e.js → lite/assets/index-a14fae00.js} +1 -1
- package/dist/{assets/index-ee5f30ed.js → lite/assets/index-b8211a8c.js} +1 -1
- package/dist/lite/assets/{index-818913fd.js → index-b94004c5.js} +1 -1
- package/dist/{assets/index-67f967f8.js → lite/assets/index-dfffd899.js} +1 -1
- package/dist/{assets/index-legacy-3958848d.js → lite/assets/index-legacy-17656f04.js} +1 -1
- package/dist/{assets/index-legacy-473bb759.js → lite/assets/index-legacy-3d6bd4ab.js} +1 -1
- package/dist/lite/assets/{index-legacy-3f94eb41.js → index-legacy-52bb5f2d.js} +1 -1
- package/dist/lite/assets/{index-legacy-fea9c750.js → index-legacy-6dddbd7f.js} +1 -1
- package/dist/lite/assets/{index-legacy-44c019b6.js → index-legacy-737b5776.js} +1 -1
- package/dist/lite/assets/{index-legacy-feaa5c7a.js → index-legacy-a79f37d7.js} +3 -3
- package/dist/lite/assets/{index-legacy-e86d8f5e.js → index-legacy-b6946699.js} +1 -1
- package/dist/lite/assets/{index-legacy-5411e13c.js → index-legacy-d4734338.js} +1 -1
- package/dist/{assets/index-legacy-7e0ea74f.js → lite/assets/index-legacy-e78804fc.js} +1 -1
- package/dist/{assets/index-legacy-b4cf68b0.js → lite/assets/index-legacy-e78c6961.js} +1 -1
- package/dist/{assets/indexes-01316ac5.js → lite/assets/indexes-8d6a3830.js} +1 -1
- package/dist/lite/assets/{indexes-legacy-4d25163f.js → indexes-legacy-8aad9cf2.js} +1 -1
- package/dist/{assets/ipa-a2de0db0.js → lite/assets/ipa-14799eac.js} +1 -1
- package/dist/{assets/ipa-legacy-ceccd6b2.js → lite/assets/ipa-legacy-05317cab.js} +1 -1
- package/dist/{assets/markdown-04584d95.js → lite/assets/markdown-438acebf.js} +1 -1
- package/dist/{assets/markdown-legacy-2215a7c4.js → lite/assets/markdown-legacy-85cc7347.js} +1 -1
- package/dist/{assets/markdown_with_word_wrap-5b0da5e4.js → lite/assets/markdown_with_word_wrap-02b3d898.js} +1 -1
- package/dist/{assets/markdown_with_word_wrap-legacy-01adf91e.js → lite/assets/markdown_with_word_wrap-legacy-c80bbc34.js} +1 -1
- package/dist/lite/assets/offline_download-64a4f5ec.js +1 -0
- package/dist/{assets/offline_download-legacy-b10720ca.js → lite/assets/offline_download-legacy-13c80c46.js} +1 -1
- package/dist/lite/assets/plist-caa63a1c.js +1 -0
- package/dist/{assets/plist-legacy-99bde99f.js → lite/assets/plist-legacy-97df7129.js} +1 -1
- package/dist/lite/assets/{polyfills-legacy-fa59231c.js → polyfills-legacy-84c7163c.js} +1 -1
- package/dist/{assets/style-cd7664ed.js → lite/assets/style-da60bdcd.js} +1 -1
- package/dist/lite/assets/{style-legacy-1408fde5.js → style-legacy-56f6ffc2.js} +1 -1
- package/dist/lite/assets/{text-editor-b327845b.js → text-editor-faffc12e.js} +1 -1
- package/dist/{assets/text-editor-legacy-aed12f79.js → lite/assets/text-editor-legacy-c28b9e68.js} +1 -1
- package/dist/{assets/url-d09b1363.js → lite/assets/url-e7419bc0.js} +1 -1
- package/dist/lite/assets/{url-legacy-c6cbcba2.js → url-legacy-c605c2b3.js} +1 -1
- package/dist/{assets/useTitle-398aa263.js → lite/assets/useTitle-3c39724b.js} +1 -1
- package/dist/{assets/useTitle-legacy-2113db51.js → lite/assets/useTitle-legacy-f359aa82.js} +1 -1
- package/dist/{assets/video-0b7a76cf.js → lite/assets/video-bdb2443b.js} +1 -1
- package/dist/{assets/video-legacy-00d99ed3.js → lite/assets/video-legacy-aaca36d8.js} +1 -1
- package/dist/lite/assets/{video360-18a4e692.js → video360-8fe849f4.js} +1 -1
- package/dist/{assets/video360-legacy-4aa0aa33.js → lite/assets/video360-legacy-60cbacb5.js} +1 -1
- package/dist/{assets/video_box-9bb05edf.js → lite/assets/video_box-cfac536c.js} +1 -1
- package/dist/lite/assets/{video_box-legacy-975dfba8.js → video_box-legacy-6b3ebc5b.js} +1 -1
- package/dist/lite/i18n.tar.gz +0 -0
- package/dist/lite/index.html +3 -3
- package/dist/static/manifest.json +1 -1
- package/package.json +20 -18
- package/dist/assets/2fa-legacy-7c36ddda.js +0 -1
- package/dist/assets/About-4a3b9d24.js +0 -1
- package/dist/assets/About-legacy-bc58c6d4.js +0 -1
- package/dist/assets/Decompress-d15eabb0.js +0 -1
- package/dist/assets/Folder-legacy-53bc447b.js +0 -49
- package/dist/assets/Grid-45614e4a.js +0 -1
- package/dist/assets/Layout-d9fa1abd.js +0 -5
- package/dist/assets/Layout-legacy-6f4e2a0b.js +0 -6
- package/dist/assets/List-c82f9a79.js +0 -1
- package/dist/assets/Other-c559e5c1.js +0 -1
- package/dist/assets/SettingItem-legacy-6ce789b5.js +0 -1
- package/dist/assets/Storages-ff9a5d63.js +0 -1
- package/dist/assets/Storages-legacy-522d828e.js +0 -1
- package/dist/assets/Upload-a344c973.js +0 -1
- package/dist/assets/aliyun_video-1a5a17b0.js +0 -1
- package/dist/assets/aliyun_video-legacy-8072ba6a.js +0 -1
- package/dist/assets/asciinema-c3b7b1c1.js +0 -1
- package/dist/assets/asciinema-legacy-8421ca13.js +0 -1
- package/dist/assets/audio-legacy-0ba1ed4a.js +0 -1
- package/dist/assets/entry-4ea86138.js +0 -1
- package/dist/assets/entry-bef6a8ee.js +0 -1
- package/dist/assets/entry-legacy-115956ab.js +0 -1
- package/dist/assets/entry-legacy-9c720a1a.js +0 -1
- package/dist/assets/flash-e002e34f.js +0 -1
- package/dist/assets/flash-legacy-d245ee99.js +0 -1
- package/dist/assets/heic-07274d7e.js +0 -1
- package/dist/assets/heic-legacy-eb6280e1.js +0 -1
- package/dist/assets/helper-90762263.js +0 -1
- package/dist/assets/helper-d1cac093.js +0 -1
- package/dist/assets/helper-legacy-71d65e20.js +0 -1
- package/dist/assets/helper-legacy-e100c21e.js +0 -1
- package/dist/assets/hls-d1eff9e4.js +0 -6
- package/dist/assets/hls-legacy-709b904e.js +0 -8
- package/dist/assets/html-legacy-24a853e8.js +0 -1
- package/dist/assets/icon-legacy-e0cb4739.js +0 -1
- package/dist/assets/index-6408827f.js +0 -1
- package/dist/assets/index-7b587c0b.js +0 -20
- package/dist/assets/index-9090d18f.js +0 -1
- package/dist/assets/index-ccdd6f88.js +0 -1
- package/dist/assets/index-legacy-0987c205.js +0 -27
- package/dist/assets/index-legacy-1fcc5cbf.js +0 -1
- package/dist/assets/index-legacy-38640f98.js +0 -18
- package/dist/assets/index-legacy-3fb7c085.js +0 -1
- package/dist/assets/index-legacy-5b16ff88.js +0 -1
- package/dist/assets/index-legacy-ff06d38e.js +0 -1
- package/dist/assets/indexes-legacy-62be9b08.js +0 -1
- package/dist/assets/item_type-legacy-d49ae974.js +0 -1
- package/dist/assets/offline_download-50c7bca8.js +0 -1
- package/dist/assets/plist-7050baba.js +0 -1
- package/dist/assets/polyfills-legacy-fa59231c.js +0 -1
- package/dist/assets/style-legacy-3e5c71ad.js +0 -1
- package/dist/assets/text-editor-0e6ea6b2.js +0 -1
- package/dist/assets/url-legacy-be90fc20.js +0 -1
- package/dist/assets/video360-b962f1d3.js +0 -14
- package/dist/assets/video_box-legacy-dafbf901.js +0 -8
- package/dist/assets/webauthn-json.browser-ponyfill-legacy-456cc8e1.js +0 -1
- package/dist/lite/assets/2fa-ede593c5.js +0 -1
- package/dist/lite/assets/AddOrEdit-0f126e63.js +0 -1
- package/dist/lite/assets/AddOrEdit-df1e7dee.js +0 -1
- package/dist/lite/assets/AddOrEdit-fc23ad8d.js +0 -1
- package/dist/lite/assets/AddOrEdit-legacy-13d629fc.js +0 -1
- package/dist/lite/assets/AddOrEdit-legacy-83178d15.js +0 -1
- package/dist/lite/assets/AddOrEdit-legacy-a76d4c93.js +0 -1
- package/dist/lite/assets/Common-841290ec.js +0 -1
- package/dist/lite/assets/Common-legacy-ed0cdb81.js +0 -1
- package/dist/lite/assets/Copy-aa61a47c.js +0 -1
- package/dist/lite/assets/Copy-legacy-d4755c20.js +0 -1
- package/dist/lite/assets/Decompress-02eb0d77.js +0 -1
- package/dist/lite/assets/Decompress-legacy-40f7da72.js +0 -1
- package/dist/lite/assets/DeletePopover-legacy-defe79f5.js +0 -1
- package/dist/lite/assets/File-9b37c270.js +0 -1
- package/dist/lite/assets/File-legacy-d7677503.js +0 -1
- package/dist/lite/assets/Folder-774967e6.js +0 -114
- package/dist/lite/assets/FolderTree-f854d472.js +0 -1
- package/dist/lite/assets/FolderTree-legacy-21474e09.js +0 -1
- package/dist/lite/assets/Grid-c86225e4.js +0 -1
- package/dist/lite/assets/Grid-legacy-08e4c5b1.js +0 -1
- package/dist/lite/assets/GridItem-d3bbbd00.js +0 -1
- package/dist/lite/assets/GridItem-legacy-5f3bf259.js +0 -1
- package/dist/lite/assets/ImageWithError-legacy-130943d6.js +0 -1
- package/dist/lite/assets/Images-afaffe06.js +0 -1
- package/dist/lite/assets/Images-legacy-15c54b97.js +0 -1
- package/dist/lite/assets/List-legacy-a0c286d9.js +0 -1
- package/dist/lite/assets/Messenger-87c4fea9.js +0 -1
- package/dist/lite/assets/Messenger-legacy-2106df19.js +0 -1
- package/dist/lite/assets/Metas-43a08990.js +0 -1
- package/dist/lite/assets/Metas-legacy-9d82646c.js +0 -1
- package/dist/lite/assets/Other-legacy-88593fbd.js +0 -1
- package/dist/lite/assets/PackageDownload-a3350622.js +0 -1
- package/dist/lite/assets/PackageDownload-legacy-c9ad47f0.js +0 -1
- package/dist/lite/assets/Paginator-legacy-3a65b711.js +0 -1
- package/dist/lite/assets/Password-09c6e3b0.js +0 -1
- package/dist/lite/assets/Password-legacy-42da1978.js +0 -1
- package/dist/lite/assets/Profile-legacy-d3f9ade2.js +0 -1
- package/dist/lite/assets/PublicKeys-4a58bf50.js +0 -1
- package/dist/lite/assets/PublicKeys-legacy-3217939a.js +0 -1
- package/dist/lite/assets/ResponsiveGrid-fee7beb8.js +0 -1
- package/dist/lite/assets/ResponsiveGrid-legacy-f4def112.js +0 -1
- package/dist/lite/assets/S3-42185603.js +0 -1
- package/dist/lite/assets/S3-legacy-ce296b98.js +0 -1
- package/dist/lite/assets/SettingItem-32894894.js +0 -1
- package/dist/lite/assets/Upload-168fb9cf.js +0 -5
- package/dist/lite/assets/Upload-32f346e9.js +0 -1
- package/dist/lite/assets/Upload-legacy-504ab23f.js +0 -1
- package/dist/lite/assets/Upload-legacy-bea3866d.js +0 -6
- package/dist/lite/assets/Users-975e4ae4.js +0 -1
- package/dist/lite/assets/Users-legacy-a34f2e99.js +0 -1
- package/dist/lite/assets/Wether-600ba8a4.js +0 -1
- package/dist/lite/assets/Wether-legacy-d52ccde3.js +0 -1
- package/dist/lite/assets/aliyun_office-9ab080dc.js +0 -1
- package/dist/lite/assets/aliyun_office-legacy-bc40aa62.js +0 -1
- package/dist/lite/assets/archive-09e697d5.js +0 -1
- package/dist/lite/assets/archive-legacy-37a0d5db.js +0 -1
- package/dist/lite/assets/audio-dd4b2c62.js +0 -1
- package/dist/lite/assets/backup-restore-legacy-1987a6e9.js +0 -1
- package/dist/lite/assets/entry-dadcc45c.js +0 -1
- package/dist/lite/assets/entry-legacy-65e1bc60.js +0 -1
- package/dist/lite/assets/image-3859f55a.js +0 -1
- package/dist/lite/assets/image-legacy-bdc2c82d.js +0 -1
- package/dist/lite/assets/index-bfa58d6e.js +0 -14
- package/dist/lite/assets/index-legacy-49f0fd77.js +0 -1
- package/dist/lite/assets/index-legacy-73db2dba.js +0 -1
- package/dist/lite/assets/index-legacy-d67d5c5d.js +0 -1
- package/dist/lite/assets/index-legacy-ee4ae549.js +0 -1
- package/dist/lite/assets/indexes-2fde0a43.js +0 -1
- package/dist/lite/assets/ipa-fdd73bb4.js +0 -1
- package/dist/lite/assets/ipa-legacy-6939e65c.js +0 -1
- package/dist/lite/assets/markdown-0af76e6f.js +0 -1
- package/dist/lite/assets/markdown-legacy-b30e0cc6.js +0 -1
- package/dist/lite/assets/markdown_with_word_wrap-04998301.js +0 -1
- package/dist/lite/assets/markdown_with_word_wrap-legacy-12f676af.js +0 -1
- package/dist/lite/assets/offline_download-a0194aa7.js +0 -1
- package/dist/lite/assets/offline_download-legacy-61e78511.js +0 -1
- package/dist/lite/assets/plist-03f81ce6.js +0 -1
- package/dist/lite/assets/plist-legacy-8b5e0fc5.js +0 -1
- package/dist/lite/assets/style-40d992b8.js +0 -1
- package/dist/lite/assets/text-editor-legacy-9877f1df.js +0 -1
- package/dist/lite/assets/url-d50e0ae2.js +0 -1
- package/dist/lite/assets/useTitle-decc7f71.js +0 -1
- package/dist/lite/assets/useTitle-legacy-57ec27a3.js +0 -1
- package/dist/lite/assets/video-10d16623.js +0 -7
- package/dist/lite/assets/video-legacy-93ef0811.js +0 -9
- package/dist/lite/assets/video360-legacy-bd7bb7d3.js +0 -16
- package/dist/lite/assets/video_box-4b84e096.js +0 -6
- /package/dist/assets/{SourceHanSansCN-Bold-b5627435.woff2 → SourceHanSansCN-Bold-ufPDHtmM.woff2} +0 -0
- /package/dist/assets/{TimesNewRoman-d9fb32eb.ttf → TimesNewRoman-CJFXaXxy.ttf} +0 -0
- /package/dist/assets/{asciinema-9107553b.css → asciinema-CxBn2iyI.css} +0 -0
- /package/dist/assets/{index-c0564af7.css → index-DYLAoZjS.css} +0 -0
- /package/dist/assets/{item_type-32dc6fdf.js → item_type-CV3e5W3l.js} +0 -0
- /package/dist/assets/{lg-f2fe1c00.svg → lg-B0dIV2BS.svg} +0 -0
- /package/dist/assets/{lg-fefc5c0d.woff → lg-CosQH4Cu.woff} +0 -0
- /package/dist/assets/{lg-22b72ba5.ttf → lg-oyjwlqP2.ttf} +0 -0
- /package/dist/assets/{loading-298ad3ff.gif → loading-BZOHaeKn.gif} +0 -0
- /package/dist/assets/{style-a6d16836.css → style-qq4T_k44.css} +0 -0
- /package/dist/assets/{subtitles-octopus-worker-f95f2186.js → subtitles-octopus-worker-BE_B0Qbi.js} +0 -0
- /package/dist/assets/{subtitles-octopus-worker-62892886.wasm → subtitles-octopus-worker-DBPz2dPT.wasm} +0 -0
- /package/dist/assets/{video360-f0192288.css → video360-Cpoa0Nlv.css} +0 -0
- /package/dist/assets/{webauthn-json.browser-ponyfill-29d8152c.js → webauthn-json.browser-ponyfill-CVZeZdny.js} +0 -0
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{cB as Xr,cA as Oi}from"./index-7b587c0b.js";import{a as Fi}from"./index-3e5fce2e.js";var as={exports:{}};as.exports;(function(a,e){/*!
|
|
2
|
-
* artplayer-plugin-danmuku.js v5.1.5
|
|
3
|
-
* Github: https://github.com/zhw2590582/ArtPlayer
|
|
4
|
-
* (c) 2017-2025 Harvey Zack
|
|
5
|
-
* Released under the MIT License.
|
|
6
|
-
*/(function(t,s,i,r,n){var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof Oi<"u"?Oi:{},d=typeof o[r]=="function"&&o[r],l=d.cache||{},h=typeof Fi=="function"&&Fi.bind(a);function c(f,p){if(!l[f]){if(!t[f]){var y=typeof o[r]=="function"&&o[r];if(!p&&y)return y(f,!0);if(d)return d(f,!0);if(h&&typeof f=="string")return h(f);var v=Error("Cannot find module '"+f+"'");throw v.code="MODULE_NOT_FOUND",v}T.resolve=function(S){var x=t[f][1][S];return x!=null?x:S},T.cache={};var E=l[f]=new c.Module(f);t[f][0].call(E.exports,T,E,E.exports,this)}return l[f].exports;function T(S){var x=T.resolve(S);return x===!1?{}:c(x)}}c.isParcelRequire=!0,c.Module=function(f){this.id=f,this.bundle=c,this.exports={}},c.modules=t,c.cache=l,c.parent=d,c.register=function(f,p){t[f]=[function(y,v){v.exports=p},{}]},Object.defineProperty(c,"root",{get:function(){return o[r]}}),o[r]=c;for(var u=0;u<s.length;u++)c(s[u]);if(i){var g=c(i);a.exports=g}})({bgm6t:[function(t,s,i){var r=t("@parcel/transformer-js/src/esmodule-helpers.js");r.defineInteropFlag(i),r.export(i,"default",()=>u);var n=t("./danmuku"),o=r.interopDefault(n),d=t("./setting"),l=r.interopDefault(d),h=t("./heatmap"),c=r.interopDefault(h);function u(g){return f=>{let p=new o.default(f,g),y=new l.default(f,p);return p.option.heatmap&&(0,c.default)(f,p,p.option.heatmap),{name:"artplayerPluginDanmuku",emit:p.emit.bind(p),load:p.load.bind(p),config:p.config.bind(p),hide:p.hide.bind(p),show:p.show.bind(p),reset:p.reset.bind(p),mount:y.mount.bind(y),get option(){return p.option},get isHide(){return p.isHide},get isStop(){return p.isStop}}}}u.icons=l.default.icons,typeof window<"u"&&(window.artplayerPluginDanmuku=u)},{"./danmuku":"4ns48","./setting":"lO8OT","./heatmap":"8AxLD","@parcel/transformer-js/src/esmodule-helpers.js":"9pCYc"}],"4ns48":[function(t,s,i){var r=t("@parcel/transformer-js/src/esmodule-helpers.js");r.defineInteropFlag(i);var n=t("./bilibili"),o=t("bundle-text:./worker"),d=r.interopDefault(o);class l{constructor(c,u){let{constructor:g,template:f}=c;this.utils=g.utils,this.validator=g.validator,this.$danmuku=f.$danmuku,this.$player=f.$player,this.art=c,this.queue=[],this.$refs=[],this.isStop=!1,this.isHide=!1,this.timer=null,this.index=0,this.option=l.option,this.states={wait:[],ready:[],emit:[],stop:[]},this.config(u);let p=new Blob([d.default],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(p)),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.reset=this.reset.bind(this),this.resize=this.resize.bind(this),this.destroy=this.destroy.bind(this),c.on("video:play",this.start),c.on("video:playing",this.start),c.on("video:pause",this.stop),c.on("video:waiting",this.stop),c.on("destroy",this.destroy),c.on("resize",this.resize),this.load()}static get option(){return{danmuku:[],speed:5,margin:[10,"25%"],opacity:1,color:"#FFFFFF",mode:0,modes:[0,1,2],fontSize:25,antiOverlap:!0,synchronousPlayback:!1,mount:void 0,heatmap:!1,width:512,points:[],filter:()=>!0,beforeEmit:()=>!0,beforeVisible:()=>!0,visible:!0,emitter:!0,maxLength:200,lockTime:5,theme:"dark",OPACITY:{},FONT_SIZE:{},MARGIN:{},SPEED:{},COLOR:[]}}static get scheme(){return{danmuku:"array|function|string",speed:"number",margin:"array",opacity:"number",color:"string",mode:"number",modes:"array",fontSize:"number|string",antiOverlap:"boolean",synchronousPlayback:"boolean",mount:"?htmldivelement|string",heatmap:"object|boolean",width:"number",points:"array",filter:"function",beforeEmit:"function",beforeVisible:"function",visible:"boolean",emitter:"boolean",maxLength:"number",lockTime:"number",theme:"string",OPACITY:"object",FONT_SIZE:"object",MARGIN:"object",SPEED:"object",COLOR:"array"}}static get cssText(){return' user-select: none; position: absolute; white-space: pre; pointer-events: none; perspective: 500px; display: inline-block; will-change: transform; font-weight: normal; line-height: 1.125; visibility: hidden; font-family: SimHei, "Microsoft JhengHei", Arial, Helvetica, sans-serif; text-shadow: rgb(0, 0, 0) 1px 0px 1px, rgb(0, 0, 0) 0px 1px 1px, rgb(0, 0, 0) 0px -1px 1px, rgb(0, 0, 0) -1px 0px 1px; '}get isRotate(){var c,u;return(u=(c=this.art.plugins)==null?void 0:c.autoOrientation)==null?void 0:u.state}get marginTop(){let{clamp:c}=this.utils,u=this.option.margin[0],{clientHeight:g}=this.$player;return typeof u=="number"?c(u,0,g):typeof u=="string"&&u.endsWith("%")?c(g*(parseFloat(u)/100),0,g):l.option.margin[0]}get marginBottom(){let{clamp:c}=this.utils,u=this.option.margin[1],{clientHeight:g}=this.$player;return typeof u=="number"?c(u,0,g):typeof u=="string"&&u.endsWith("%")?c(g*(parseFloat(u)/100),0,g):l.option.margin[1]}get fontSize(){let{clamp:c}=this.utils,{clientHeight:u}=this.$player,g=this.option.fontSize;return typeof g=="number"?Math.round(c(g,12,u)):typeof g=="string"&&g.endsWith("%")?Math.round(c(u*(parseFloat(g)/100),12,u)):l.option.fontSize}get $ref(){let c=this.$refs.pop()||document.createElement("div");return c.style.cssText=l.cssText,c.dataset.mode="",c.className="",c}get readys(){let{currentTime:c}=this.art,u=[];return this.filter("ready",g=>u.push(g)),this.filter("wait",g=>{c+.1>=g.time&&g.time>=c-.1&&u.push(g)}),u}get visibles(){let c=[],{clientWidth:u}=this.$player,g=this.getLeft(this.$player);return this.filter("emit",f=>{let p=f.$ref.offsetTop,y=this.getLeft(f.$ref)-g,v=f.$ref.clientHeight,E=f.$ref.clientWidth,T=y+E,S=T/f.$restTime,x={};x.top=p,x.left=y,x.height=v,x.width=E,x.right=u-T,x.speed=S,x.distance=T,x.time=f.$restTime,x.mode=f.mode,c.push(x)}),c}get speed(){return this.option.synchronousPlayback&&this.art.playbackRate?this.option.speed/Number(this.art.playbackRate):this.option.speed}async load(c){let{errorHandle:u}=this.utils,g=[],f=c||this.option.danmuku;try{typeof f=="function"?g=await f():f instanceof Promise?g=await f:typeof f=="string"?g=await(0,n.bilibiliDanmuParseFromUrl)(f):Array.isArray(f)&&(g=f),u(Array.isArray(g),"Danmuku need return an array as result"),c===void 0&&(this.reset(),this.queue=[],this.states={wait:[],ready:[],emit:[],stop:[]},this.$refs=[],this.$danmuku.innerText="");for(let p=0;p<g.length;p++){let y=g[p];await this.emit(y)}this.art.emit("artplayerPluginDanmuku:loaded",this.queue)}catch(p){throw this.art.emit("artplayerPluginDanmuku:error",p),p}return this}async emit(c){let{clamp:u}=this.utils;if(this.validator(c,{text:"string",mode:"?number",color:"?string",time:"?number",border:"?boolean",style:"?object"}),!c.text.trim()||(c.time?c.time=u(c.time,0,1/0):c.time=this.art.currentTime+.5,c.mode===void 0&&(c.mode=this.option.mode),c.style===void 0&&(c.style={}),c.color===void 0&&(c.color=this.option.color),![0,1,2].includes(c.mode)||!this.option.filter(c)))return this;let g={...c,$state:"wait",$id:this.index++,$ref:null,$restTime:0,$lastStartTime:0};return this.setState(g,"wait"),this.queue.push(g),this}config(c){let{clamp:u}=this.utils,{$controlsCenter:g}=this.art.template;return Object.keys(c).some(f=>JSON.stringify(this.option[f])!==JSON.stringify(c[f]))&&(this.option=Object.assign({},l.option,this.option,c),this.validator(this.option,l.scheme),this.option.mode=u(this.option.mode,0,2),this.option.speed=u(this.option.speed,1,10),this.option.opacity=u(this.option.opacity,0,1),this.option.lockTime=u(this.option.lockTime,1,60),this.option.maxLength=u(this.option.maxLength,1,1e3),this.option.mount=this.option.mount||g,c.fontSize&&this.reset(),this.option.visible?this.show():this.hide(),this.art.emit("artplayerPluginDanmuku:config",this.option)),this}getLeft(c){let u=c.getBoundingClientRect();return this.isRotate?u.top:u.left}postMessage(c={}){return new Promise(u=>{c.id=Date.now(),this.worker.postMessage(c),this.worker.onmessage=g=>{let{data:f}=g;f.id===c.id&&u(f)}})}filter(c,u){let g=this.states[c]||[];for(let f=0;f<g.length;f++)u(g[f]);return g}setState(c,u){this.states[c.$state]=this.states[c.$state].filter(g=>g!==c),c.$state=u,c.$ref&&(c.$ref.dataset.state=u),this.states[u].push(c)}makeWait(c){this.setState(c,"wait"),c.$ref&&(c.$ref.style.cssText=l.cssText,c.$ref.style.visibility="hidden",c.$ref.style.marginLeft="0px",c.$ref.style.transform="translateX(0px)",c.$ref.style.transition="transform 0s linear 0s",this.$refs.push(c.$ref),c.$ref=null)}update(){let{setStyles:c}=this.utils;return this.timer=window.requestAnimationFrame(async()=>{if(this.art.playing&&!this.isHide){this.filter("emit",g=>{let f=(Date.now()-g.$lastStartTime)/1e3;g.$restTime-=f,g.$lastStartTime=Date.now(),g.$restTime<=0&&this.makeWait(g)});let u=this.readys;for(let g=0;g<u.length;g++){let f=u[g];if(await this.option.beforeVisible(f)){let{clientWidth:p,clientHeight:y}=this.$player;f.$ref=this.$ref,f.$ref.innerText=f.text,this.$danmuku.appendChild(f.$ref),f.$ref.style.opacity=this.option.opacity,f.$ref.style.fontSize="".concat(this.fontSize,"px"),f.$ref.style.color=f.color,f.$ref.style.border=f.border?"1px solid ".concat(f.color):null,f.$ref.style.backgroundColor=f.border?"rgb(0 0 0 / 50%)":null,c(f.$ref,f.style),f.$lastStartTime=Date.now(),f.$restTime=this.speed;let v=p+f.$ref.clientWidth,{result:E}=await this.postMessage({type:"getDanmuTop",target:{mode:f.mode,height:f.$ref.clientHeight,speed:v/f.$restTime},visibles:this.visibles,antiOverlap:this.option.antiOverlap,clientWidth:p,clientHeight:y,marginBottom:this.marginBottom,marginTop:this.marginTop});if(f.$ref)if(this.isStop||E===void 0)this.setState(f,"ready"),this.$refs.push(f.$ref),f.$ref=null;else{switch(this.setState(f,"emit"),f.$ref.style.top="".concat(E,"px"),f.$ref.style.visibility="visible",f.$ref.dataset.mode=f.mode,f.mode){case 0:f.$ref.style.left="".concat(p,"px"),f.$ref.style.marginLeft="0px",f.$ref.style.transform="translateX(".concat(-v,"px)"),f.$ref.style.transition="transform ".concat(f.$restTime,"s linear 0s");break;case 1:case 2:f.$ref.style.left="50%",f.$ref.style.marginLeft="-".concat(f.$ref.clientWidth/2,"px")}this.art.emit("artplayerPluginDanmuku:visible",f)}}}}this.isStop||this.update()}),this}resize(){let{clientWidth:c}=this.$player;this.filter("stop",u=>{u.mode===0&&(u.$ref.style.left="".concat(c,"px"))}),this.filter("emit",u=>{if(u.$lastStartTime=Date.now(),u.mode===0){let g=c+u.$ref.clientWidth;u.$ref.style.left="".concat(c,"px"),u.$ref.style.transform="translateX(".concat(-g,"px)"),u.$ref.style.transition="transform ".concat(u.$restTime,"s linear 0s")}})}continue(){let{clientWidth:c}=this.$player;return this.filter("stop",u=>{if(this.setState(u,"emit"),u.$lastStartTime=Date.now(),u.mode===0){let g=c+u.$ref.clientWidth;u.$ref.style.transform="translateX(".concat(-g,"px)"),u.$ref.style.transition="transform ".concat(u.$restTime,"s linear 0s")}}),this}suspend(){let{clientWidth:c}=this.$player;return this.filter("emit",u=>{if(this.setState(u,"stop"),u.mode===0){let g=c-(this.getLeft(u.$ref)-this.getLeft(this.$player));u.$ref.style.transform="translateX(".concat(-g,"px)"),u.$ref.style.transition="transform 0s linear 0s"}}),this}stop(){return this.isStop=!0,this.suspend(),window.cancelAnimationFrame(this.timer),this.art.emit("artplayerPluginDanmuku:stop"),this}start(){return this.isStop=!1,this.continue(),this.update(),this.art.emit("artplayerPluginDanmuku:start"),this}reset(){return this.queue.forEach(c=>this.makeWait(c)),this.art.emit("artplayerPluginDanmuku:reset"),this}show(){return this.isHide=!1,this.$danmuku.style.opacity=1,this.option.visible=!0,this.art.emit("artplayerPluginDanmuku:show"),this}hide(){return this.isHide=!0,this.$danmuku.style.opacity=0,this.option.visible=!1,this.art.emit("artplayerPluginDanmuku:hide"),this}destroy(){this.stop(),this.worker.terminate(),this.art.off("video:play",this.start),this.art.off("video:playing",this.start),this.art.off("video:pause",this.stop),this.art.off("video:waiting",this.stop),this.art.off("resize",this.reset),this.art.off("destroy",this.destroy),this.art.emit("artplayerPluginDanmuku:destroy")}}i.default=l},{"./bilibili":"f83sx","bundle-text:./worker":"lfIAi","@parcel/transformer-js/src/esmodule-helpers.js":"9pCYc"}],f83sx:[function(t,s,i){var r=t("@parcel/transformer-js/src/esmodule-helpers.js");function n(h){switch(h){case 1:case 2:case 3:default:return 0;case 4:return 2;case 5:return 1}}function o(h){if(typeof h!="string")return[];let c=new RegExp(new RegExp('<d (?:.*? )??p="(?<p>.+?)"(?: .*?)?>(?<text>.+?)<\\/d>',"gs"));return Array.from(h.matchAll(c)).map(u=>{let g=u.groups.p.split(",");return g.length>=8?{text:u.groups.text.trim().replaceAll(""",'"').replaceAll("'","'").replaceAll("<","<").replaceAll(">",">").replaceAll("&","&"),time:Number(g[0]),mode:n(Number(g[1])),fontSize:Number(g[2]),color:"#".concat(Number(g[3]).toString(16)),timestamp:Number(g[4]),pool:Number(g[5]),userID:g[6],rowID:Number(g[7])}:null}).filter(Boolean)}function d({data:h}){let{xml:c,id:u}=h;if(!u||!c)return;let g=o(c);self.postMessage({danmus:g,id:u})}function l(h){return new Promise(async c=>{let u=await fetch(h),g=await u.text();try{let f=function(){let p=new Blob([" ".concat(n.toString()," ").concat(o.toString()," onmessage = ").concat(d.toString()," ")],{type:"application/javascript"});return new Worker(URL.createObjectURL(p))}();f.onmessage=p=>{let{danmus:y,id:v}=p.data;v&&y&&(c(y),f.terminate())},f.postMessage({xml:g,id:Date.now()})}catch(f){c(o(g))}})}r.defineInteropFlag(i),r.export(i,"bilibiliDanmuParseFromUrl",()=>l)},{"@parcel/transformer-js/src/esmodule-helpers.js":"9pCYc"}],"9pCYc":[function(t,s,i){i.interopDefault=function(r){return r&&r.__esModule?r:{default:r}},i.defineInteropFlag=function(r){Object.defineProperty(r,"__esModule",{value:!0})},i.exportAll=function(r,n){return Object.keys(r).forEach(function(o){o==="default"||o==="__esModule"||Object.prototype.hasOwnProperty.call(n,o)||Object.defineProperty(n,o,{enumerable:!0,get:function(){return r[o]}})}),n},i.export=function(r,n,o){Object.defineProperty(r,n,{enumerable:!0,get:o})}},{}],lfIAi:[function(t,s,i){s.exports='!function(e,t,n,o,i){var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},f="function"==typeof r[o]&&r[o],l=f.cache||{},d="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function u(t,n){if(!l[t]){if(!e[t]){var i="function"==typeof r[o]&&r[o];if(!n&&i)return i(t,!0);if(f)return f(t,!0);if(d&&"string"==typeof t)return d(t);var h=Error("Cannot find module \'"+t+"\'");throw h.code="MODULE_NOT_FOUND",h}s.resolve=function(n){var o=e[t][1][n];return null!=o?o:n},s.cache={};var p=l[t]=new u.Module(t);e[t][0].call(p.exports,s,p,p.exports,this)}return l[t].exports;function s(e){var t=s.resolve(e);return!1===t?{}:u(t)}}u.isParcelRequire=!0,u.Module=function(e){this.id=e,this.bundle=u,this.exports={}},u.modules=e,u.cache=l,u.parent=f,u.register=function(t,n){e[t]=[function(e,t){t.exports=n},{}]},Object.defineProperty(u,"root",{get:function(){return r[o]}}),r[o]=u;for(var h=0;h<t.length;h++)u(t[h]);if(n){var p=u(n);"object"==typeof exports&&"undefined"!=typeof module?module.exports=p:"function"==typeof define&&define.amd&&define(function(){return p})}}({"59OZS":[function(e,t,n){function o({target:e,visibles:t,clientWidth:n,clientHeight:o,marginBottom:i,marginTop:r,antiOverlap:f}){let l=o-i,d=t.filter(t=>t.mode===e.mode&&t.top<=l).sort((e,t)=>e.top-t.top);if(0===d.length)return 2===e.mode?l-e.height:r;if(d.unshift({type:"top",top:0,left:0,right:0,height:r,width:n,speed:0,distance:n}),d.push({type:"bottom",top:l,left:0,right:0,height:i,width:n,speed:0,distance:n}),2===e.mode)for(let t=d.length-2;t>=0;t-=1){let n=d[t],o=d[t+1],i=n.top+n.height;if(o.top-i>=e.height)return o.top-e.height}else for(let t=1;t<d.length;t+=1){let n=d[t],o=d[t-1],i=o.top+o.height;if(n.top-i>=e.height)return i}let u=[];for(let e=1;e<d.length-1;e+=1){let t=d[e];if(u.length){let e=u[u.length-1];e[0].top===t.top?e.push(t):u.push([t])}else u.push([t])}if(f)switch(e.mode){case 0:{let t=u.find(t=>t.every(t=>!(n<t.distance)&&(e.speed<t.speed||t.right/(e.speed-t.speed)>t.time)));return t&&t[0]?t[0].top:void 0}case 1:case 2:return}else{switch(e.mode){case 0:u.sort((e,t)=>{let n=Math.min(...t.map(e=>e.right)),o=Math.min(...e.map(e=>e.right));return n*t.length-o*e.length});break;case 1:case 2:u.sort((e,t)=>{let n=Math.max(...t.map(e=>e.width));return Math.max(...e.map(e=>e.width))*e.length-n*t.length})}return u[0][0].top}}onmessage=e=>{let{data:t}=e;if(!t.id||!t.type)return;let n=(0,({getDanmuTop:o})[t.type])(t);self.postMessage({result:n,id:t.id})}},{}]},["59OZS"],"59OZS","parcelRequire4dc0");'},{}],lO8OT:[function(t,s,i){var r=t("@parcel/transformer-js/src/esmodule-helpers.js");r.defineInteropFlag(i);var n=t("bundle-text:./style.less"),o=r.interopDefault(n),d=t("bundle-text:./img/on.svg"),l=r.interopDefault(d),h=t("bundle-text:./img/off.svg"),c=r.interopDefault(h),u=t("bundle-text:./img/config.svg"),g=r.interopDefault(u),f=t("bundle-text:./img/style.svg"),p=r.interopDefault(f),y=t("bundle-text:./img/mode_0_off.svg"),v=r.interopDefault(y),E=t("bundle-text:./img/mode_0_on.svg"),T=r.interopDefault(E),S=t("bundle-text:./img/mode_1_off.svg"),x=r.interopDefault(S),I=t("bundle-text:./img/mode_1_on.svg"),A=r.interopDefault(I),b=t("bundle-text:./img/mode_2_off.svg"),k=r.interopDefault(b),L=t("bundle-text:./img/mode_2_on.svg"),F=r.interopDefault(L),U=t("bundle-text:./img/check_on.svg"),B=r.interopDefault(U),N=t("bundle-text:./img/check_off.svg"),$=r.interopDefault(N);if(i.default=class{constructor(D,C){this.art=D,this.danmuku=C,this.utils=D.constructor.utils;let{setStyle:O}=this.utils,{$controlsCenter:P}=D.template;O(P,"display","flex"),this.template={$controlsCenter:P,$mount:P,$danmuku:null,$toggle:null,$config:null,$configPanel:null,$configModes:null,$style:null,$stylePanel:null,$styleModes:null,$colors:null,$opacitySlider:null,$opacityValue:null,$marginSlider:null,$marginValue:null,$fontSizeSlider:null,$fontSizeValue:null,$speedSlider:null,$speedValue:null,$input:null,$send:null},this.slider={opacity:null,margin:null,fontSize:null,speed:null},this.emitting=!1,this.isLock=!1,this.timer=null,this.createTemplate(),this.createSliders(),this.createEvents(),this.mount(this.option.mount),D.on("resize",()=>this.resize()),D.on("fullscreen",M=>this.onFullscreen(M)),D.on("fullscreenWeb",M=>this.onFullscreen(M)),D.proxy(this.template.$config,"mouseenter",()=>{this.onMouseEnter({$control:this.template.$config,$panel:this.template.$configPanel})}),D.proxy(this.template.$style,"mouseenter",()=>{this.onMouseEnter({$control:this.template.$style,$panel:this.template.$stylePanel})})}static get icons(){return{$on:l.default,$off:c.default,$config:g.default,$style:p.default,$mode_0_off:v.default,$mode_0_on:T.default,$mode_1_off:x.default,$mode_1_on:A.default,$mode_2_off:k.default,$mode_2_on:F.default,$check_on:B.default,$check_off:$.default}}get option(){return this.danmuku.option}get outside(){return this.template.$mount!==this.template.$controlsCenter}get TEMPLATE(){let{option:D}=this;return'<div class="apd-toggle">'.concat(l.default).concat(c.default,'</div><div class="apd-config">').concat(g.default,'<div class="apd-config-panel"><div class="apd-config-panel-inner"><div class="apd-config-mode">按类型屏蔽<div class="apd-modes"><div data-mode="0" class="apd-mode">').concat(v.default).concat(T.default,'<div>滚动</div></div><div data-mode="1" class="apd-mode">').concat(x.default).concat(A.default,'<div>顶部</div></div><div data-mode="2" class="apd-mode">').concat(k.default).concat(F.default,'<div>底部</div></div></div></div><div class="apd-config-other"><div class="apd-other apd-anti-overlap">').concat(B.default).concat($.default,' 防止弹幕重叠</div><div class="apd-other apd-sync-video">').concat(B.default).concat($.default,' 同步视频速度</div></div><div class="apd-config-slider apd-config-opacity">不透明度<div class="apd-slider"></div><div class="apd-value">未知</div></div><div class="apd-config-slider apd-config-margin">显示区域<div class="apd-slider"></div><div class="apd-value">未知</div></div><div class="apd-config-slider apd-config-fontSize">弹幕字号<div class="apd-slider"></div><div class="apd-value">未知</div></div><div class="apd-config-slider apd-config-speed">弹幕速度<div class="apd-slider"></div><div class="apd-value">未知</div></div></div></div></div><div class="apd-emitter"><div class="apd-style">').concat(p.default,'<div class="apd-style-panel"><div class="apd-style-panel-inner"><div class="apd-style-mode">模式<div class="apd-modes"><div data-mode="0" class="apd-mode">').concat(T.default,'<div>滚动</div></div><div data-mode="1" class="apd-mode">').concat(A.default,'<div>顶部</div></div><div data-mode="2" class="apd-mode">').concat(F.default,'<div>底部</div></div></div></div><div class="apd-style-color">颜色<div class="apd-colors">').concat(this.COLOR.map(C=>'<div data-color="'.concat(C,'" class="apd-color" style="background-color: ').concat(C,'"></div>')).join(""),'</div></div></div></div></div><input class="apd-input" placeholder="发个友善的弹幕见证当下" autocomplete="off" maxLength="').concat(D.maxLength,'" /><div class="apd-send">发送</div></div>')}get OPACITY(){return{min:0,max:100,steps:[],...this.option.OPACITY}}get FONT_SIZE(){return{min:12,max:120,steps:[],...this.option.FONT_SIZE}}get MARGIN(){return{min:0,max:3,steps:[{name:"1/4",value:[10,"75%"]},{name:"半屏",value:[10,"50%"]},{name:"3/4",value:[10,"25%"]},{name:"满屏",value:[10,10]}],...this.option.MARGIN}}get SPEED(){return{min:0,max:4,steps:[{name:"极慢",value:10},{name:"较慢",value:7.5,hide:!0},{name:"适中",value:5},{name:"较快",value:2.5,hide:!0},{name:"极快",value:1}],...this.option.SPEED}}get COLOR(){return this.option.COLOR.length?this.option.COLOR:["#FE0302","#FF7204","#FFAA02","#FFD302","#FFFF00","#A0EE00","#00CD00","#019899","#4266BE","#89D5FF","#CC0273","#222222","#9B9B9B","#FFFFFF"]}query(D){let{query:C}=this.utils,{$danmuku:O}=this.template;return C(D,O)}append(D,C){let{append:O}=this.utils;[...D.children].some(P=>P===C)||O(D,C)}setData(D,C){let{$player:O}=this.art.template,{$mount:P}=this.template;O.dataset[D]=C,this.outside&&(P.dataset[D]=C)}createTemplate(){let{createElement:D,tooltip:C}=this.utils,O=D("div");O.className="artplayer-plugin-danmuku",O.innerHTML=this.TEMPLATE,this.template.$danmuku=O,this.template.$toggle=this.query(".apd-toggle"),this.template.$config=this.query(".apd-config"),this.template.$configPanel=this.query(".apd-config-panel"),this.template.$configModes=this.query(".apd-config-mode .apd-modes"),this.template.$style=this.query(".apd-style"),this.template.$stylePanel=this.query(".apd-style-panel"),this.template.$styleModes=this.query(".apd-style-mode .apd-modes"),this.template.$colors=this.query(".apd-colors"),this.template.$antiOverlap=this.query(".apd-anti-overlap"),this.template.$syncVideo=this.query(".apd-sync-video"),this.template.$opacitySlider=this.query(".apd-config-opacity .apd-slider"),this.template.$opacityValue=this.query(".apd-config-opacity .apd-value"),this.template.$marginSlider=this.query(".apd-config-margin .apd-slider"),this.template.$marginValue=this.query(".apd-config-margin .apd-value"),this.template.$fontSizeSlider=this.query(".apd-config-fontSize .apd-slider"),this.template.$fontSizeValue=this.query(".apd-config-fontSize .apd-value"),this.template.$speedSlider=this.query(".apd-config-speed .apd-slider"),this.template.$speedValue=this.query(".apd-config-speed .apd-value"),this.template.$input=this.query(".apd-input"),this.template.$send=this.query(".apd-send");let{$toggle:P}=this.template;this.art.on("artplayerPluginDanmuku:show",()=>{C(P,"关闭弹幕")}),this.art.on("artplayerPluginDanmuku:hide",()=>{C(P,"打开弹幕")})}createEvents(){let{$toggle:D,$configModes:C,$styleModes:O,$colors:P,$antiOverlap:M,$syncVideo:W,$send:K,$input:j}=this.template;this.art.proxy(D,"click",()=>{this.danmuku.config({visible:!this.option.visible}),this.reset()}),this.art.proxy(C,"click",q=>{let X=q.target.closest(".apd-mode");if(!X)return;let J=Number(X.dataset.mode);this.option.modes.includes(J)?this.danmuku.config({modes:this.option.modes.filter(le=>le!==J)}):this.danmuku.config({modes:[...this.option.modes,J]}),this.reset()}),this.art.proxy(M,"click",()=>{this.danmuku.config({antiOverlap:!this.option.antiOverlap}),this.reset()}),this.art.proxy(W,"click",()=>{this.danmuku.config({synchronousPlayback:!this.option.synchronousPlayback}),this.reset()}),this.art.proxy(O,"click",q=>{let X=q.target.closest(".apd-mode");if(!X)return;let J=Number(X.dataset.mode);this.danmuku.config({mode:J}),this.reset()}),this.art.proxy(P,"click",q=>{let X=q.target.closest(".apd-color");X&&(this.danmuku.config({color:X.dataset.color}),this.reset())}),this.art.proxy(K,"click",()=>this.emit()),this.art.proxy(j,"keypress",q=>{q.key==="Enter"&&(q.preventDefault(),this.emit())})}createSliders(){this.slider.opacity=this.createSlider({...this.OPACITY,container:this.template.$opacitySlider,findIndex:()=>Math.round(100*this.option.opacity),onChange:D=>{let{$opacityValue:C}=this.template;C.textContent="".concat(D,"%"),this.danmuku.config({opacity:D/100})}}),this.slider.margin=this.createSlider({...this.MARGIN,container:this.template.$marginSlider,findIndex:()=>this.MARGIN.steps.findIndex(D=>D.value[0]===this.option.margin[0]&&D.value[1]===this.option.margin[1]),onChange:D=>{let C=this.MARGIN.steps[D];if(!C)return;let{$marginValue:O}=this.template;O.textContent=C.name,this.danmuku.config({margin:C.value})}}),this.slider.fontSize=this.createSlider({...this.FONT_SIZE,container:this.template.$fontSizeSlider,findIndex:()=>this.danmuku.fontSize,onChange:D=>{let{$fontSizeValue:C}=this.template;C.textContent="".concat(D,"px"),D!==this.danmuku.fontSize&&this.danmuku.config({fontSize:D})}}),this.slider.speed=this.createSlider({...this.SPEED,container:this.template.$speedSlider,findIndex:()=>this.SPEED.steps.findIndex(D=>D.value===this.option.speed),onChange:D=>{let C=this.SPEED.steps[D];if(!C)return;let{$speedValue:O}=this.template;O.textContent=C.name,this.danmuku.config({speed:C.value})}})}createSlider({min:D,max:C,container:O,findIndex:P,onChange:M,steps:W=[]}){let{query:K,clamp:j,setStyle:q}=this.utils;q(O,"touch-action","none"),O.innerHTML='<div class="apd-slider-line"><div class="apd-slider-points">'.concat(W.map(()=>'<div class="apd-slider-point"></div>').join(""),'</div><div class="apd-slider-progress"></div></div><div class="apd-slider-dot"></div><div class="apd-slider-steps">').concat(W.map(de=>de.hide?"":'<div class="apd-slider-step">'.concat(de.name,"</div>")).join(""),"</div>");let X=K(".apd-slider-dot",O),J=K(".apd-slider-progress",O),le=!1;function ue(de=P()){if(de<D||de>C)return;let yt=(de-D)/(C-D);X.style.left="".concat(100*yt,"%"),W.length===0&&(J.style.width=X.style.left),M(de)}function xe(de){let{top:yt,height:Ft,left:vt,width:it}=O.getBoundingClientRect();this.art.isRotate?ue(Math.round(j(de.clientY-yt,0,Ft)/Ft*(C-D)+D)):ue(Math.round(j(de.clientX-vt,0,it)/it*(C-D)+D))}return this.art.proxy(O,"click",de=>{xe.call(this,de)}),this.art.proxy(O,"pointerdown",de=>{le=de.button===0}),this.art.proxy(document,"pointermove",de=>{le&&xe.call(this,de)}),this.art.proxy(document,"pointerup",de=>{le&&(le=!1,xe.call(this,de))}),{reset:ue}}onFullscreen(D){let{$danmuku:C,$controlsCenter:O,$mount:P}=this.template;this.outside?D?this.append(O,C):this.append(P,C):this.append(O,C)}onMouseEnter({$control:D,$panel:C}){let{$player:O}=this.art.template,P=D.getBoundingClientRect(),M=C.getBoundingClientRect(),W=O.getBoundingClientRect(),K=M.width/2-P.width/2,j=W.left-(P.left-K),q=P.right+K-W.right;j>0?C.style.left="".concat(-K+j,"px"):q>0?C.style.left="".concat(-K-q,"px"):C.style.left="".concat(-K,"px")}async emit(){let{$input:D}=this.template,C=D.value.trim();if(!C.length||this.isLock||this.emitting)return;let O={text:C,mode:this.option.mode,color:this.option.color,time:this.art.currentTime};try{this.emitting=!0;let P=await this.option.beforeEmit(O);if(this.emitting=!1,P!==!0)return;O.border=!0,delete O.time,this.danmuku.emit(O),D.value="",this.lock()}catch(P){this.emitting=!1}}lock(){let{addClass:D}=this.utils,{$send:C}=this.template;this.isLock=!0;let O=this.option.lockTime;C.innerText=O,D(C,"apd-lock");let P=()=>{this.timer=setTimeout(()=>{O===0?this.unlock():(O-=1,C.innerText=O,P())},1e3)};P()}unlock(){let{removeClass:D}=this.utils,{$send:C}=this.template;clearTimeout(this.timer),this.isLock=!1,C.innerText="发送",D(C,"apd-lock")}resize(){if(this.outside||this.art.fullscreen||this.art.fullscreenWeb)return;let{$player:D,$controlsCenter:C}=this.art.template,{$danmuku:O}=this.template;this.art.width<this.option.width?this.append(D,O):this.append(C,O)}reset(){let{inverseClass:D,tooltip:C}=this.utils,{$toggle:O,$colors:P}=this.template;this.slider.opacity.reset(),this.slider.margin.reset(),this.slider.fontSize.reset(),this.slider.speed.reset(),this.setData("danmukuVisible",this.option.visible),this.setData("danmukuMode",this.option.mode),this.setData("danmukuColor",this.option.color),this.setData("danmukuMode0",this.option.modes.includes(0)),this.setData("danmukuMode1",this.option.modes.includes(1)),this.setData("danmukuMode2",this.option.modes.includes(2)),this.setData("danmukuAntiOverlap",this.option.antiOverlap),this.setData("danmukuSyncVideo",this.option.synchronousPlayback),this.setData("danmukuTheme",this.option.theme),this.setData("danmukuEmitter",this.option.emitter);let M=Array.from(P.children).find(W=>W.dataset.color===this.option.color.toUpperCase());M&&D(M,"apd-active"),C(O,this.option.visible?"关闭弹幕":"打开弹幕"),this.resize()}mount(D){let{errorHandle:C}=this.utils,O=typeof D=="string"?document.querySelector(D):D;C(O,"Can not find the mount point: ".concat(D)),this.append(O,this.template.$danmuku),this.template.$mount=O,this.reset()}},typeof document<"u"){let D="artplayer-plugin-danmuku",C=document.getElementById(D);if(C)C.textContent=o.default;else{let O=document.createElement("style");O.id=D,O.textContent=o.default,document.head.appendChild(O)}}},{"bundle-text:./style.less":"hViDo","bundle-text:./img/on.svg":"9pjcf","bundle-text:./img/off.svg":"b2dkP","bundle-text:./img/config.svg":"l8tyy","bundle-text:./img/style.svg":"5iZC3","bundle-text:./img/mode_0_off.svg":"i0Vut","bundle-text:./img/mode_0_on.svg":"hOSvZ","bundle-text:./img/mode_1_off.svg":"bOXC3","bundle-text:./img/mode_1_on.svg":"lKuh0","bundle-text:./img/mode_2_off.svg":"eB8W6","bundle-text:./img/mode_2_on.svg":"bpe2E","bundle-text:./img/check_on.svg":"kL9zy","bundle-text:./img/check_off.svg":"22xpM","@parcel/transformer-js/src/esmodule-helpers.js":"9pCYc"}],hViDo:[function(t,s,i){s.exports='.artplayer-plugin-danmuku{z-index:99;color:#fff;flex-shrink:0;justify-content:center;align-items:center;gap:10px;width:100%;height:32px;font-size:12px;font-weight:300;display:flex;position:relative}.artplayer-plugin-danmuku .apd-icon{cursor:pointer;opacity:.75;fill:#fff;transition:all .2s}.artplayer-plugin-danmuku .apd-icon:hover{opacity:1}.artplayer-plugin-danmuku .apd-config{display:flex;position:relative}.artplayer-plugin-danmuku .apd-config .apd-config-panel{opacity:0;pointer-events:none;width:320px;padding:10px;position:absolute;bottom:24px;left:0}.artplayer-plugin-danmuku .apd-config .apd-config-panel .apd-config-panel-inner{background-color:#000000d9;border-radius:3px;width:100%;padding:10px}.artplayer-plugin-danmuku .apd-config:hover .apd-config-panel{opacity:100;pointer-events:all}.artplayer-plugin-danmuku .apd-config-mode,.artplayer-plugin-danmuku .apd-config-slider,.artplayer-plugin-danmuku .apd-config-other,.artplayer-plugin-danmuku .apd-style-mode{margin-bottom:15px}.artplayer-plugin-danmuku .apd-modes{align-items:center;gap:20px;margin-top:5px;display:flex}.artplayer-plugin-danmuku .apd-modes .apd-mode{cursor:pointer;text-align:center}.artplayer-plugin-danmuku .apd-modes .apd-mode:hover{color:#00a1d6}.artplayer-plugin-danmuku .apd-config-slider{align-items:center;gap:12px;display:flex}.artplayer-plugin-danmuku .apd-config-slider .apd-value{text-align:right;width:32px}.artplayer-plugin-danmuku .apd-slider{cursor:pointer;flex:1;justify-content:center;align-items:center;height:20px;display:flex;position:relative}.artplayer-plugin-danmuku .apd-slider .apd-slider-line{background-color:#ffffff40;border-radius:3px;width:100%;height:2px;position:relative;overflow:hidden}.artplayer-plugin-danmuku .apd-slider .apd-slider-points{justify-content:space-between;align-items:center;display:flex;position:absolute;inset:0}.artplayer-plugin-danmuku .apd-slider .apd-slider-points .apd-slider-point{background-color:#ffffff80;border-radius:50%;width:2px;height:2px}.artplayer-plugin-danmuku .apd-slider .apd-slider-progress{background-color:#00a1d6;width:0%;height:100%}.artplayer-plugin-danmuku .apd-slider .apd-slider-dot{background-color:#00a1d6;border-radius:50%;width:12px;height:12px;position:absolute;left:0%;transform:translate(-6px)}.artplayer-plugin-danmuku .apd-slider .apd-slider-steps{color:#777;justify-content:space-between;align-items:center;width:calc(100% + 32px);display:flex;position:absolute;bottom:-12px}.artplayer-plugin-danmuku .apd-slider .apd-slider-steps .apd-slider-step{text-align:center;flex-shrink:0;width:36px;scale:.95}.artplayer-plugin-danmuku .apd-config-other{align-items:center;gap:20px;display:flex}.artplayer-plugin-danmuku .apd-config-other .apd-check-off,.artplayer-plugin-danmuku .apd-config-other .apd-check-on{width:16px;height:16px}.artplayer-plugin-danmuku .apd-config-other .apd-other{cursor:pointer;align-items:center;gap:2px;display:flex}.artplayer-plugin-danmuku .apd-config-other .apd-other:hover{color:#00a1d6}.artplayer-plugin-danmuku .apd-emitter{background-color:#ffffff40;border-radius:5px;flex:1;align-items:center;height:100%;display:flex}.artplayer-plugin-danmuku .apd-style{justify-content:center;align-items:center;display:flex;position:relative}.artplayer-plugin-danmuku .apd-style .apd-style-panel{opacity:0;pointer-events:none;width:200px;padding:10px;position:absolute;bottom:24px;left:0}.artplayer-plugin-danmuku .apd-style .apd-style-panel .apd-style-panel-inner{background-color:#000000d9;border-radius:3px;width:100%;padding:10px}.artplayer-plugin-danmuku .apd-style:hover .apd-style-panel{opacity:100;pointer-events:all}.artplayer-plugin-danmuku .apd-colors{flex-wrap:wrap;gap:8px;margin-top:5px;display:flex}.artplayer-plugin-danmuku .apd-colors .apd-color{cursor:pointer;border-radius:2px;width:16px;height:16px}.artplayer-plugin-danmuku .apd-colors .apd-color.apd-active{border:1px solid #000;box-shadow:0 0 0 1px #fff}.artplayer-plugin-danmuku .apd-input{color:#fff;background-color:#0000;border:none;outline:none;flex:1;width:auto;min-width:0;height:100%;line-height:1}.artplayer-plugin-danmuku .apd-input::placeholder{color:#ffffff80}.artplayer-plugin-danmuku .apd-send{cursor:pointer;text-shadow:none;background-color:#00a1d6;border-top-right-radius:5px;border-bottom-right-radius:5px;flex-shrink:0;justify-content:center;align-items:center;width:60px;height:100%;display:flex}.artplayer-plugin-danmuku .apd-send.apd-lock{cursor:not-allowed;color:#666;background-color:#e7e7e7}.art-controls-center .apd-emitter{flex:none;width:260px}.art-fullscreen .artplayer-plugin-danmuku,.art-fullscreen-web .artplayer-plugin-danmuku{gap:16px;height:38px}.art-fullscreen .artplayer-plugin-danmuku .apd-config-icon,.art-fullscreen-web .artplayer-plugin-danmuku .apd-config-icon,.art-fullscreen .artplayer-plugin-danmuku .apd-toggle-off,.art-fullscreen-web .artplayer-plugin-danmuku .apd-toggle-off,.art-fullscreen .artplayer-plugin-danmuku .apd-toggle-on,.art-fullscreen-web .artplayer-plugin-danmuku .apd-toggle-on{width:28px;height:28px}.art-fullscreen .artplayer-plugin-danmuku .apd-emitter,.art-fullscreen-web .artplayer-plugin-danmuku .apd-emitter{flex:none;width:400px}.art-video-player>.artplayer-plugin-danmuku{padding:0 10px;position:absolute;bottom:-40px;left:0;right:0}.art-video-player:has(>.artplayer-plugin-danmuku){margin-bottom:40px}[data-danmuku-emitter=false] .apd-emitter{display:none!important}[data-danmuku-emitter=false] .art-controls-center .artplayer-plugin-danmuku{justify-content:flex-end;gap:18px}[data-danmuku-emitter=false].art-fullscreen .art-controls-center .artplayer-plugin-danmuku,[data-danmuku-emitter=false].art-fullscreen-web .art-controls-center .artplayer-plugin-danmuku{gap:24px}[data-danmuku-theme=light]>.artplayer-plugin-danmuku .apd-icon{fill:#333}[data-danmuku-theme=light]>.artplayer-plugin-danmuku .apd-emitter{background-color:#f1f2f3}[data-danmuku-theme=light]>.artplayer-plugin-danmuku .apd-input{color:#000}[data-danmuku-theme=light]>.artplayer-plugin-danmuku .apd-input::placeholder{color:#0000004d}[data-danmuku-visible=false] .apd-toggle-off{display:block}[data-danmuku-visible=false] .apd-toggle-on,[data-danmuku-visible=true] .apd-toggle-off{display:none}[data-danmuku-visible=true] .apd-toggle-on{display:block}[data-danmuku-anti-overlap=false] .apd-anti-overlap .apd-check-on{display:none}[data-danmuku-anti-overlap=false] .apd-anti-overlap .apd-check-off,[data-danmuku-anti-overlap=true] .apd-anti-overlap .apd-check-on{display:block}[data-danmuku-anti-overlap=true] .apd-anti-overlap .apd-check-off,[data-danmuku-sync-video=false] .apd-sync-video .apd-check-on{display:none}[data-danmuku-sync-video=false] .apd-sync-video .apd-check-off,[data-danmuku-sync-video=true] .apd-sync-video .apd-check-on{display:block}[data-danmuku-sync-video=true] .apd-sync-video .apd-check-off{display:none}[data-danmuku-mode0=false] .apd-config-mode .apd-mode-0-off{display:block}[data-danmuku-mode0=false] .apd-config-mode .apd-mode-0-on{display:none}[data-danmuku-mode0=false] .art-danmuku [data-mode="0"]{opacity:0!important}[data-danmuku-mode0=true] .apd-config-mode .apd-mode-0-off{display:none}[data-danmuku-mode0=true] .apd-config-mode .apd-mode-0-on{display:block}[data-danmuku-mode="0"] .apd-style-mode [data-mode="0"]{color:#00a1d6}[data-danmuku-mode="0"] .apd-style-mode [data-mode="0"] path{fill:#00a1d6}[data-danmuku-mode1=false] .apd-config-mode .apd-mode-1-off{display:block}[data-danmuku-mode1=false] .apd-config-mode .apd-mode-1-on{display:none}[data-danmuku-mode1=false] .art-danmuku [data-mode="1"]{opacity:0!important}[data-danmuku-mode1=true] .apd-config-mode .apd-mode-1-off{display:none}[data-danmuku-mode1=true] .apd-config-mode .apd-mode-1-on{display:block}[data-danmuku-mode="1"] .apd-style-mode [data-mode="1"]{color:#00a1d6}[data-danmuku-mode="1"] .apd-style-mode [data-mode="1"] path{fill:#00a1d6}[data-danmuku-mode2=false] .apd-config-mode .apd-mode-2-off{display:block}[data-danmuku-mode2=false] .apd-config-mode .apd-mode-2-on{display:none}[data-danmuku-mode2=false] .art-danmuku [data-mode="2"]{opacity:0!important}[data-danmuku-mode2=true] .apd-config-mode .apd-mode-2-off{display:none}[data-danmuku-mode2=true] .apd-config-mode .apd-mode-2-on{display:block}[data-danmuku-mode="2"] .apd-style-mode [data-mode="2"]{color:#00a1d6}[data-danmuku-mode="2"] .apd-style-mode [data-mode="2"] path{fill:#00a1d6}'},{}],"9pjcf":[function(t,s,i){s.exports='<svg class="apd-icon apd-toggle-on" xmlns="http://www.w3.org/2000/svg" data-pointer="none" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M11.989 4.828c-.47 0-.975.004-1.515.012l-1.71-2.566a1.008 1.008 0 0 0-1.678 1.118l.999 1.5c-.681.018-1.403.04-2.164.068a4.013 4.013 0 0 0-3.83 3.44c-.165 1.15-.245 2.545-.245 4.185 0 1.965.115 3.67.35 5.116a4.012 4.012 0 0 0 3.763 3.363l.906.046c1.205.063 1.808.095 3.607.095a.988.988 0 0 0 0-1.975c-1.758 0-2.339-.03-3.501-.092l-.915-.047a2.037 2.037 0 0 1-1.91-1.708c-.216-1.324-.325-2.924-.325-4.798 0-1.563.076-2.864.225-3.904.14-.977.96-1.713 1.945-1.747 2.444-.087 4.465-.13 6.063-.131 1.598 0 3.62.044 6.064.13.96.034 1.71.81 1.855 1.814.075.524.113 1.962.141 3.065v.002c.01.342.017.65.025.88a.987.987 0 1 0 1.974-.068c-.008-.226-.016-.523-.025-.856v-.027c-.03-1.118-.073-2.663-.16-3.276-.273-1.906-1.783-3.438-3.74-3.507-.9-.032-1.743-.058-2.531-.078l1.05-1.46a1.008 1.008 0 0 0-1.638-1.177l-1.862 2.59c-.38-.004-.744-.007-1.088-.007h-.13Zm.521 4.775h-1.32v4.631h2.222v.847h-2.618v1.078h2.618l.003.678c.36.026.714.163 1.01.407h.11v-1.085h2.694v-1.078h-2.695v-.847H16.8v-4.63h-1.276a8.59 8.59 0 0 0 .748-1.42L15.183 7.8a14.232 14.232 0 0 1-.814 1.804h-1.518l.693-.308a8.862 8.862 0 0 0-.814-1.408l-1.045.352c.297.396.572.847.825 1.364Zm-4.18 3.564.154-1.485h1.98V8.294h-3.2v.98H9.33v1.43H7.472l-.308 3.453h2.277c0 1.166-.044 1.925-.12 2.277-.078.352-.386.528-.936.528-.308 0-.616-.022-.902-.055l.297 1.067.062.005c.285.02.551.04.818.04 1.001-.067 1.562-.419 1.694-1.057.11-.638.176-1.903.176-3.795h-2.2Zm7.458.11v-.858h-1.254v.858h1.254Zm-2.376-.858v.858h-1.199v-.858h1.2Zm-1.199-.946h1.2v-.902h-1.2v.902Zm2.321 0v-.902h1.254v.902h-1.254Z" clip-rule="evenodd"/><path fill="#00AEEC" fill-rule="evenodd" d="M22.846 14.627a1 1 0 0 0-1.412.075l-5.091 5.703-2.216-2.275-.097-.086-.008-.005a1 1 0 0 0-1.322 1.493l2.963 3.041.093.083.007.005a1 1 0 0 0 1.354-.124l5.81-6.505.08-.102.005-.008a1 1 0 0 0-.166-1.295Z" clip-rule="evenodd"/></svg>'},{}],b2dkP:[function(t,s,i){s.exports='<svg class="apd-icon apd-toggle-off" xmlns="http://www.w3.org/2000/svg" data-pointer="none" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="m8.085 4.891-.999-1.499a1.008 1.008 0 0 1 1.679-1.118l1.709 2.566c.54-.008 1.045-.012 1.515-.012h.13c.345 0 .707.003 1.088.007l1.862-2.59a1.008 1.008 0 0 1 1.637 1.177l-1.049 1.46c.788.02 1.631.046 2.53.078 1.958.069 3.468 1.6 3.74 3.507.088.613.13 2.158.16 3.276l.001.027c.01.333.017.63.025.856a.987.987 0 0 1-1.974.069c-.008-.23-.016-.539-.025-.881v-.002c-.028-1.103-.066-2.541-.142-3.065-.143-1.004-.895-1.78-1.854-1.813a179.14 179.14 0 0 0-6.064-.131c-1.598 0-3.619.044-6.063.13a2.037 2.037 0 0 0-1.945 1.748c-.15 1.04-.225 2.341-.225 3.904 0 1.874.11 3.474.325 4.798.154.949.95 1.66 1.91 1.708a97.58 97.58 0 0 0 5.416.139.988.988 0 0 1 0 1.975 99.78 99.78 0 0 1-5.513-.141A4.012 4.012 0 0 1 2.197 17.7c-.236-1.446-.351-3.151-.351-5.116 0-1.64.08-3.035.245-4.184A4.013 4.013 0 0 1 5.92 4.96c.761-.027 1.483-.05 2.164-.069Zm4.436 4.707h-1.32v4.63h2.222v.848h-2.618v1.078h2.431a5.01 5.01 0 0 1 3.575-3.115V9.598h-1.276a8.59 8.59 0 0 0 .748-1.42l-1.089-.384a14.232 14.232 0 0 1-.814 1.804h-1.518l.693-.308a8.862 8.862 0 0 0-.814-1.408l-1.045.352c.297.396.572.847.825 1.364Zm-4.18 3.564.154-1.485h1.98V8.289h-3.2v.979h2.067v1.43H7.483l-.308 3.454h2.277c0 1.166-.044 1.925-.12 2.277-.078.352-.386.528-.936.528-.308 0-.616-.022-.902-.055l.297 1.067.062.004c.285.02.551.04.818.04 1.001-.066 1.562-.418 1.694-1.056.11-.638.176-1.903.176-3.795h-2.2Zm7.458.11v-.858h-1.254v.858H15.8Zm-2.376-.858v.858h-1.199v-.858h1.2Zm-1.199-.946h1.2v-.902h-1.2v.902Zm2.321 0v-.902H15.8v.902h-1.254Zm3.517 10.594a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm-.002-1.502a2.5 2.5 0 0 1-2.217-3.657l3.326 3.398a2.49 2.49 0 0 1-1.109.259Zm2.5-2.5c0 .42-.103.815-.286 1.162l-3.328-3.401a2.5 2.5 0 0 1 3.614 2.239Z" clip-rule="evenodd"/></svg>'},{}],l8tyy:[function(t,s,i){s.exports='<svg class="apd-icon apd-config-icon" xmlns="http://www.w3.org/2000/svg" data-pointer="none" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="m15.645 4.881 1.06-1.473a.998.998 0 1 0-1.622-1.166L13.22 4.835a110.67 110.67 0 0 0-1.1-.007h-.131c-.47 0-.975.004-1.515.012L8.783 2.3A.998.998 0 0 0 7.12 3.408l.988 1.484c-.688.019-1.418.042-2.188.069a4.013 4.013 0 0 0-3.83 3.44c-.165 1.15-.245 2.545-.245 4.185 0 1.965.115 3.67.35 5.116a4.012 4.012 0 0 0 3.763 3.363 99.78 99.78 0 0 0 5.513.141.988.988 0 0 0 0-1.975 97.58 97.58 0 0 1-5.416-.139 2.037 2.037 0 0 1-1.91-1.708c-.216-1.324-.325-2.924-.325-4.798 0-1.563.076-2.864.225-3.904.14-.977.96-1.713 1.945-1.747 2.444-.087 4.465-.13 6.063-.131 1.598 0 3.62.044 6.064.13.96.034 1.71.81 1.855 1.814.075.524.113 1.962.141 3.065v.002c.005.183.01.07.014-.038.004-.096.008-.189.011-.081a.987.987 0 1 0 1.974-.069c-.004-.105-.007-.009-.011.09a2.175 2.175 0 0 1-.007.135l-.002.01a.574.574 0 0 1-.005-.091v-.027c-.03-1.118-.073-2.663-.16-3.276-.273-1.906-1.783-3.438-3.74-3.507-.905-.032-1.752-.058-2.543-.079Zm-3.113 4.703h-1.307v4.643h2.2v.04l.651-1.234c.113-.215.281-.389.482-.509v-.11h.235c.137-.049.283-.074.433-.074h1.553V9.584h-1.264a8.5 8.5 0 0 0 .741-1.405l-1.078-.381c-.24.631-.501 1.23-.806 1.786h-1.503l.686-.305a8.613 8.613 0 0 0-.806-1.394l-1.034.348c.294.392.566.839.817 1.35Zm-1.7 5.502h2.16l-.564 1.068h-1.595v-1.068Zm-2.498-1.863.152-1.561h1.96V8.289H7.277v.969h2.048v1.435h-1.84l-.306 3.51h2.254c0 1.155-.043 1.906-.12 2.255-.076.348-.38.523-.925.523-.305 0-.61-.022-.893-.055l.294 1.056.061.005c.282.02.546.039.81.039.991-.065 1.547-.414 1.677-1.046.11-.631.175-1.883.175-3.757H8.334Zm5.09-.8v.85h-1.188v-.85h1.187Zm-1.188-.955h1.187v-.893h-1.187v.893Zm2.322.007v-.893h1.241v.893h-1.241Zm.528 2.757a1.26 1.26 0 0 1 1.087-.627l4.003-.009a1.26 1.26 0 0 1 1.094.63l1.721 2.982c.226.39.225.872-.001 1.263l-1.743 3a1.26 1.26 0 0 1-1.086.628l-4.003.009a1.26 1.26 0 0 1-1.094-.63l-1.722-2.982a1.26 1.26 0 0 1 .002-1.263l1.742-3Zm1.967.858a1.26 1.26 0 0 0-1.08.614l-.903 1.513a1.26 1.26 0 0 0-.002 1.289l.885 1.492c.227.384.64.62 1.086.618l2.192-.005a1.26 1.26 0 0 0 1.08-.615l.904-1.518a1.26 1.26 0 0 0 .001-1.288l-.884-1.489a1.26 1.26 0 0 0-1.086-.616l-2.193.005Zm2.517 2.76a1.4 1.4 0 1 1-2.8 0 1.4 1.4 0 0 1 2.8 0Z" clip-rule="evenodd"/></svg>'},{}],"5iZC3":[function(t,s,i){s.exports='<svg class="apd-icon apd-style-icon" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" data-pointer="none" style="enable-background:new 0 0 22 22" viewBox="0 0 22 22" width="36" height="24"><path d="M17 16H5c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1zM6.96 15c.39 0 .74-.24.89-.6l.65-1.6h5l.66 1.6c.15.36.5.6.89.6.69 0 1.15-.71.88-1.34l-3.88-8.97C11.87 4.27 11.46 4 11 4s-.87.27-1.05.69l-3.88 8.97c-.27.63.2 1.34.89 1.34zM11 5.98 12.87 11H9.13L11 5.98z"/></svg>'},{}],i0Vut:[function(t,s,i){s.exports='<svg class="apd-icon apd-mode-0-off" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" data-pointer="none" style="enable-background:new 0 0 28 28" viewBox="0 0 28 28" width="28" height="28"><path d="M23 15c1.487 0 2.866.464 4 1.255V7a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v14a4 4 0 0 0 4 4h11.674A7 7 0 0 1 23 15zM11 9h6a1 1 0 0 1 0 2h-6a1 1 0 0 1 0-2zm-3 2H6V9h2v2zm4 4h-2v-2h2v2zm2-1a1 1 0 0 1 1-1h1a1 1 0 0 1 0 2h-1a1 1 0 0 1-1-1z" fill="#00AEEC"/><path d="M26.536 18.464a5 5 0 0 0-7.071 0 5 5 0 0 0 0 7.071 5 5 0 1 0 7.071-7.071zm-5.657 5.657a3 3 0 0 1-.586-3.415l4.001 4.001a3 3 0 0 1-3.415-.586zm4.829-.827-4.001-4.001a3.002 3.002 0 0 1 4.001 4.001z" fill="#00AEEC"/></svg>'},{}],hOSvZ:[function(t,s,i){s.exports='<svg class="apd-icon apd-mode-0-on" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" data-pointer="none" style="enable-background:new 0 0 28 28" viewBox="0 0 28 28" width="28" height="28"><path d="M23 3H5a4 4 0 0 0-4 4v14a4 4 0 0 0 4 4h18a4 4 0 0 0 4-4V7a4 4 0 0 0-4-4zM11 9h6a1 1 0 0 1 0 2h-6a1 1 0 0 1 0-2zm-3 2H6V9h2v2zm4 4h-2v-2h2v2zm9 0h-6a1 1 0 0 1 0-2h6a1 1 0 0 1 0 2z" fill="#FFF"/></svg>'},{}],bOXC3:[function(t,s,i){s.exports='<svg class="apd-icon apd-mode-1-off" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" data-pointer="none" style="enable-background:new 0 0 28 28" viewBox="0 0 28 28" width="28" height="28"><path d="M23 15c1.487 0 2.866.464 4 1.255V7a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v14a4 4 0 0 0 4 4h11.674A7 7 0 0 1 23 15zm-4-8h2v2h-2V7zM9 9H7V7h2v2zm4 0h-2V7h2v2zm2-2h2v2h-2V7z" fill="#00AEEC"/><path d="M26.536 18.464a5 5 0 0 0-7.071 0 5 5 0 0 0 0 7.071 5 5 0 1 0 7.071-7.071zm-5.657 5.657a3 3 0 0 1-.586-3.415l4.001 4.001a3 3 0 0 1-3.415-.586zm4.829-.827-4.001-4.001a3.002 3.002 0 0 1 4.001 4.001z" fill="#00AEEC"/></svg>'},{}],lKuh0:[function(t,s,i){s.exports='<svg class="apd-icon apd-mode-1-on" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" data-pointer="none" style="enable-background:new 0 0 28 28" viewBox="0 0 28 28" width="28" height="28"><path d="M23 3H5a4 4 0 0 0-4 4v14a4 4 0 0 0 4 4h18a4 4 0 0 0 4-4V7a4 4 0 0 0-4-4zM9 9H7V7h2v2zm4 0h-2V7h2v2zm4 0h-2V7h2v2zm4 0h-2V7h2v2z" fill="#FFF"/></svg>'},{}],eB8W6:[function(t,s,i){s.exports='<svg class="apd-icon apd-mode-2-off" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" data-pointer="none" style="enable-background:new 0 0 28 28" viewBox="0 0 28 28" width="28" height="28"><path d="M23 15c1.487 0 2.866.464 4 1.255V7a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v14a4 4 0 0 0 4 4h11.674A7 7 0 0 1 23 15zM9 21H7v-2h2v2zm4 0h-2v-2h2v2z" fill="#00AEEC"/><path d="M26.536 18.464a5 5 0 0 0-7.071 0 5 5 0 0 0 0 7.071 5 5 0 1 0 7.071-7.071zm-5.657 5.657a3 3 0 0 1-.586-3.415l4.001 4.001a3 3 0 0 1-3.415-.586zm4.829-.827-4.001-4.001a3.002 3.002 0 0 1 4.001 4.001z" fill="#00AEEC"/></svg>'},{}],bpe2E:[function(t,s,i){s.exports='<svg class="apd-icon apd-mode-2-on" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" data-pointer="none" style="enable-background:new 0 0 28 28" viewBox="0 0 28 28" width="28" height="28"><path d="M23 3H5a4 4 0 0 0-4 4v14a4 4 0 0 0 4 4h18a4 4 0 0 0 4-4V7a4 4 0 0 0-4-4zM9 21H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2z" fill="#FFF"/></svg>'},{}],kL9zy:[function(t,s,i){s.exports='<svg class="apd-icon apd-check-on" xmlns="http://www.w3.org/2000/svg" data-pointer="none" viewBox="0 0 32 32" width="32" height="32"><path d="m13 18.25-1.8-1.8c-.6-.6-1.65-.6-2.25 0s-.6 1.5 0 2.25l2.85 2.85c.318.318.762.468 1.2.448.438.02.882-.13 1.2-.448l8.85-8.85c.6-.6.6-1.65 0-2.25s-1.65-.6-2.25 0l-7.8 7.8zM8 4h16c2.21 0 4 1.79 4 4v16c0 2.21-1.79 4-4 4H8c-2.21 0-4-1.79-4-4V8c0-2.21 1.79-4 4-4z" fill="#00AEEC"/></svg>'},{}],"22xpM":[function(t,s,i){s.exports='<svg class="apd-icon apd-check-off" xmlns="http://www.w3.org/2000/svg" data-pointer="none" viewBox="0 0 32 32" width="32" height="32"><path d="M8 6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2H8zm0-2h16c2.21 0 4 1.79 4 4v16c0 2.21-1.79 4-4 4H8c-2.21 0-4-1.79-4-4V8c0-2.21 1.79-4 4-4z" fill="#FFF"/></svg>'},{}],"8AxLD":[function(t,s,i){var r=t("@parcel/transformer-js/src/esmodule-helpers.js");r.defineInteropFlag(i),r.export(i,"default",()=>d);let n={map:(l,h,c,u,g)=>(l-h)*(g-u)/(c-h)+u,range(l,h,c){let u=Math.round(l/c)*c;return Array.from({length:Math.floor((h-l)/c)},(g,f)=>f*c+u)}},o=(l,h)=>{let c=h[0]-l[0],u=h[1]-l[1];return{length:Math.sqrt(Math.pow(c,2)+Math.pow(u,2)),angle:Math.atan2(u,c)}};function d(l,h,c){let{query:u}=l.constructor.utils;l.controls.add({name:"heatmap",position:"top",html:"",style:{position:"absolute",top:"-100px",left:"0px",right:"0px",height:"100px",width:"100%",pointerEvents:"none"},mounted(g){let f=null,p=null;function y(v=[]){if(f=null,p=null,g.innerHTML="",!l.duration||l.option.isLive)return;let E={w:g.offsetWidth,h:g.offsetHeight},T={xMin:0,xMax:E.w,yMin:0,yMax:128,scale:.25,opacity:.2,minHeight:Math.floor(.05*E.h),sampling:Math.floor(E.w/100),smoothing:.2,flattening:.2};typeof c=="object"&&Object.assign(T,c);let S=[];if(Array.isArray(v)&&v.length)S=[...v];else{let B=l.duration/E.w;for(let N=0;N<=E.w;N+=T.sampling){let $=h.queue.filter(({time:D})=>D>N*B&&D<=(N+T.sampling)*B).length;S.push([N,$])}}if(S.length===0)return;let x=S[S.length-1],I=x[0],A=x[1];I!==E.w&&S.push([E.w,A]);let b=S.map(B=>B[1]),k=(Math.min(...b)+Math.max(...b))/2;for(let B=0;B<S.length;B++){let N=S[B],$=N[1];N[1]=$*($>k?1+T.scale:1-T.scale)+T.minHeight}let L=(B,N,$,D)=>{let C=o(N||B,$||B),O=n.map(Math.cos(C.angle)*T.flattening,0,1,1,0),P=C.angle*O+(D?Math.PI:0),M=C.length*T.smoothing;return[B[0]+Math.cos(P)*M,B[1]+Math.sin(P)*M]},F=(B,N,$)=>{let D=L($[N-1],$[N-2],B),C=L(B,$[N-1],$[N+1],!0),O=N===$.length-1?" z":"";return"C ".concat(D[0],",").concat(D[1]," ").concat(C[0],",").concat(C[1]," ").concat(B[0],",").concat(B[1]).concat(O)},U=S.map(B=>[n.map(B[0],T.xMin,T.xMax,0,E.w),n.map(B[1],T.yMin,T.yMax,E.h,0)]).reduce((B,N,$,D)=>$===0?"M ".concat(D[D.length-1][0],",").concat(E.h," L ").concat(N[0],",").concat(E.h," L ").concat(N[0],",").concat(N[1]):"".concat(B," ").concat(F(N,$,D)),"");g.innerHTML='<svg viewBox="0 0 '.concat(E.w," ").concat(E.h,'"><defs><linearGradient id="heatmap-solids" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" style="stop-color:var(--art-theme);stop-opacity:').concat(T.opacity,'" /><stop offset="0%" style="stop-color:var(--art-theme);stop-opacity:').concat(T.opacity,'" id="heatmap-start" /><stop offset="0%" style="stop-color:var(--art-progress-color);stop-opacity:1" id="heatmap-stop" /><stop offset="100%" style="stop-color:var(--art-progress-color);stop-opacity:1" /></linearGradient></defs><path fill="url(#heatmap-solids)" d="').concat(U,'"></path></svg>'),f=u("#heatmap-start",g),p=u("#heatmap-stop",g),f.setAttribute("offset","".concat(100*l.played,"%")),p.setAttribute("offset","".concat(100*l.played,"%"))}l.on("video:timeupdate",()=>{f&&p&&(f.setAttribute("offset","".concat(100*l.played,"%")),p.setAttribute("offset","".concat(100*l.played,"%")))}),l.on("setBar",(v,E)=>{f&&p&&v==="played"&&(f.setAttribute("offset","".concat(100*E,"%")),p.setAttribute("offset","".concat(100*E,"%")))}),l.on("ready",()=>y()),l.on("resize",()=>y()),l.on("artplayerPluginDanmuku:loaded",()=>y()),l.on("artplayerPluginDanmuku:points",v=>y(v))}})}},{"@parcel/transformer-js/src/esmodule-helpers.js":"9pCYc"}]},["bgm6t"],"bgm6t","parcelRequire4dc0")})(as,as.exports);var Aa=as.exports;const Ah=Xr(Aa);var Qr={exports:{}};(function(a,e){var t=function(s){var i=!1;try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){const v=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));v instanceof WebAssembly.Module&&(i=new WebAssembly.Instance(v)instanceof WebAssembly.Instance)}}catch(v){}console.log("WebAssembly support detected: "+(i?"yes":"no"));var r=this;r.canvas=s.canvas,r.renderMode=s.renderMode||(s.lossyRender?"lossy":"wasm-blend"),r.libassMemoryLimit=s.libassMemoryLimit||0,r.libassGlyphLimit=s.libassGlyphLimit||0,r.targetFps=s.targetFps||24,r.prescaleFactor=s.prescaleFactor||1,r.prescaleHeightLimit=s.prescaleHeightLimit||1080,r.maxRenderHeight=s.maxRenderHeight||0,r.dropAllAnimations=s.dropAllAnimations||!1,r.isOurCanvas=!1,r.video=s.video,r.canvasParent=null,r.fonts=s.fonts||[],r.availableFonts=s.availableFonts||[],r.fallbackFont=s.fallbackFont||"default.woff2",r.lazyFileLoading=s.lazyFileLoading||!1,r.onReadyEvent=s.onReady,i?r.workerUrl=s.workerUrl||"subtitles-octopus-worker.js":r.workerUrl=s.legacyWorkerUrl||"subtitles-octopus-worker-legacy.js",r.subUrl=s.subUrl,r.subContent=s.subContent||null,r.onErrorEvent=s.onError,r.debug=s.debug||!1,r.lastRenderTime=0,r.pixelRatio=window.devicePixelRatio||1,r.timeOffset=s.timeOffset||0,r.hasAlphaBug=!1,function(){if(typeof ImageData.prototype.constructor=="function")try{new window.ImageData(new Uint8ClampedArray([0,0,0,0]),1,1);return}catch(T){console.log("detected that ImageData is not constructable despite browser saying so")}var v=document.createElement("canvas"),E=v.getContext("2d");window.ImageData=function(){var T=0;if(arguments[0]instanceof Uint8ClampedArray)var S=arguments[T++];var x=arguments[T++],I=arguments[T],A=E.createImageData(x,I);return S&&A.data.set(S),A}}(),r.workerError=function(v){if(console.error("Worker error: ",v),r.onErrorEvent&&r.onErrorEvent(v),!r.debug)throw r.dispose(),new Error("Worker error: "+v)},r.init=function(){if(!window.Worker){r.workerError("worker not supported");return}r.worker||(r.worker=new Worker(r.workerUrl),r.worker.addEventListener("message",r.onWorkerMessage),r.worker.addEventListener("error",r.workerError)),r.workerActive=!1,r.createCanvas(),r.setVideo(s.video),r.setSubUrl(s.subUrl),r.worker.postMessage({target:"worker-init",width:r.canvas.width,height:r.canvas.height,URL:document.URL,currentScript:r.workerUrl,preMain:!0,renderMode:r.renderMode,subUrl:r.subUrl,subContent:r.subContent,fonts:r.fonts,availableFonts:r.availableFonts,fallbackFont:r.fallbackFont,lazyFileLoading:r.lazyFileLoading,debug:r.debug,targetFps:r.targetFps,libassMemoryLimit:r.libassMemoryLimit,libassGlyphLimit:r.libassGlyphLimit,dropAllAnimations:r.dropAllAnimations})},r.createCanvas=function(){r.canvas||(r.video?(r.isOurCanvas=!0,r.canvas=document.createElement("canvas"),r.canvas.className="libassjs-canvas",r.canvas.style.display="none",r.canvasParent=document.createElement("div"),r.canvasParent.className="libassjs-canvas-parent",r.canvasParent.appendChild(r.canvas),r.video.nextSibling?r.video.parentNode.insertBefore(r.canvasParent,r.video.nextSibling):r.video.parentNode.appendChild(r.canvasParent)):r.canvas||r.workerError("Don't know where to render: you should give video or canvas in options.")),r.ctx=r.canvas.getContext("2d"),r.bufferCanvas=document.createElement("canvas"),r.bufferCanvasCtx=r.bufferCanvas.getContext("2d"),r.bufferCanvas.width=1,r.bufferCanvas.height=1;var v=new Uint8ClampedArray([0,255,0,0]),E=new ImageData(v,1,1);r.bufferCanvasCtx.clearRect(0,0,1,1),r.ctx.clearRect(0,0,1,1);var T=r.ctx.getImageData(0,0,1,1).data;r.bufferCanvasCtx.putImageData(E,0,0),r.ctx.drawImage(r.bufferCanvas,0,0);var S=r.ctx.getImageData(0,0,1,1).data;r.hasAlphaBug=T[1]!=S[1],r.hasAlphaBug&&console.log("Detected a browser having issue with transparent pixels, applying workaround")};function n(){r.setCurrentTime(r.video.currentTime+r.timeOffset)}function o(){r.setIsPaused(!1,r.video.currentTime+r.timeOffset)}function d(){r.setIsPaused(!0,r.video.currentTime+r.timeOffset)}function l(){r.video.removeEventListener("timeupdate",n,!1)}function h(){r.video.addEventListener("timeupdate",n,!1);var v=r.video.currentTime+r.timeOffset;r.setCurrentTime(v)}function c(){r.setRate(r.video.playbackRate)}function u(){r.setIsPaused(!0,r.video.currentTime+r.timeOffset)}function g(v){v.target.removeEventListener(v.type,g,!1),r.resize()}r.setVideo=function(v){r.video=v,r.video&&(r.video.addEventListener("timeupdate",n,!1),r.video.addEventListener("playing",o,!1),r.video.addEventListener("pause",d,!1),r.video.addEventListener("seeking",l,!1),r.video.addEventListener("seeked",h,!1),r.video.addEventListener("ratechange",c,!1),r.video.addEventListener("waiting",u,!1),document.addEventListener("fullscreenchange",r.resizeWithTimeout,!1),document.addEventListener("mozfullscreenchange",r.resizeWithTimeout,!1),document.addEventListener("webkitfullscreenchange",r.resizeWithTimeout,!1),document.addEventListener("msfullscreenchange",r.resizeWithTimeout,!1),window.addEventListener("resize",r.resizeWithTimeout,!1),typeof ResizeObserver<"u"&&(r.ro=new ResizeObserver(r.resizeWithTimeout),r.ro.observe(r.video)),r.video.videoWidth>0?r.resize():r.video.addEventListener("loadedmetadata",g,!1))},r.getVideoPosition=function(){var v=r.video.videoWidth/r.video.videoHeight,E=r.video.offsetWidth,T=r.video.offsetHeight,S=E/T,x=E,I=T;S>v?x=Math.floor(T*v):I=Math.floor(E/v);var A=(E-x)/2,b=(T-I)/2;return{width:x,height:I,x:A,y:b}},r.setSubUrl=function(v){r.subUrl=v},r.renderFrameData=null;function f(){var v=r.renderFramesData,E=performance.now();r.ctx.clearRect(0,0,r.canvas.width,r.canvas.height);for(var T=0;T<v.canvases.length;T++){var S=v.canvases[T];r.bufferCanvas.width=S.w,r.bufferCanvas.height=S.h;var x=new Uint8ClampedArray(S.buffer);if(r.hasAlphaBug)for(var I=3;I<x.length;I=I+4)x[I]=x[I]>=1?x[I]:1;var A=new ImageData(x,S.w,S.h);r.bufferCanvasCtx.putImageData(A,0,0),r.ctx.drawImage(r.bufferCanvas,S.x,S.y)}if(r.debug){var b=Math.round(performance.now()-E),k=v.blendTime;console.log(typeof k<"u"?"render: "+Math.round(v.spentTime-k)+" ms, blend: "+Math.round(k)+" ms, draw: "+b+" ms; TOTAL="+Math.round(v.spentTime+b)+" ms":Math.round(v.spentTime)+" ms (+ "+b+" ms draw)"),r.renderStart=performance.now()}}function p(){var v=r.renderFramesData,E=performance.now();r.ctx.clearRect(0,0,r.canvas.width,r.canvas.height);for(var T=0;T<v.bitmaps.length;T++){var S=v.bitmaps[T];r.ctx.drawImage(S.bitmap,S.x,S.y)}if(r.debug){var x=Math.round(performance.now()-E);console.log(v.bitmaps.length+" bitmaps, libass: "+Math.round(v.libassTime)+"ms, decode: "+Math.round(v.decodeTime)+"ms, draw: "+x+"ms"),r.renderStart=performance.now()}}r.workerActive=!1,r.frameId=0,r.onWorkerMessage=function(v){r.workerActive||(r.workerActive=!0,r.onReadyEvent&&r.onReadyEvent());var E=v.data;switch(E.target){case"stdout":{console.log(E.content);break}case"console-log":{console.log.apply(console,JSON.parse(E.content));break}case"console-debug":{console.debug.apply(console,JSON.parse(E.content));break}case"console-info":{console.info.apply(console,JSON.parse(E.content));break}case"console-warn":{console.warn.apply(console,JSON.parse(E.content));break}case"console-error":{console.error.apply(console,JSON.parse(E.content));break}case"stderr":{console.error(E.content);break}case"window":{window[E.method]();break}case"canvas":{switch(E.op){case"getContext":{r.ctx=r.canvas.getContext(E.type,E.attributes);break}case"resize":{r.resize(E.width,E.height);break}case"renderCanvas":{r.lastRenderTime<E.time&&(r.lastRenderTime=E.time,r.renderFramesData=E,window.requestAnimationFrame(f));break}case"renderFastCanvas":{r.lastRenderTime<E.time&&(r.lastRenderTime=E.time,r.renderFramesData=E,window.requestAnimationFrame(p));break}case"setObjectProperty":{r.canvas[E.object][E.property]=E.value;break}default:throw"eh?"}break}case"tick":{r.frameId=E.id,r.worker.postMessage({target:"tock",id:r.frameId});break}case"custom":{if(r.onCustomMessage)r.onCustomMessage(v);else throw"Custom message received but client onCustomMessage not implemented.";break}case"setimmediate":{r.worker.postMessage({target:"setimmediate"});break}case"get-events":break;case"get-styles":break;case"ready":break;default:throw"what? "+E.target}};function y(v,E){var T=r.prescaleFactor<=0?1:r.prescaleFactor;if(E<=0||v<=0)v=0,E=0;else{var S=T<1?-1:1,x=E;S*x*T<=S*r.prescaleHeightLimit?x*=T:S*x<S*r.prescaleHeightLimit&&(x=r.prescaleHeightLimit),r.maxRenderHeight>0&&x>r.maxRenderHeight&&(x=r.maxRenderHeight),v*=x/E,E=x}return{width:v,height:E}}r.resize=function(v,E,T,S){var x=null;if(T=T||0,S=S||0,(!v||!E)&&r.video){x=r.getVideoPosition();var I=y(x.width*r.pixelRatio,x.height*r.pixelRatio);v=I.width,E=I.height;var A=r.canvasParent.getBoundingClientRect().top-r.video.getBoundingClientRect().top;T=x.y-A,S=x.x}if(!v||!E){r.video||console.error("width or height is 0. You should specify width & height for resize.");return}(r.canvas.width!=v||r.canvas.height!=E||r.canvas.style.top!=T||r.canvas.style.left!=S)&&(r.canvas.width=v,r.canvas.height=E,x!=null&&(r.canvasParent.style.position="relative",r.canvas.style.display="block",r.canvas.style.position="absolute",r.canvas.style.width=x.width+"px",r.canvas.style.height=x.height+"px",r.canvas.style.top=T+"px",r.canvas.style.left=S+"px",r.canvas.style.pointerEvents="none"),r.worker.postMessage({target:"canvas",width:r.canvas.width,height:r.canvas.height}))},r.resizeWithTimeout=function(){r.resize(),setTimeout(r.resize,100)},r.runBenchmark=function(){r.worker.postMessage({target:"runBenchmark"})},r.customMessage=function(v,E){E=E||{},r.worker.postMessage({target:"custom",userData:v,preMain:E.preMain})},r.setCurrentTime=function(v){r.worker.postMessage({target:"video",currentTime:v})},r.setTrackByUrl=function(v){r.worker.postMessage({target:"set-track-by-url",url:v})},r.setTrack=function(v){r.worker.postMessage({target:"set-track",content:v})},r.freeTrack=function(v){r.worker.postMessage({target:"free-track"})},r.render=r.setCurrentTime,r.setIsPaused=function(v,E){r.worker.postMessage({target:"video",isPaused:v,currentTime:E})},r.setRate=function(v){r.worker.postMessage({target:"video",rate:v})},r.dispose=function(){r.worker.postMessage({target:"destroy"}),r.worker.terminate(),r.worker.removeEventListener("message",r.onWorkerMessage),r.worker.removeEventListener("error",r.workerError),r.workerActive=!1,r.worker=null,r.video&&(r.video.removeEventListener("timeupdate",n,!1),r.video.removeEventListener("playing",o,!1),r.video.removeEventListener("pause",d,!1),r.video.removeEventListener("seeking",l,!1),r.video.removeEventListener("seeked",h,!1),r.video.removeEventListener("ratechange",c,!1),r.video.removeEventListener("waiting",u,!1),r.video.removeEventListener("loadedmetadata",g,!1),document.removeEventListener("fullscreenchange",r.resizeWithTimeout,!1),document.removeEventListener("mozfullscreenchange",r.resizeWithTimeout,!1),document.removeEventListener("webkitfullscreenchange",r.resizeWithTimeout,!1),document.removeEventListener("msfullscreenchange",r.resizeWithTimeout,!1),window.removeEventListener("resize",r.resizeWithTimeout,!1),r.video.parentNode.removeChild(r.canvasParent),r.video=null),r.ro&&(r.ro.disconnect(),r.ro=null),r.onCustomMessage=null,r.onErrorEvent=null,r.onReadyEvent=null},r.fetchFromWorker=function(v,E,T){try{var S=v.target,x=setTimeout(function(){A(Error("Error: Timeout while try to fetch "+S))},5e3),I=function(b){b.data.target==S&&(E(b.data),r.worker.removeEventListener("message",I),r.worker.removeEventListener("error",A),clearTimeout(x))},A=function(b){T(b),r.worker.removeEventListener("message",I),r.worker.removeEventListener("error",A),clearTimeout(x)};r.worker.addEventListener("message",I),r.worker.addEventListener("error",A),r.worker.postMessage(v)}catch(b){T(b)}},r.createEvent=function(v){r.worker.postMessage({target:"create-event",event:v})},r.getEvents=function(v,E){r.fetchFromWorker({target:"get-events"},function(T){v(T.events)},E)},r.setEvent=function(v,E){r.worker.postMessage({target:"set-event",event:v,index:E})},r.removeEvent=function(v){r.worker.postMessage({target:"remove-event",index:v})},r.createStyle=function(v){r.worker.postMessage({target:"create-style",style:v})},r.getStyles=function(v,E){r.fetchFromWorker({target:"get-styles"},function(T){v(T.styles)},E)},r.setStyle=function(v,E){r.worker.postMessage({target:"set-style",style:v,index:E})},r.removeStyle=function(v){r.worker.postMessage({target:"remove-style",index:v})},r.init()};typeof SubtitlesOctopusOnLoad=="function"&&SubtitlesOctopusOnLoad(),a.exports&&(a.exports=t)})(Qr);var La=Qr.exports;const ba=Xr(La),Ia= window.__dynamic_base__+"/assets/subtitles-octopus-worker-f95f2186.js",Ra= window.__dynamic_base__+"/assets/subtitles-octopus-worker-62892886.wasm",Da= window.__dynamic_base__+"/assets/TimesNewRoman-d9fb32eb.ttf",_a= window.__dynamic_base__+"/assets/SourceHanSansCN-Bold-b5627435.woff2";let Pe=null;function ka(a){return/^https?:\/\//.test(a)}function os(a){return ka(a)?a:new URL(a,document.baseURI).toString()}function Ca({workerUrl:a,wasmUrl:e}){return new Promise(t=>{fetch(a).then(s=>s.text()).then(s=>{let i=s;i=i.replace(/wasmBinaryFile\s*=\s*"(subtitles-octopus-worker\.wasm)"/g,(n,o)=>(e?e=os(e):e=new URL(o,os(a)).toString(),'wasmBinaryFile = "'.concat(e,'"')));const r=new Blob([i],{type:"text/javascript"});t(URL.createObjectURL(r))})})}function Ss(a){Pe.canvasParent&&(Pe.canvasParent.style.display=a?"block":"none")}function Lh(a){return async e=>(Pe=new ba({availableFonts:{"times new roman":os(Da)},workerUrl:await Ca({workerUrl:Ia,wasmUrl:Ra}),fallbackFont:os(_a),video:e.template.$video,...a}),Pe.canvasParent.className="artplayer-plugin-ass",Pe.canvasParent.style.cssText="\n position: absolute;\n width: 100%;\n height: 100%;\n user-select: none;\n pointer-events: none;\n z-index: 20;\n ",e.on("artplayer-plugin-ass:switch",t=>{Pe.freeTrack(),Pe.setTrackByUrl(t),Ss(!0)}),e.on("subtitle",t=>Ss(t)),e.on("artplayer-plugin-ass:visible",t=>Ss(t)),e.on("subtitleOffset",t=>Pe.timeOffset=t),e.on("destroy",()=>Pe.dispose()),{name:"artplayerPluginAss",instance:Pe})}const G=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Pa=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=wa},wa=Number.MAX_SAFE_INTEGER||9007199254740991;let H=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),_=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a}({}),m=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a}({});var Z={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},V={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class nt{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Oa{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new nt(e),this.fast_=new nt(t),this.defaultTTFB_=i,this.ttfb_=new nt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new nt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new nt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new nt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Fa(a,e,t){return(e=Na(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function re(){return re=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},re.apply(null,arguments)}function Mi(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function se(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Mi(Object(t),!0).forEach(function(s){Fa(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):Mi(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function Ma(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function Na(a){var e=Ma(a,"string");return typeof e=="symbol"?e:e+""}class Ke{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s="[".concat(e,"]:");this.trace=Ye,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Ye=function(){},$a={trace:Ye,debug:Ye,log:Ye,warn:Ye,info:Ye,error:Ye};function Ws(){return re({},$a)}function Ba(a,e){const t=self.console[a];return t?t.bind(self.console,"".concat(e?"["+e+"] ":"","[").concat(a,"] >")):Ye}function Ni(a,e,t){return e[a]?e[a].bind(e):Ba(a,t)}const Ys=Ws();function Ua(a,e,t){const s=Ws();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Ni(r,a,t)});try{s.log('Debug logs enabled for "'.concat(e,'" in hls.js version 1.6.5'))}catch(r){return Ws()}i.forEach(r=>{Ys[r]=Ni(r,a)})}else re(Ys,s);return s}const te=Ys;function qe(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ga(a){return typeof self<"u"&&a===self.ManagedMediaSource}function Zr(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function Se(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}const Oe={hexDump:function(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}};function Va(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var xs={exports:{}},$i;function Ka(){return $i||($i=1,function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(d,l,h){if(h=h||{},d=d.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return d;var c=o.parseURL(d);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return h.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):l;var g=o.parseURL(d);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(p.netLoc=g.netLoc,u.path[0]!=="/"))if(!u.path)p.path=g.path,u.params||(p.params=g.params,u.query||(p.query=g.query));else{var y=g.path,v=y.substring(0,y.lastIndexOf("/")+1)+u.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(p)},parseURL:function(d){var l=s.exec(d);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(d){for(d=d.split("").reverse().join("").replace(r,"");d.length!==(d=d.replace(n,"")).length;);return d.split("").reverse().join("")},buildURLFromParts:function(d){return d.scheme+d.netLoc+d.path+d.params+d.query+d.fragment}};a.exports=o})()}(xs)),xs.exports}var li=Ka();class di{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ne={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Jr{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Wa(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=(t==null?void 0:t.byteRangeEndOffset)||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ne.AUDIO]:null,[ne.VIDEO]:null,[ne.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new di),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=li.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ne.AUDIO]=null,e[ne.VIDEO]=null,e[ne.AUDIOVIDEO]=null}}function ge(a){return a.sn!=="initSegment"}class As extends Jr{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange){const e=this.byteRange[0],t=this.byteRange[1];if(G(e)&&G(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(s.length===1)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=G(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),s=t.length;if(s>1||s===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!G(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ge(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,d=o[e];if(!d){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}d.startPTS=Math.min(d.startPTS,t),d.endPTS=Math.max(d.endPTS,s),d.startDTS=Math.min(d.startDTS,i),d.endDTS=Math.max(d.endDTS,r)}}class Ha extends Jr{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function en(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||en(t,e)}}function Wa(a,e){const t=en(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const ls=Math.pow(2,32)-1,Ya=[].push,tn={video:1,audio:2,id3:3,text:4};function ce(a){return String.fromCharCode.apply(null,a)}function sn(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function Y(a,e){const t=rn(a,e);return t<0?4294967296+t:t}function Bi(a,e){let t=Y(a,e);return t*=Math.pow(2,32),t+=Y(a,e+4),t}function rn(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Ls(a,e,t){a[e]=t>>24,a[e+1]=t>>16&255,a[e+2]=t>>8&255,a[e+3]=t&255}function ja(a){const e=a.byteLength;for(let t=0;t<e;){const s=Y(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function Q(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=Y(a,i),n=ce(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const d=Q(a.subarray(i+8,o),e.slice(1));d.length&&Ya.apply(t,d)}i=o}return t}function qa(a){const e=[],t=a[0];let s=8;const i=Y(a,s);s+=4;let r=0,n=0;t===0?(r=Y(a,s),n=Y(a,s+4),s+=8):(r=Bi(a,s),n=Bi(a,s+8),s+=16),s+=2;let o=a.length+n;const d=sn(a,s);s+=2;for(let l=0;l<d;l++){let h=s;const c=Y(a,h);h+=4;const u=c&2147483647;if((c&2147483648)>>>31===1)return te.warn("SIDX has hierarchical references (not supported)"),null;const f=Y(a,h);h+=4,e.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+u-1}}),o+=u,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:d,references:e}}function nn(a){const e=[],t=Q(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=Q(r,["tkhd"])[0];if(n){let o=n[0];const d=Y(n,o===0?12:20),l=Q(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=Y(l,o===0?12:20),c=Q(r,["mdia","hdlr"])[0];if(c){const u=ce(c.subarray(8,12)),g={soun:ne.AUDIO,vide:ne.VIDEO}[u],f=Q(r,["mdia","minf","stbl","stsd"])[0],p=za(f);g?(e[d]={timescale:h,type:g,stsd:p},e[g]=se({timescale:h,id:d},p)):e[d]={timescale:h,type:u,stsd:p}}}}}return Q(a,["moov","mvex","trex"]).forEach(i=>{const r=Y(i,4),n=e[r];n&&(n.default={duration:Y(i,12),flags:Y(i,20)})}),e}function za(a){const e=a.subarray(8),t=e.subarray(8+78),s=ce(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=Q(e,[s])[0].subarray(s==="enca"?28:78);Q(l,["sinf"]).forEach(c=>{const u=Q(c,["schm"])[0];if(u){const g=ce(u.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=Q(c,["frma"])[0];f&&(i=ce(f))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const d=Q(t,["avcC"])[0];d&&d.length>3&&(i+="."+$t(d[1])+$t(d[2])+$t(d[3]),r=Nt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const d=Q(e,[s])[0],l=Q(d.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=bs(l,h),h+=2;const c=l[h++];if(c&128&&(h+=2),c&64&&(h+=l[h++]),l[h++]!==4)break;h=bs(l,h);const u=l[h++];if(u===64)i+="."+$t(u);else break;if(h+=12,l[h++]!==5)break;h=bs(l,h);const g=l[h++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[h]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const d=Q(t,["hvcC"])[0];if(d&&d.length>12){const l=d[1],h=["","A","B","C"][l>>6],c=l&31,u=Y(d,2),g=(l&32)>>5?"H":"L",f=d[12],p=d.subarray(6,12);i+="."+h+c,i+="."+Xa(u).toString(16).toUpperCase(),i+="."+g+f;let y="";for(let v=p.length;v--;){const E=p[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}i+=y}r=Nt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Nt(i,t)||i;break}case"vp09":{const d=Q(t,["vpcC"])[0];if(d&&d.length>6){const l=d[4],h=d[5],c=d[6]>>4&15;i+="."+we(l)+"."+we(h)+"."+we(c)}break}case"av01":{const d=Q(t,["av1C"])[0];if(d&&d.length>2){const l=d[1]>>>5,h=d[1]&31,c=d[2]>>>7?"H":"M",u=(d[2]&64)>>6,g=(d[2]&32)>>5,f=l===2&&u?g?12:10:u?10:8,p=(d[2]&16)>>4,y=(d[2]&8)>>3,v=(d[2]&4)>>2,E=d[2]&3,T=1,S=1,x=1,I=0;i+="."+l+"."+we(h)+c+"."+we(f)+"."+p+"."+y+v+E+"."+we(T)+"."+we(S)+"."+we(x)+"."+I,r=Nt("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function Nt(a,e){const t=Q(e,["dvvC"]),s=t.length?t[0]:Q(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+we(i)+"."+we(r)}}function Xa(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<32-1-t;return e>>>0}function bs(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function $t(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function we(a){return(a<10?"0":"")+a}function Qa(a,e){if(!a||!e)return a;const t=e.keyId;return t&&e.isCommonEncryption&&Q(a,["moov","trak"]).forEach(i=>{const n=Q(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=Q(n,["enca"]);const d=o.length>0;d||(o=Q(n,["encv"])),o.forEach(l=>{const h=d?l.subarray(28):l.subarray(78);Q(h,["sinf"]).forEach(u=>{const g=an(u);if(g){const f=g.subarray(8,24);f.some(p=>p!==0)||(te.log("[eme] Patching keyId in 'enc".concat(d?"a":"v",">sinf>>tenc' box: ").concat(Oe.hexDump(f)," -> ").concat(Oe.hexDump(t))),g.set(t,8))}})})}),a}function an(a){const e=Q(a,["schm"])[0];if(e){const t=ce(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return Q(a,["schi","tenc"])[0]}return null}function Za(a,e,t){const s={},i=Q(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=Q(n,["tfhd"])[0],d=Y(o,4),l=e[d];if(!l)continue;const h=s[d]||(s[d]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type}),c=Q(n,["tfdt"])[0];if(c){const T=c[0];let S=Y(c,4);T===1&&(S===ls?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=ls+1,S+=Y(c,8))),G(S)&&(!G(h.start)||S<h.start)&&(h.start=S)}const u=l.default,g=Y(o,0)|(u==null?void 0:u.flags);let f=(u==null?void 0:u.duration)||0;g&8&&(g&2?f=Y(o,12):f=Y(o,8));const p=Q(n,["trun"]);let y=h.start||0,v=0,E=f;for(let T=0;T<p.length;T++){const S=p[T],x=Y(S,4),I=h.sampleCount;h.sampleCount+=x;const A=S[3]&1,b=S[3]&4,k=S[2]&1,L=S[2]&2,F=S[2]&4,U=S[2]&8;let B=8,N=x;for(A&&(B+=4),b&&x&&(!(S[B+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=I),B+=4,k?(E=Y(S,B),B+=4):E=f,L&&(B+=4),U&&(B+=4),y+=E,v+=E,N--);N--;)k?(E=Y(S,B),B+=4):E=f,L&&(B+=4),F&&(S[B+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(N+1),h.keyFrameStart=y),B+=4),U&&(B+=4),y+=E,v+=E;!v&&f&&(v+=f*x)}h.duration+=v}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=Q(a,["sidx"]);for(let d=0;d<o.length;d++){const l=qa(o[d]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((c,u)=>c+u.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&G(n)&&Object.keys(s).forEach(d=>{s[d].duration||(s[d].duration=n*s[d].timescale-s[d].start)})}return s}function Ja(a,e,t){Q(e,["moof","traf"]).forEach(s=>{Q(s,["tfhd"]).forEach(i=>{const r=Y(i,4),n=a[r];if(!n)return;const o=n.timescale||9e4;Q(s,["tfdt"]).forEach(d=>{const l=d[0],h=t*o;if(h){let c=Y(d,4);if(l===0)c-=h,c=Math.max(c,0),Ls(d,4,c);else{c*=Math.pow(2,32),c+=Y(d,8),c-=h,c=Math.max(c,0);const u=Math.floor(c/(ls+1)),g=Math.floor(c%(ls+1));Ls(d,4,u),Ls(d,8,g)}}})})})}function eo(a){const e={valid:null,remainder:null},t=Q(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function Re(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Ui(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return Q(s,["moof"]).map(d=>{const l=d.byteOffset-8;Q(d,["traf"]).map(c=>{const u=Q(c,["tfdt"]).map(g=>{const f=g[0];let p=Y(g,4);return f===1&&(p*=Math.pow(2,32),p+=Y(g,8)),p/i})[0];return u!==void 0&&(a=u),Q(c,["tfhd"]).map(g=>{const f=Y(g,4),p=Y(g,0)&16777215,y=(p&1)!==0,v=(p&2)!==0,E=(p&8)!==0;let T=0;const S=(p&16)!==0;let x=0;const I=(p&32)!==0;let A=8;f===r&&(y&&(A+=8),v&&(A+=4),E&&(T=Y(g,A),A+=4),S&&(x=Y(g,A),A+=4),I&&(A+=4),e.type==="video"&&(n=Es(e.codec)),Q(c,["trun"]).map(b=>{const k=b[0],L=Y(b,0)&16777215,F=(L&1)!==0;let U=0;const B=(L&4)!==0,N=(L&256)!==0;let $=0;const D=(L&512)!==0;let C=0;const O=(L&1024)!==0,P=(L&2048)!==0;let M=0;const W=Y(b,4);let K=8;F&&(U=Y(b,K),K+=4),B&&(K+=4);let j=U+l;for(let q=0;q<W;q++){if(N?($=Y(b,K),K+=4):$=T,D?(C=Y(b,K),K+=4):C=x,O&&(K+=4),P&&(k===0?M=Y(b,K):M=rn(b,K),K+=4),e.type===ne.VIDEO){let X=0;for(;X<C;){const J=Y(s,j);if(j+=4,to(n,s[j])){const le=s.subarray(j,j+J);ci(le,n?2:1,a+M/i,t)}j+=J,X+=J+4}}a+=$/i}}))})})}),t}function Es(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function to(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ci(a,e,t,s){const i=on(a);let r=0;r+=e;let n=0,o=0,d=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;d=i[r++],n+=d}while(d===255);o=0;do{if(r>=i.length)break;d=i[r++],o+=d}while(d===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){te.error("Malformed SEI payload. ".concat(o," is too small, only ").concat(l," bytes left to parse."));break}if(n===4){if(i[h++]===181){const u=sn(i,h);if(h+=2,u===49){const g=Y(i,h);if(h+=4,g===1195456820){const f=i[h++];if(f===3){const p=i[h++],y=31&p,v=64&p,E=v?2+y*3:0,T=new Uint8Array(E);if(v){T[0]=p;for(let S=1;S<E;S++)T[S]=i[h++]}s.push({type:f,payloadType:n,pts:t,bytes:T})}}}}}else if(n===5&&o>16){const c=[];for(let f=0;f<16;f++){const p=i[h++].toString(16);c.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&c.push("-")}const u=o-16,g=new Uint8Array(u);for(let f=0;f<u;f++)g[f]=i[h++];s.push({payloadType:n,pts:t,uuid:c.join(""),userData:Se(g),userDataBytes:g})}}}function on(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function so(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,d=0,l=0;if(e===0){for(;ce(a.subarray(l,l+1))!=="\0";)t+=ce(a.subarray(l,l+1)),l+=1;for(t+=ce(a.subarray(l,l+1)),l+=1;ce(a.subarray(l,l+1))!=="\0";)s+=ce(a.subarray(l,l+1)),l+=1;s+=ce(a.subarray(l,l+1)),l+=1,i=Y(a,12),r=Y(a,16),o=Y(a,20),d=Y(a,24),l=28}else if(e===1){l+=4,i=Y(a,l),l+=4;const c=Y(a,l);l+=4;const u=Y(a,l);for(l+=4,n=2**32*c+u,Pa(n)||(n=Number.MAX_SAFE_INTEGER,te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(a,l),l+=4,d=Y(a,l),l+=4;ce(a.subarray(l,l+1))!=="\0";)t+=ce(a.subarray(l,l+1)),l+=1;for(t+=ce(a.subarray(l,l+1)),l+=1;ce(a.subarray(l,l+1))!=="\0";)s+=ce(a.subarray(l,l+1)),l+=1;s+=ce(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:d,payload:h}}function io(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function ro(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),io([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t||new Uint8Array)}function no(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=ao(i);e.push(r),s+=r.size}}return e}function ao(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=Oe.hexDump(new Uint8Array(n,t+12,16)),d=a.getUint32(28);let l=null,h=null;if(r===0){if(e-32<d||d<22)return{offset:t,size:e};h=new Uint8Array(n,t+32,d)}else if(r===1){if(!d||s<t+32+d*16+16)return{offset:t,size:e};l=[];for(let c=0;c<d;c++)l.push(new Uint8Array(n,t+32+c*16,16))}return{version:r,systemId:o,kids:l,data:h,offset:t,size:e}}const ln=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),gt={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function dn(a,e){const t=gt[e];return!!t&&!!t[a.slice(0,4)]}function js(a,e,t=!0){return!a.split(",").some(s=>!cn(s,e,t))}function cn(a,e,t=!0){var s;const i=qe(t);return(s=i==null?void 0:i.isTypeSupported(Rt(a,e)))!=null?s:!1}function Rt(a,e){return"".concat(e,"/mp4;codecs=").concat(a)}function Gi(a){if(a){const e=a.substring(0,4);return gt.video[e]}return 2}function ds(a){const e=ln();return a.split(",").reduce((t,s)=>{const r=e&&Es(s)?9:gt.video[s];return r?(r*2+t)/(t?3:2):(gt.audio[s]+t)/(t?2:1)},0)}const Is={};function oo(a,e=!0){if(Is[a])return Is[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(cn(t[i],"audio",e))return Is[a]=t[i],t[i];if(t[i]==="mp3"&&(s=qe(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const lo=/flac|opus|mp4a\.40\.34/i;function cs(a,e=!0){return a.replace(lo,t=>oo(t.toLowerCase(),e))}function co(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)dn(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function Zt(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function ho(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]="avc1.".concat(parseInt(s[1]).toString(16)).concat(("000"+parseInt(s[2]).toString(16)).slice(-4)))}return e.join(",")}function uo(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function Vi(a){const e=qe(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function hn(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const un={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function fn(a,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:a}}const Ki={};function fo(a,e,t,s,i,r){const n=a.audioCodec?a.audioGroups:null,o=r==null?void 0:r.audioCodec,d=r==null?void 0:r.channels,l=d?parseInt(d):o?1/0:2;let h=null;if(n!=null&&n.length)try{n.length===1&&n[0]?h=e.groups[n[0]].channels:h=n.reduce((c,u)=>{if(u){const g=e.groups[u];if(!g)throw new Error("Audio track group ".concat(u," not found"));Object.keys(g.channels).forEach(f=>{c[f]=(c[f]||0)+g.channels[f]})}return c},{2:0})}catch(c){return!0}return a.videoCodec!==void 0&&(a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!h&&G(l)&&Object.keys(h).some(c=>parseInt(c)>l)}function gn(a,e,t){const s=a.videoCodec,i=a.audioCodec;if(!s&&!i||!t)return Promise.resolve(un);const r=[];if(s){const n={width:a.width,height:a.height,bitrate:Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)),framerate:a.frameRate||30},o=a.videoRange;o!=="SDR"&&(n.transferFunction=o.toLowerCase());const d=s.split(","),l=navigator.userAgent;if(d.some(h=>Es(h))&&ln())return Promise.resolve(fn(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (".concat(l,")")),r));r.push.apply(r,d.map(h=>({type:"media-source",video:se(se({},n),{},{contentType:Rt(uo(h),"video")})})))}return i&&a.audioGroups&&a.audioGroups.forEach(n=>{var o;n&&((o=e.groups[n])==null||o.tracks.forEach(d=>{if(d.groupId===n){const l=d.channels||"",h=parseFloat(l);G(h)&&h>2&&r.push.apply(r,i.split(",").map(c=>({type:"media-source",audio:{contentType:Rt(c,"audio"),channels:""+h}})))}}))}),Promise.all(r.map(n=>{const o=go(n);return Ki[o]||(Ki[o]=t.decodingInfo(n))})).then(n=>({supported:!n.some(o=>!o.supported),configurations:r,decodingInfoResults:n})).catch(n=>({supported:!1,configurations:r,decodingInfoResults:[],error:n}))}function go(a){const{audio:e,video:t}=a,s=t||e;if(s){const i=hn(s.contentType);if(t)return"r".concat(t.height,"x").concat(t.width,"f").concat(Math.ceil(t.framerate)).concat(t.transferFunction||"sd","_").concat(i,"_").concat(Math.ceil(t.bitrate/1e5));if(e)return"c".concat(e.channels).concat(e.spatialRendering?"s":"n","_").concat(i)}return""}const qs=["NONE","TYPE-0","TYPE-1",null];function mo(a){return qs.indexOf(a)>-1}const hs=["SDR","PQ","HLG"];function po(a){return!!a&&hs.indexOf(a)>-1}var Jt={No:"",Yes:"YES",v2:"v2"};function Hi(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?Jt.v2:Jt.Yes:Jt.No}class Wi{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Dt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=",".concat(s.substring(0,4)))}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Yi(this._audioGroups,e)}hasSubtitleGroup(e){return Yi(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Yi(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function yo(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function vo(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||hs.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&yo(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Eo=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ae=(a,e)=>JSON.stringify(a,Eo(e));function To(a,e,t,s,i){const r=Object.keys(a),n=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,d=i==null?void 0:i.videoCodec,l=n&&parseInt(n)===2;let h=!1,c=!1,u=1/0,g=1/0,f=1/0,p=1/0,y=0,v=[];const{preferHDR:E,allowedVideoRanges:T}=vo(e,i);for(let b=r.length;b--;){const k=a[r[b]];h||(h=k.channels[2]>0),u=Math.min(u,k.minHeight),g=Math.min(g,k.minFramerate),f=Math.min(f,k.minBitrate),T.filter(F=>k.videoRanges[F]>0).length>0&&(c=!0)}u=G(u)?u:0,g=G(g)?g:0;const S=Math.max(1080,u),x=Math.max(30,g);f=G(f)?f:t,t=Math.max(f,t),c||(e=void 0);const I=r.length>1;return{codecSet:r.reduce((b,k)=>{const L=a[k];if(k===b)return b;if(v=c?T.filter(F=>L.videoRanges[F]>0):[],I){if(L.minBitrate>t)return Ce(k,"min bitrate of ".concat(L.minBitrate," > current estimate of ").concat(t)),b;if(!L.hasDefaultAudio)return Ce(k,"no renditions with default or auto-select sound found"),b;if(o&&k.indexOf(o.substring(0,4))%5!==0)return Ce(k,'audio codec preference "'.concat(o,'" not found')),b;if(n&&!l){if(!L.channels[n])return Ce(k,"no renditions with ".concat(n," channel sound found (channels options: ").concat(Object.keys(L.channels),")")),b}else if((!o||l)&&h&&L.channels[2]===0)return Ce(k,"no renditions with stereo sound found"),b;if(L.minHeight>S)return Ce(k,"min resolution of ".concat(L.minHeight," > maximum of ").concat(S)),b;if(L.minFramerate>x)return Ce(k,"min framerate of ".concat(L.minFramerate," > maximum of ").concat(x)),b;if(!v.some(F=>L.videoRanges[F]>0))return Ce(k,"no variants with VIDEO-RANGE of ".concat(ae(v)," found")),b;if(d&&k.indexOf(d.substring(0,4))%5!==0)return Ce(k,'video codec preference "'.concat(d,'" not found')),b;if(L.maxScore<y)return Ce(k,"max score of ".concat(L.maxScore," < selected max of ").concat(y)),b}return b&&(ds(k)>=ds(b)||L.fragmentError>a[b].fragmentError)?b:(p=L.minIndex,y=L.maxScore,k)},void 0),videoRanges:v,preferHDR:E,minFramerate:g,minBitrate:f,minIndex:p}}function Ce(a,e){te.log('[abr] start candidates with "'.concat(a,'" ignored because ').concat(e))}function mn(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function So(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let d=i[r.codecSet];d||(i[r.codecSet]=d={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),d.minBitrate=Math.min(d.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return d.minHeight=Math.min(d.minHeight,l),d.minFramerate=Math.min(d.minFramerate,r.frameRate),d.minIndex=Math.min(d.minIndex,n),d.maxScore=Math.max(d.maxScore,r.score),d.fragmentError+=r.fragmentError,d.videoRanges[r.videoRange]=(d.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const c=e.groups[h];c&&(d.hasDefaultAudio=d.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(u=>{d.channels[u]=(d.channels[u]||0)+c.channels[u]}))}),i},{})}function ji(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function Me(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(tt(a,i,t))return s}return-1}function tt(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,d=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||xo(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(d===void 0||e.forced===d)&&(!("characteristics"in a)||Ao(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function xo(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function Ao(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function Je(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Lo(a,e,t,s,i){const r=e[s],o=e.reduce((u,g,f)=>{const p=g.uri;return(u[p]||(u[p]=[])).push(f),u},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const d=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),c=qi(e,s,u=>{if(u.videoRange!==d||u.frameRate!==l||u.codecSet.substring(0,4)!==h)return!1;const g=u.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return Me(a,f,i)>-1});return c>-1?c:qi(e,s,u=>{const g=u.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return Me(a,f,i)>-1})}function qi(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function us(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class bo extends Ke{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:d}=n;if(!i||!d)return;const l=performance.now(),h=r?r.stats:i.stats,c=r?r.duration:i.duration,u=l-h.loading.start,g=n.minAutoLevel,f=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==f,v=!!t||y;if(!v&&(d.paused||!d.playbackRate||!d.readyState))return;const E=n.mainForwardBufferInfo;if(!v&&E===null)return;const T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(d.playbackRate);if(u<=Math.max(T,1e3*(c/(S*2))))return;const x=E?E.len/S:0,I=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&I>-1,b=this.getBwEstimate(),k=n.levels,L=k[f],F=Math.max(h.loaded,Math.round(c*(i.bitrate||L.averageBitrate)/8));let U=A?u-I:u;U<1&&A&&(U=Math.min(u,h.loaded*8/b));const B=A?h.loaded*1e3/U:0,N=T/1e3,$=B?(F-h.loaded)/B:F*8/b+N;if($<=x)return;const D=B?B*8:b,C=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,O=this.hls.config.abrBandWidthUpFactor;let P=Number.POSITIVE_INFINITY,M;for(M=f-1;M>g;M--){const q=k[M].maxBitrate,X=!k[M].details||C;if(P=this.getTimeToLoadFrag(N,D,c*q,X),P<Math.min(x,c+N))break}if(P>=$||P>c*10)return;A?this.bwEstimator.sample(u-Math.min(T,I),h.loaded):this.bwEstimator.sampleTTFB(u);const W=k[M].maxBitrate;this.getBwEstimate()*O>W&&this.resetEstimator(W);const K=this.findBestLevel(W,g,M,0,x,1,1);K>-1&&(M=K),this.warn("Fragment ".concat(i.sn).concat(r?" part "+r.index:""," of level ").concat(f," is loading too slowly;\n Fragment duration: ").concat(i.duration.toFixed(3),"\n Time to underbuffer: ").concat(x.toFixed(3)," s\n Estimated load time for current fragment: ").concat($.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(P.toFixed(3)," s\n TTFB estimate: ").concat(I|0," ms\n Current BW estimate: ").concat(G(b)?b|0:"Unknown"," bps\n New BW estimate: ").concat(this.getBwEstimate()|0," bps\n Switching to level ").concat(M," @ ").concat(W|0," bps")),n.nextLoadLevel=n.nextAutoLevel=M,this.clearTimer();const j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===M&&M>0){const q=this.getStarvationDelay();if(this.warn("Aborting inflight request ".concat(M>0?"and switching down":"","\n Fragment duration: ").concat(i.duration.toFixed(3)," s\n Time to underbuffer: ").concat(q.toFixed(3)," s")),i.abortRequests(),this.fragCurrent=this.partCurrent=null,M>g){let X=this.findBestLevel(this.hls.levels[g].bitrate,g,M,0,q,1,1);X===-1&&(X=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=X,this.resetEstimator(this.hls.levels[X].bitrate)}}};y||$>P*2?j():this.timer=self.setInterval(j,P*1e3),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log("setting initial bwe to ".concat(e)),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Oa(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,d=n-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(d-Math.min(c,l),o.loaded)}else this.bwEstimator.sampleTTFB(d)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;G(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===V.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,d=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:d},n.realBitrate=Math.round(8*o/d)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==V.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(n," clamped to ").concat(o)),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,d=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(d,n,i,l,0,h,c);if(y>=0)return this.rebufferNotice=-1,y}let u=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(u=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info("bitrate test took ".concat(Math.round(1e3*y),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*u)," ms")),h=c=1)}const g=this.findBestLevel(d,n,i,l,u,h,c);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info("".concat(l?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(g))),g>-1)return g;const f=s.levels[n],p=s.loadLevelObj;return p&&(f==null?void 0:f.bitrate)<p.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var d;const l=i+r,h=this.lastLoadedFragLevel,c=h===-1?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:g}=this,{levels:f,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(f.length===1)return 0;const E=f[c],T=!!((d=this.hls.latestLevelDetails)!=null&&d.live),S=y===-1||h===-1;let x,I="SDR",A=(E==null?void 0:E.frameRate)||0;const{audioPreference:b,videoPreference:k}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=mn(p));let F=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const D=this.codecTiers||(this.codecTiers=So(f,L,t,s)),C=To(D,I,e,b,k),{codecSet:O,videoRanges:P,minFramerate:M,minBitrate:W,minIndex:K,preferHDR:j}=C;F=K,x=O,I=j?P[P.length-1]:P[0],A=M,e=Math.max(e,W),this.log("picked start tier ".concat(ae(C)))}else x=E==null?void 0:E.codecSet,I=E==null?void 0:E.videoRange;const U=g?g.duration:u?u.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,N=[];for(let D=s;D>=t;D--){var $;const C=f[D],O=D>c;if(!C)continue;if(v.useMediaCapabilities&&!C.supportedResult&&!C.supportedPromise){const X=navigator.mediaCapabilities;typeof(X==null?void 0:X.decodingInfo)=="function"&&(fo(C,L,I,A,e,b)||Es(C.videoCodec))?(C.supportedPromise=gn(C,L,X),C.supportedPromise.then(J=>{if(!this.hls)return;C.supportedResult=J;const le=this.hls.levels,ue=le.indexOf(C);J.error?this.warn('MediaCapabilities decodingInfo error: "'.concat(J.error,'" for level ').concat(ue," ").concat(ae(J))):J.supported||(this.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(ue," ").concat(ae(J))),ue>-1&&le.length>1&&(this.log("Removing unsupported level ".concat(ue)),this.hls.removeLevel(ue),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):C.supportedResult=un}if((x&&C.codecSet!==x||I&&C.videoRange!==I||O&&A>C.frameRate||!O&&A>0&&A<C.frameRate||C.supportedResult&&!(($=C.supportedResult.decodingInfoResults)!=null&&$[0].smooth))&&(!S||D!==F)){N.push(D);continue}const P=C.details,M=(g?P==null?void 0:P.partTarget:P==null?void 0:P.averagetargetduration)||U;let W;O?W=o*e:W=n*e;const K=U&&i>=U*2&&r===0?C.averageBitrate:C.maxBitrate,j=this.getTimeToLoadFrag(B,W,K*M,P===void 0);if(W>=K&&(D===h||C.loadError===0&&C.fragmentError===0)&&(j<=B||!G(j)||T&&!this.bitrateTestDelay||j<l)){const X=this.forcedAutoLevel;return D!==y&&(X===-1||X!==y)&&(N.length&&this.trace("Skipped level(s) ".concat(N.join(",")," of ").concat(s,' max with CODECS and VIDEO-RANGE:"').concat(f[N[0]].codecs,'" ').concat(f[N[0]].videoRange,'; not compatible with "').concat(x,'" ').concat(I)),this.info("switch candidate:".concat(c,"->").concat(D," adjustedbw(").concat(Math.round(W),")-bitrate=").concat(Math.round(W-K)," ttfb:").concat(B.toFixed(1)," avgDuration:").concat(M.toFixed(1)," maxFetchDuration:").concat(l.toFixed(1)," fetchDuration:").concat(j.toFixed(1)," firstSelection:").concat(S," codecSet:").concat(C.codecSet," videoRange:").concat(C.videoRange," hls.loadLevel:").concat(y))),S&&(this.firstSelection=D),D}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const pn={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function Io(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!G(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<a.length;++r){const n=a[r];if(Do(e,t,n))return n}return null}function st(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&a.level!==r.level&&r.end<=a.end&&(r=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&zi(t,s,r)===0||Ro(r,a,Math.min(i,s))))return r;const n=pn.search(e,zi.bind(null,t,s));return n&&(n!==a||!r)?n:r}function Ro(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function zi(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function Do(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function yn(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let s=a.fragments;const{fragmentHint:i}=a;i&&(s=s.concat(i));let r;return pn.search(s,n=>n.cc<e?1:n.cc>e?-1:(r=n,n.end<=t?1:n.start>t?-1:0)),r||null}return null}function fs(a){switch(a.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Xi(a,e){const t=fs(e);return a.default["".concat(t?"timeout":"error","Retry")]}function hi(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function Qi(a){return se(se({},a),{errorRetry:null,timeoutRetry:null})}function gs(a,e,t,s){if(!a)return!1;const i=s==null?void 0:s.code,r=e<a.maxNumRetry&&(_o(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function _o(a){return a===0&&navigator.onLine===!1||!!a&&(a<400||a>499)}var pe={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ke={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class ko extends Ke{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===V.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case _.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=_t();return}case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=pe.SendAlternateToPenaltyBox;return}case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var n,o;const l=t.parent===V.MAIN?t.level:i.loadLevel;t.details===_.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(o=n.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const l=i.loadLevelObj;if(l&&(r.type===Z.AUDIO_TRACK&&l.hasAudioGroup(r.groupId)||r.type===Z.SUBTITLE_TRACK&&l.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=pe.SendAlternateToPenaltyBox,t.errorAction.flags=ke.MoveAllAlternatesMatchingHost;return}}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=i.loadLevelObj,h=l==null?void 0:l.attrs["HDCP-LEVEL"];h?t.errorAction={action:pe.SendAlternateToPenaltyBox,flags:ke.MoveAllAlternatesMatchingHDCP,hdcpLevel:h}:this.keySystemError(t)}return;case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:if(!t.errorAction){var d;t.errorAction=this.getLevelSwitchAction(t,(d=t.level)!=null?d:i.loadLevel)}return;case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:t.errorAction=_t();return}t.type===H.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Xi(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(gs(i,r,fs(e),e.response))return{action:pe.RetryRequest,flags:ke.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=Xi(e.details.startsWith("key")?n:r,e),d=t.levels.reduce((h,c)=>h+c.fragmentError,0);if(i&&(e.details!==_.FRAG_GAP&&i.fragmentError++,gs(o,d,fs(e),e.response)))return{action:pe.RetryRequest,flags:ke.None,retryConfig:o,retryCount:d};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=d),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===_.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:c,loadLevel:u,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=e.frag)==null?void 0:r.type,v=(p===V.AUDIO&&l===_.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:I})=>i.audioCodec!==I),T=e.sourceBufferName==="video"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR)&&c.some(({codecSet:I,audioCodec:A})=>i.codecSet!==I&&i.audioCodec===A),{type:S,groupId:x}=(n=e.context)!=null?n:{};for(let I=c.length;I--;){const A=(I+u)%c.length;if(A!==u&&A>=g&&A<=f&&c[A].loadError===0){var o,d;const b=c[A];if(l===_.FRAG_GAP&&p===V.MAIN&&e.frag){const k=c[A].details;if(k){const L=st(e.frag,k.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(S===Z.AUDIO_TRACK&&b.hasAudioGroup(x)||S===Z.SUBTITLE_TRACK&&b.hasSubtitleGroup(x))continue;if(p===V.AUDIO&&(o=i.audioGroups)!=null&&o.some(k=>b.hasAudioGroup(k))||p===V.SUBTITLE&&(d=i.subtitleGroups)!=null&&d.some(k=>b.hasSubtitleGroup(k))||v&&i.audioCodec===b.audioCodec||!v&&i.audioCodec!==b.audioCodec||T&&i.codecSet===b.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:pe.SendAlternateToPenaltyBox,flags:ke.None,nextAutoLevel:h}}return{action:pe.SendAlternateToPenaltyBox,flags:ke.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case pe.DoNothing:break;case pe.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==_.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'.concat(t.sourceBufferName,'" sourceBuffer append error. Attempting to recover from media error.')),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case ke.None:this.switchLevel(e,n);break;case ke.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=qs[qs.indexOf(r)-1],s.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'));break}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn("switching to level ".concat(t," after ").concat(e.details)),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===_.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=hn(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r]["".concat(e.sourceBufferName,"Codec")]===s&&this.hls.removeLevel(r)}}}function _t(a){const e={action:pe.DoNothing,flags:ke.None};return a&&(e.resolved=!0),e}var he={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Co{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;const n=r.end;if(r.start<=e&&n!==null&&e<=n)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const o=i[r[n]];if((o==null?void 0:o.body.type)===t&&(!s||o.buffered)){const d=o.body;if(d.start<=e&&e<=d.end)return d}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const d=this.fragments[o];if(!d||n>=d.body.sn)return;if(!d.buffered&&(!d.loaded||r)){d.body.type===s&&this.removeFragment(d.body);return}const l=d.range[e];if(l){if(l.time.length===0){this.removeFragment(d.body);return}l.time.some(h=>{const c=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return c&&this.removeFragment(d.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=at(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(o=>{const d=s.elementaryStreams[o];if(!d)return;const l=t[o],h=n||d.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(r.buffered=!0,(r.body.endList=s.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),Bt(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Zi(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=at(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,d=e.minEndPTS||o,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const c=i.start(h)-this.bufferPadding,u=i.end(h)+this.bufferPadding;if(l>=c&&d<=u){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(n<u&&o>c){const g=Math.max(n,i.start(h)),f=Math.min(o,i.end(h));f>g&&(r.partial=!0,r.time.push({startPTS:g,endPTS:f}))}else if(o<=c)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:d}=this;return Object.keys(d).forEach(l=>{const h=d[l];h&&Bt(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Bt(t))}getState(e){const t=at(e),s=this.fragments[t];return s?s.buffered?Bt(s)?he.PARTIAL:he.OK:he.APPENDING:he.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=at(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const d=r[n];this.detectEvictedFragments(n,d,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=at(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const d=o.body;d.type!==s||i&&!d.gap||d.start<t&&d.end>e&&(o.buffered||r)&&this.removeFragment(d)})}removeFragment(e){const t=at(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Zi(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const s=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;s&&s.forEach(i=>i.clearElementaryStreamInfo())}}function Bt(a){var e,t,s;return a.buffered&&(a.body.gap||((e=a.range.video)==null?void 0:e.partial)||((t=a.range.audio)==null?void 0:t.partial)||((s=a.range.audiovideo)==null?void 0:s.partial))}function at(a){return"".concat(a.type,"_").concat(a.level,"_").concat(a.sn)}function Zi(a,e){return a.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var ze={cbc:0,ctr:1};class Po{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case ze.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ze.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode ".concat(this.aesMode))}}}function wo(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class Oo{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],d=this.invSubMix,l=d[0],h=d[1],c=d[2],u=d[3],g=new Uint32Array(256);let f=0,p=0,y=0;for(y=0;y<256;y++)y<128?g[y]=y<<1:g[y]=y<<1^283;for(y=0;y<256;y++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;const E=g[f],T=g[E],S=g[T];let x=g[v]*257^v*16843008;i[f]=x<<24|x>>>8,r[f]=x<<16|x>>>16,n[f]=x<<8|x>>>24,o[f]=x,x=S*16843009^T*65537^E*257^f*16843008,l[v]=x<<24|x>>>8,h[v]=x<<16|x>>>16,c[v]=x<<8|x>>>24,u[v]=x,f?(f=E^g[g[g[S^E]]],p^=g[g[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,d;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),c=this.sBox,u=this.rcon,g=this.invSubMix,f=g[0],p=g[1],y=g[2],v=g[3];let E,T;for(o=0;o<n;o++){if(o<r){E=l[o]=t[o];continue}T=E,o%r===0?(T=T<<8|T>>>24,T=c[T>>>24]<<24|c[T>>>16&255]<<16|c[T>>>8&255]<<8|c[T&255],T^=u[o/r|0]<<24):r>6&&o%r===4&&(T=c[T>>>24]<<24|c[T>>>16&255]<<16|c[T>>>8&255]<<8|c[T&255]),l[o]=E=(l[o-r]^T)>>>0}for(d=0;d<n;d++)o=n-d,d&3?T=l[o]:T=l[o-4],d<4||o<=4?h[d]=T:h[d]=f[c[T>>>24]]^p[c[T>>>16&255]]^y[c[T>>>8&255]]^v[c[T&255]],h[d]=h[d]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,d=o[0],l=o[1],h=o[2],c=o[3],u=this.uint8ArrayToUint32Array_(s);let g=u[0],f=u[1],p=u[2],y=u[3];const v=new Int32Array(e),E=new Int32Array(v.length);let T,S,x,I,A,b,k,L,F,U,B,N,$,D;const C=this.networkToHostOrderSwap;for(;t<v.length;){for(F=C(v[t]),U=C(v[t+1]),B=C(v[t+2]),N=C(v[t+3]),A=F^r[0],b=N^r[1],k=B^r[2],L=U^r[3],$=4,D=1;D<i;D++)T=d[A>>>24]^l[b>>16&255]^h[k>>8&255]^c[L&255]^r[$],S=d[b>>>24]^l[k>>16&255]^h[L>>8&255]^c[A&255]^r[$+1],x=d[k>>>24]^l[L>>16&255]^h[A>>8&255]^c[b&255]^r[$+2],I=d[L>>>24]^l[A>>16&255]^h[b>>8&255]^c[k&255]^r[$+3],A=T,b=S,k=x,L=I,$=$+4;T=n[A>>>24]<<24^n[b>>16&255]<<16^n[k>>8&255]<<8^n[L&255]^r[$],S=n[b>>>24]<<24^n[k>>16&255]<<16^n[L>>8&255]<<8^n[A&255]^r[$+1],x=n[k>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[b&255]^r[$+2],I=n[L>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[k&255]^r[$+3],E[t]=C(T^g),E[t+1]=C(I^f),E[t+2]=C(x^p),E[t+3]=C(S^y),g=F,f=U,p=B,y=N,t=t+4}return E.buffer}}class Fo{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Mo(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Mo(a){switch(a){case ze.cbc:return"AES-CBC";case ze.ctr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode ".concat(a))}}const No=16;class ui{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(s){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?wo(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const d=this.flush();d?r(d.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:o}=this;if(i!==ze.cbc||t.byteLength!==16)return te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Re(o,e),this.remainderData=null);const d=this.getValidChunk(e);if(!d.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Oo),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(d.buffer,0,s),this.currentIV=d.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Fo(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Po(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(te.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(r.name,": ").concat(r.message)),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%No;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(te.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}const Ji=Math.pow(2,17);class $o{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Ge({type:H.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,d)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){d(tr(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),h=er(e);e.loader=l;const c=Qi(i.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ji};e.stats=l.stats;const g={onSuccess:(f,p,y,v)=>{this.resetLoader(e,l);let E=f.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:v})},onError:(f,p,y,v)=>{this.resetLoader(e,l),d(new Ge({type:H.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:se({url:s,data:void 0},f),error:new Error("HTTP Error ".concat(f.code," ").concat(f.text)),networkDetails:y,stats:v}))},onAbort:(f,p,y)=>{this.resetLoader(e,l),d(new Ge({type:H.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,p,y)=>{this.resetLoader(e,l),d(new Ge({type:H.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(u.timeout,"ms")),networkDetails:y,stats:f}))}};t&&(g.onProgress=(f,p,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),l.load(h,u,g)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,d)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){d(tr(e,t));return}const l=this.loader=r?new r(i):new n(i),h=er(e,t);e.loader=l;const c=Qi(i.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ji};t.stats=l.stats,l.load(h,u,{onSuccess:(g,f,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:g.data,networkDetails:y};s(v),o(v)},onError:(g,f,p,y)=>{this.resetLoader(e,l),d(new Ge({type:H.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:se({url:h.url,data:void 0},g),error:new Error("HTTP Error ".concat(g.code," ").concat(g.text)),networkDetails:p,stats:y}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),d(new Ge({type:H.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,l),d(new Ge({type:H.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after ".concat(u.timeout,"ms")),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const d=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),d),c=(d-l)*Math.round(s.loaded/l);s.total=s.loaded+c}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function er(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(G(i)&&G(r)){var n;let o=i,d=r;if(a.sn==="initSegment"&&Bo((n=a.decryptdata)==null?void 0:n.method)){const l=r-i;l%16&&(d=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=d}return s}function tr(a,e){const t=new Error("GAP ".concat(a.gap?"tag":"attribute"," found")),s={type:H.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new Ge(s)}function Bo(a){return a==="AES-128"||a==="AES-256"}class Ge extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class vn extends Ke{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class fi{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Ut(),this.buffering={audio:Ut(),video:Ut(),audiovideo:Ut()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function Ut(){return{start:0,executeStart:0,executeEnd:0,end:0}}const sr={length:0,start:()=>0,end:()=>0};class z{static isBuffered(e,t){if(e){const s=z.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=z.getBuffered(e);return z.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=z.bufferedRanges(e);if(i.length)return z.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,c)=>h.start-c.start||c.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const c=r.length;if(c){const u=r[c-1].end;e[h].start-u<s?e[h].end>u&&(r[c-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n=0,o,d=t,l=t;for(let h=0;h<r.length;h++){const c=r[h].start,u=r[h].end;if(i===-1&&t>=c&&t<=u&&(i=h),t+s>=c&&t<u)d=c,l=u,n=l-t;else if(t+s<c){o=c;break}}return{len:n,start:d||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||sr}catch(t){return te.log("failed to get media.buffered",t),sr}}}const En=/\{\$([a-zA-Z0-9-_]+)\}/g;function ir(a){return En.test(a)}function zs(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(En,s=>{const i=s.substring(2,s.length-1),r=t==null?void 0:t[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(i,'"'))),s):r})}return e}function rr(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error('"'.concat(i,'" does not match any query parameter in URI: "').concat(t,'"'))}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(n.message)))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(i,'"'))):s[i]=r||""}function Uo(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(s,'"')))}const Go=/^(\d+)x(\d+)$/,nr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class oe{constructor(e,t){typeof e=="string"&&(e=oe.parseAttrList(e,t)),re(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Go.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={},r='"';for(nr.lastIndex=0;(s=nr.exec(e))!==null;){const n=s[1].trim();let o=s[2];const d=o.indexOf(r)===0&&o.lastIndexOf(r)===o.length-1;let l=!1;if(d)o=o.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(d||l))o=zs(t,o);else if(!l&&!d)switch(n){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":te.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}i[n]=o}return i}}const Vo="com.apple.hls.interstitial";function Ko(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Ho(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class Tn{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(i=t==null?void 0:t.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){te.warn('DATERANGE tag attribute: "'.concat(n,'" does not match for tags with ID: "').concat(e.ID,'"')),this._badValueForSameId=n;break}e=re(new oe({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);G(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(te.warn('Expected tagAnchor Fragment with PDT set for DateRange "'.concat(this.id,'": ').concat(e)),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(G(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Vo}get isValid(){return!!this.id&&!this._badValueForSameId&&G(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const Wo=10;class Yo{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}get hasProgramDateTime(){return this.fragments.length?G(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Wo}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ht(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function gi(a){switch(a){case"AES-128":case"AES-256":return ze.cbc;case"AES-256-CTR":return ze.ctr;default:throw new Error("invalid full segment method ".concat(a))}}function mi(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function Xs(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function jo(a){const e=Xs(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function qo(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function zo(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=mi(n)):t=jo(n)}}return t}const ms=typeof self<"u"?self:void 0;var ie={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function es(a){switch(a){case ve.FAIRPLAY:return ie.FAIRPLAY;case ve.PLAYREADY:return ie.PLAYREADY;case ve.WIDEVINE:return ie.WIDEVINE;case ve.CLEARKEY:return ie.CLEARKEY}}var Gt={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Rs(a){if(a===Gt.WIDEVINE)return ie.WIDEVINE;if(a===Gt.PLAYREADY)return ie.PLAYREADY;if(a===Gt.CENC||a===Gt.CLEARKEY)return ie.CLEARKEY}function Vt(a){switch(a){case ie.FAIRPLAY:return ve.FAIRPLAY;case ie.PLAYREADY:return ve.PLAYREADY;case ie.WIDEVINE:return ve.WIDEVINE;case ie.CLEARKEY:return ve.CLEARKEY}}function xt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[ie.FAIRPLAY,ie.WIDEVINE,ie.PLAYREADY,ie.CLEARKEY].filter(i=>!!e[i]):[];return!s[ie.WIDEVINE]&&t&&s.push(ie.WIDEVINE),s}const Sn=function(a){return ms!=null&&(a=ms.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Xo(a,e,t,s){let i;switch(a){case ie.FAIRPLAY:i=["cenc","sinf"];break;case ie.WIDEVINE:case ie.PLAYREADY:i=["cenc"];break;case ie.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(a))}return Qo(i,e,t,s)}function Qo(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:"audio/mp4; codecs=".concat(r),robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:"video/mp4; codecs=".concat(r),robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Zo(a){var e;return a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function xn(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const o=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(o){const d=mi(o).subarray(0,16);return qo(d),d}}return null}let Kt={};class kt{static clearKeyUriToKeyIdMap(){Kt={}}constructor(e,t,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!ht(e)}isSupported(){if(this.method){if(ht(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ve.FAIRPLAY:case ve.WIDEVINE:case ve.PLAYREADY:case ve.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(ht(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(te.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),e=0);const s=Jo(e);return new kt(this.method,this.uri,"identity",this.keyFormatVersions,s)}const t=zo(this.uri);if(t)switch(this.keyFormat){case ve.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case ve.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ro(s,null,t),this.keyId=xn(t);break}default:{let s=t.subarray(0,16);if(s.length!==16){const i=new Uint8Array(16);i.set(s,16-s.length),s=i}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s=Kt[this.uri];if(!s){const i=Object.keys(Kt).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,i),Kt[this.uri]=s}this.keyId=s}return this}}function Jo(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const ar=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,or=/#EXT-X-MEDIA:(.*)/g,el=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ds=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),tl=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ne{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return li.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return el.test(e)}static parseMasterPlaylist(e,t){const s=ir(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];ar.lastIndex=0;let n;for(;(n=ar.exec(e))!=null;)if(n[1]){var o;const l=new oe(n[1],i),h=zs(i,n[2]),c={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:Ne.resolve(h,t)},u=l.decimalResolution("RESOLUTION");u&&(c.width=u.width,c.height=u.height),cr(l.CODECS,c);const g=l["SUPPLEMENTAL-CODECS"];g&&(c.supplemental={},cr(g,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||r.push(c),i.levels.push(c)}else if(n[3]){const l=n[3],h=n[4];switch(l){case"SESSION-DATA":{const c=new oe(h,i),u=c["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=c);break}case"SESSION-KEY":{const c=lr(h,t,i);c.encrypted&&c.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(c)):te.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(h,'"'));break}case"DEFINE":{{const c=new oe(h,i);rr(i,c,t)}break}case"CONTENT-STEERING":{const c=new oe(h,i);i.contentSteering={uri:Ne.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=dr(h);break}}}const d=r.length>0&&r.length<i.levels.length;return i.levels=d?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:n.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let d=0;for(or.lastIndex=0;(i=or.exec(e))!==null;){const l=new oe(i[1],s),h=l.TYPE;if(h){const c=o[h],u=r[h]||[];r[h]=u;const g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,v=l["INSTREAM-ID"],E={attrs:l,bitrate:0,id:d++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?Ne.resolve(l.URI,t):""};if(f&&(E.assocLang=f),p&&(E.channels=p),y&&(E.characteristics=y),v&&(E.instreamId=v),c!=null&&c.length){const T=Ne.findGroup(c,E.groupId)||c[0];hr(E,T,"audioCodec"),hr(E,T,"textCodec")}u.push(E)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var o;const d={url:t},l=new Yo(t),h=l.fragments,c=[];let u=null,g=0,f=0,p=0,y=0,v=0,E=null,T=new As(i,d),S,x,I,A=-1,b=!1,k=null,L;if(Ds.lastIndex=0,l.m3u8=e,l.hasVariableRefs=ir(e),((o=Ds.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=Ds.exec(e))!==null;){b&&(b=!1,T=new As(i,d),T.playlistOffset=p,T.start=p,T.sn=g,T.cc=y,v&&(T.bitrate=v),T.level=s,u&&(T.initSegment=u,u.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),k&&(T.setByteRange(k),k=null)));const N=S[1];if(N){T.duration=parseFloat(N);const $=(" "+S[2]).slice(1);T.title=$||null,T.tagList.push($?["INF",N,$]:["INF",N])}else if(S[3]){if(G(T.duration)){T.playlistOffset=p,T.start=p,I&&fr(T,I,l),T.sn=g,T.level=s,T.cc=y,h.push(T);const $=(" "+S[3]).slice(1);T.relurl=zs(l,$),Qs(T,E,c),E=T,p+=T.duration,g++,f=0,b=!0}}else{if(S=S[0].match(tl),!S){te.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<S.length&&S[x]===void 0;x++);const $=(" "+S[x]).slice(1),D=(" "+S[x+1]).slice(1),C=S[x+2]?(" "+S[x+2]).slice(1):null;switch($){case"BYTERANGE":E?T.setByteRange(D,E):T.setByteRange(D);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=D,T.tagList.push(["PROGRAM-DATE-TIME",D]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&Be(l,$,S),l.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Be(l,$,S):h.length>0&&gr(l,$,S),g=l.startSN=parseInt(D);break;case"SKIP":{l.skippedSegments&&Be(l,$,S);const O=new oe(D,l),P=O.decimalInteger("SKIPPED-SEGMENTS");if(G(P)){l.skippedSegments+=P;for(let W=P;W--;)h.push(null);g+=P}const M=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");M&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(M.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Be(l,$,S),l.targetduration=Math.max(parseInt(D),1);break;case"VERSION":l.version!==null&&Be(l,$,S),l.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Be(l,$,S),l.live=!1;break;case"#":(D||C)&&T.tagList.push(C?[D,C]:[D]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([$]);break;case"BITRATE":T.tagList.push([$,D]),v=parseInt(D)*1e3,G(v)?T.bitrate=v:v=0;break;case"DATERANGE":{const O=new oe(D,l),P=new Tn(O,l.dateRanges[O.ID],l.dateRangeTagCount);l.dateRangeTagCount++,P.isValid||l.skippedSegments?l.dateRanges[P.id]=P:te.warn('Ignoring invalid DATERANGE tag: "'.concat(D,'"')),T.tagList.push(["EXT-X-DATERANGE",D]);break}case"DEFINE":{{const O=new oe(D,l);"IMPORT"in O?Uo(l,O,n):rr(l,O,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Be(l,$,S):h.length>0&&gr(l,$,S),l.startCC=y=parseInt(D);break;case"KEY":{const O=lr(D,t,l);if(O.isSupported()){if(O.method==="NONE"){I=void 0;break}I||(I={}),I[O.keyFormat]&&(I=re({},I)),I[O.keyFormat]=O}else te.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'.concat(D,'"'));break}case"START":l.startTimeOffset=dr(D);break;case"MAP":{const O=new oe(D,l);if(T.duration){const P=new As(i,d);ur(P,O,s,I),u=P,T.initSegment=u,u.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime)}else{const P=T.byteRangeEndOffset;if(P){const M=T.byteRangeStartOffset;k="".concat(P-M,"@").concat(M)}else k=null;ur(T,O,s,I),u=T,b=!0}u.cc=y;break}case"SERVER-CONTROL":{L&&Be(l,$,S),L=new oe(D),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Be(l,$,S);const O=new oe(D);l.partTarget=O.decimalFloatingPoint("PART-TARGET");break}case"PART":{let O=l.partList;O||(O=l.partList=[]);const P=f>0?O[O.length-1]:void 0,M=f++,W=new oe(D,l),K=new Ha(W,T,d,M,P);O.push(K),T.duration+=K.duration;break}case"PRELOAD-HINT":{const O=new oe(D,l);l.preloadHint=O;break}case"RENDITION-REPORT":{const O=new oe(D,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(O);break}default:te.warn("line parsed but not handled: ".concat(S));break}}}E&&!E.relurl?(h.pop(),p-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(Qs(T,E,c),T.cc=y,l.fragmentHint=T,I&&fr(T,I,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const F=h.length,U=h[0],B=h[F-1];if(p+=l.skippedSegments*l.targetduration,p>0&&F&&B){l.averagetargetduration=p/F;const N=B.sn;l.endSN=N!=="initSegment"?N:0,l.live||(B.endList=!0),U&&l.startCC===void 0&&(l.startCC=U.cc),A>0&&(il(h,A),U&&c.unshift(U))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,c.length&&l.dateRangeTagCount&&U&&An(c,l),l.endCC=y,l}}function An(a,e){const t=a.length;if(!t)return;const s=a[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let n=r.length;n--;){const o=e.dateRanges[r[n]],d=o.startDate.getTime();o.tagAnchor=s.ref;for(let l=t;l--;){const h=sl(e,d,a,l,i);if(h!==-1){o.tagAnchor=e.fragments[h].ref;break}}}}function sl(a,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var n;const d=(((n=t[s+1])==null?void 0:n.start)||i)-r.start;if(e<=o+d*1e3){const l=t[s].sn-a.startSN,h=a.fragments;if(h.length>t.length){const u=(t[s+1]||h[h.length-1]).sn-a.startSN;for(let g=u;g>l;g--){const f=h[g].programDateTime;if(e>=f&&e<f+h[g].duration*1e3)return g}}return l}}}return-1}function lr(a,e,t){var s,i;const r=new oe(a,t),n=(s=r.METHOD)!=null?s:"",o=r.URI,d=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!d&&te.error("Invalid IV: ".concat(r.IV));const c=o?Ne.resolve(o,e):"",u=(l||"1").split("/").map(Number).filter(Number.isFinite);return new kt(n,c,h,u,d)}function dr(a){const t=new oe(a).decimalFloatingPoint("TIME-OFFSET");return G(t)?t:null}function cr(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>dn(r,s));i.length&&(e["".concat(s,"Codec")]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function hr(a,e,t){const s=e[t];s&&(a[t]=s)}function il(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Qs(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function ur(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function fr(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}function Be(a,e,t){a.playlistParsingError=new Error("#EXT-X-".concat(e," must not appear more than once (").concat(t[0],")"))}function gr(a,e,t){a.playlistParsingError=new Error("#EXT-X-".concat(e," must appear before the first Media Segment (").concat(t[0],")"))}function _s(a,e){const t=e.startPTS;if(G(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function Ln(a,e,t,s,i,r){s-t<=0&&(te.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let o=t,d=s;const l=e.startPTS,h=e.endPTS;if(G(l)){const y=Math.abs(l-t);G(e.deltaPTS)?e.deltaPTS=Math.max(y,e.deltaPTS):e.deltaPTS=y,o=Math.max(t,l),t=Math.min(t,l),i=Math.min(i,e.startDTS),d=Math.min(s,h),s=Math.max(s,h),r=Math.max(r,e.endDTS)}const c=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=o,e.startDTS=i,e.endPTS=s,e.minEndPTS=d,e.endDTS=r;const u=e.sn;if(!a||u<a.startSN||u>a.endSN)return 0;let g;const f=u-a.startSN,p=a.fragments;for(p[f]=e,g=f;g>0;g--)_s(p[g],p[g-1]);for(g=f;g<p.length-1;g++)_s(p[g],p[g+1]);return a.fragmentHint&&_s(p[p.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,c}function rl(a,e){if(a===e)return;let t=null;const s=a.fragments;for(let l=s.length-1;l>=0;l--){const h=s[l].initSegment;if(h){t=h;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let i;ol(a,e,(l,h,c,u)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==l.cc){const g=l.cc-h.cc;for(let f=c;f<u.length;f++)u[f].cc+=g;e.endCC=u[u.length-1].cc}G(l.startPTS)&&G(l.endPTS)&&(h.setStart(h.startPTS=l.startPTS),h.startDTS=l.startDTS,h.maxStartPTS=l.maxStartPTS,h.endPTS=l.endPTS,h.endDTS=l.endDTS,h.minEndPTS=l.minEndPTS,h.setDuration(l.endPTS-l.startPTS),h.duration&&(i=h),e.PTSKnown=e.alignedSliding=!0),l.hasStreams&&(h.elementaryStreams=l.elementaryStreams),h.loader=l.loader,l.hasStats&&(h.stats=l.stats),l.initSegment&&(h.initSegment=l.initSegment,t=l.initSegment)});const r=e.fragments,n=e.fragmentHint?r.concat(e.fragmentHint):r;if(t&&n.forEach(l=>{var h;l&&(!l.initSegment||l.initSegment.relurl===((h=t)==null?void 0:h.relurl))&&(l.initSegment=t)}),e.skippedSegments){if(e.deltaUpdateFailed=r.some(l=>!l),e.deltaUpdateFailed){te.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)r.shift();e.startSN=r[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=nl(a.dateRanges,e));const l=a.fragments.filter(h=>h.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<n.length;h++)n[h].programDateTime===null&&Qs(n[h],n[h-1],l);An(l,e)}e.endCC=r[r.length-1].cc}if(!e.startCC){var o;const l=Rn(a,e.startSN-1);e.startCC=(o=l==null?void 0:l.cc)!=null?o:r[0].cc}al(a.partList,e.partList,(l,h)=>{h.elementaryStreams=l.elementaryStreams,h.stats=l.stats}),i?Ln(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):bn(a,e),r.length&&(e.totalduration=e.edge-r[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const l=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=l),e.driftEndTime=d,e.driftEnd=l}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function nl(a,e){const{dateRanges:t,recentlyRemovedDateranges:s}=e,i=re({},a);s&&s.forEach(o=>{delete i[o]});const n=Object.keys(i).length;return n&&Object.keys(t).forEach(o=>{const d=i[o],l=new Tn(t[o].attr,d);l.isValid?(i[o]=l,d||(l.tagOrder+=n)):te.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(ae(t[o].attr),'"'))}),i}function al(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function ol(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=i;l<=r;l++){const h=d[n+l];let c=o[l];if(s&&!c&&h&&(c=e.fragments[l]=h),h&&c){if(t(h,c,l,o),h.url&&h.url!==c.url){e.playlistParsingError=mr("media sequence mismatch ".concat(c.sn,":"),a,e,h,c);return}else if(h.cc!==c.cc){e.playlistParsingError=mr("discontinuity sequence mismatch (".concat(h.cc,"!=").concat(c.cc,")"),a,e,h,c);return}}}}function mr(a,e,t,s,i){return new Error("".concat(a," ").concat(i.url,"\nPlaylist starting @").concat(e.startSN,"\n").concat(e.m3u8,"\n\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8))}function bn(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;Zs(e,n)}function Zs(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function In(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments,i=4;if(s.length&&t*i>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Rn(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function pr(a,e,t){return a?Dn(a.partList,e,t):null}function Dn(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function _n(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function Lt(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function ll(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function yr(a,e){if(a){const t=a.start+e;a.start=a.startPTS=t,a.endPTS=t+a.duration}}function kn(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)yr(t[s],a);e.fragmentHint&&yr(e.fragmentHint,a),e.alignedSliding=!0}function dl(a,e){a&&(Cn(e,a),!e.alignedSliding&&a&&ps(e,a),!e.alignedSliding&&a&&!e.skippedSegments&&bn(a,e,!1))}function Cn(a,e){if(!ll(e,a))return;const t=Math.min(e.endCC,a.endCC),s=Lt(e.fragments,t),i=Lt(a.fragments,t);if(!s||!i)return;te.log("Aligning playlist at start of dicontinuity sequence ".concat(t));const r=s.start-i.start;kn(r,a)}function ps(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=Lt(s,n),r=Lt(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Lt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,d=r.programDateTime;if(!o||!d)return;const l=(d-o)/1e3-(r.start-i.start);kn(l,a)}const cl={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+="[".concat(a.start(s).toFixed(3),"-").concat(a.end(s).toFixed(3),"]");return e}},w={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class pi extends vn{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=w.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:d,mediaBuffer:l,state:h}=this,c=d?d.currentTime:0,u=z.bufferInfo(l||d,c,n.maxBufferHole);if(this.log("media seeking to ".concat(G(c)?c.toFixed(3):c,", state: ").concat(h)),this.state===w.ENDED)this.resetLoadingState();else if(o){const g=n.maxFragLookUpTolerance,f=o.start-g,p=o.start+o.duration+g;if(!u.len||p<u.start||f>u.end){const y=c>p;(c<f||y)&&(y&&o.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(d){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(c>g&&(this.lastCurrentTime=c),!this.loadingParts){const f=Math.max(u.end,c),p=this.shouldLoadParts(this.getLevelDetails(),f);p&&(this.log("LL-Part loading ON after seeking to ".concat(c.toFixed(2)," with buffer @").concat(f.toFixed(2))),this.loadingParts=p)}}!this.hls.hasEnoughToStart&&!u.len&&(this.log("setting startPosition to ".concat(c," because of seek before start")),this.nextLoadPosition=this.startPosition=c),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new $o(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ui(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===w.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=w.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=z.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const d=t.partList;if(d!=null&&d.length){const h=d[d.length-1];return z.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),s.addEventListener("seeking",this.onMediaSeeking),s.addEventListener("ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===w.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=w.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn("".concat(n.type," sn: ").concat(n.sn).concat(r.part?" part: "+r.part.index:""," of ").concat(this.fragInfo(n,!1,r.part),") was dropped during download.")),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===w.FRAG_LOADING||!this.fragCurrent&&n===w.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=w.IDLE);return}"payload"in r&&(this.log("Loaded ".concat(o.type," sn: ").concat(o.sn," of ").concat(this.playlistLabel()," ").concat(o.level)),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===w.STOPPED||this.state===w.ERROR||(this.warn("Frag error: ".concat((r==null?void 0:r.message)||r)),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===he.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),d=this.backtrackFragment;((d?e.sn-d.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===he.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s==null?void 0:s.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&ht(o.method)){const d=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,gi(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:d,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===w.STOPPED||this.state===w.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==w.STOPPED&&(this.state=w.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(s?cl.toString(z.getBuffered(s)):"(detached)",")")),ge(e)){var i;if(e.type!==V.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=w.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log("Resetting level fragment error count of ".concat(r.fragmentError," on frag buffered")),r.fragmentError=0)}this.state=w.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(d=>!d),o=new fi(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t==null?void 0:t.details;if(!this.levels||!n)throw new Error("frag load aborted, missing level".concat(n?"":" detail","s"));let o=null;e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log("Loading key for ".concat(e.sn," of [").concat(n.startSN,"-").concat(n.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=w.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(m.KEY_LOADED,c),this.state===w.KEY_LOADING&&(this.state=w.IDLE),c}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):e.encrypted||(o=this.keyLoader.loadClear(e,n.encryptedFragments),o&&this.log("[eme] blocking frag load until media-keys acquired"));const d=this.fragPrevious;if(ge(e)&&(!d||e.sn!==d.sn)){const c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log("LL-Part loading ".concat(c?"ON":"OFF"," loading sn ").concat(d==null?void 0:d.sn,"->").concat(e.sn)),this.loadingParts=c)}if(s=Math.max(e.start,s||0),this.loadingParts&&ge(e)){const c=n.partList;if(c&&i){s>e.end&&n.fragmentHint&&(e=n.fragmentHint);const u=this.getNextPart(c,e,s);if(u>-1){const g=c[u];e=this.fragCurrent=g.fragment,this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(g.index," (").concat(u,"/").concat(c.length-1,") of ").concat(this.fragInfo(e,!1,g),") cc: ").concat(e.cc," [").concat(n.startSN,"-").concat(n.endSN,"], target: ").concat(parseFloat(s.toFixed(3)))),this.nextLoadPosition=g.start+g.duration,this.state=w.FRAG_LOADING;let f;return o?f=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(p=>this.handleFragLoadError(p)):f=this.doFragPartsLoad(e,g,t,i).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(c,s))return Promise.resolve(null)}}if(ge(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(s.toFixed(2))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1),") cc: ").concat(e.cc," ").concat(n?"["+n.startSN+"-"+n.endSN+"]":"",", target: ").concat(parseFloat(s.toFixed(3)))),G(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=w.FRAG_LOADING;const l=this.config.progressive;let h;return l&&o?h=o.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,i)).catch(c=>this.handleFragLoadError(c)):h=Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([c])=>(!l&&c&&i&&i(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const d=[],l=(o=s.details)==null?void 0:o.partList,h=c=>{this.fragmentLoader.loadPart(e,c,i).then(u=>{d[c.index]=u;const g=u.part;this.hls.trigger(m.FRAG_LOADED,u);const f=pr(s.details,e.sn,c.index+1)||Dn(l,e.sn,c.index+1);if(f)h(f);else return r({frag:e,part:g,partsLoaded:d})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==w.PARSING){!this.fragCurrent&&this.state!==w.STOPPED&&this.state!==w.ERROR&&(this.state=w.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log("LL-Part loading ".concat(l?"ON":"OFF"," after parsing segment ending @").concat(s.end.toFixed(2))),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var s;const r=e.partList[0],n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn("Levels object was unset while buffering fragment ".concat(r," of ").concat(this.playlistLabel()," ").concat(i,". The current chunk will not be buffered.")),null;const o=t[i],d=o.details,l=n>-1?pr(d,r,n):null,h=l?l.fragment:Rn(d,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){var n;if(!e||this.state!==w.PARSING)return;const{data1:o,data2:d}=e;let l=o;if(o&&d&&(l=Re(o,d)),!((n=l)!=null&&n.length))return;const h={type:e.type,frag:t,part:s,chunkMeta:i,parent:t.type,data:l};if(this.hls.trigger(m.BUFFER_APPENDING,h),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!z.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=z.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!G(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=z.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return z.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn("Reduce max buffer length to ".concat(r,"s")),!0):!1}getAppendedFrag(e,t=V.MAIN){var s;const i=(s=this.fragmentTracker)==null?void 0:s.getAppendedFrag(e,t);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let d=null;if(t.live){const c=r.initialLiveManifestSize;if(i<c)return this.warn("Not enough fragments to start playback (have: ".concat(i,", need: ").concat(c,")")),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),d=this.getInitialLiveFragment(t);const u=this.hls.startPosition,g=this.hls.liveSyncPosition,f=d?(u!==-1&&u>=n?u:g)||d.start:e;this.log("Setting startPosition to ".concat(f," to match start frag at live edge. mainStart: ").concat(u," liveSyncPosition: ").concat(g," frag.start: ").concat((l=d)==null?void 0:l.start)),this.startPosition=this.nextLoadPosition=f}}else e<=n&&(d=s[0]);if(!d){const c=this.loadingParts?t.partEnd:t.fragmentEnd;d=this.getFragmentAtPosition(e,c,t)}let h=this.filterReplacedPrimary(d,t);if(!h&&d){const c=d.sn-t.startSN;h=this.filterReplacedPrimary(s[c+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===he.OK||s===he.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const d=n.sn;return this.loopSn!==d&&(this.log('buffer full after gaps in "'.concat(i,'" playlist starting at sn: ').concat(d)),this.loopSn=d),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(vr(this.hls.config)){var e,t;if((e=this.hls.interstitialsManager)==null||(t=e.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(vr(this.hls.config)&&e.type!==V.SUBTITLE){const s=this.hls.interstitialsManager,i=s==null?void 0:s.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&(t==null?void 0:t.live)===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s==null?void 0:s.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,d=e.length;o<d;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||l.independent||n)&&l.fragment===t&&(i=o),r=h}return i}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(s.programDateTime)),i=Io(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(i.sn)))}i||(i=yn(e,s.cc,s.end),i&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(i.sn)))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:d}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,c=!!(this.loadingParts&&h!=null&&h.length&&d);c&&d&&!this.bitrateTest&&h[h.length-1].fragment.sn===d.sn&&(n=n.concat(d),o=d.sn);let u;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;u=st(r,n,e,p)}else u=n[n.length-1];if(u){const f=u.sn-s.startSN,p=this.fragmentTracker.getState(u);if((p===he.OK||p===he.PARTIAL&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!c||h[0].fragment.sn>u.sn||!s.live&&!c)&&r&&u.level===r.level){const v=n[f+1];u.sn<o&&this.fragmentTracker.getState(v)!==he.OK?u=v:u=null}}return u}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&G(r);if(n||!o&&!r){dl(s,e);const d=e.fragmentStart;return this.log("Live playlist sliding: ".concat(d.toFixed(2)," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(i)),d}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&G(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log("Setting startPosition to ".concat(s," for start time offset ").concat(n," found in ").concat(r?"multivariant":"media"," playlist")),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge ".concat(s)),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ge(e)&&e.stats.aborted&&(this.warn("Fragment ".concat(e.sn).concat(t?" part "+t.index:""," of ").concat(this.playlistLabel()," ").concat(e.level," was aborted")),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==w.FRAG_LOADING_WAITING_RETRY)&&(this.state=w.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const f=this.getCurrentContext(t.chunkMeta);f&&(t.frag=f.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var i;this.warn("Frag load error must match current frag to retry ".concat(s.url," > ").concat((i=this.fragCurrent)==null?void 0:i.url));return}const r=t.details===_.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=t.errorAction,{action:o,flags:d,retryCount:l=0,retryConfig:h}=n||{},c=!!n&&!!h,u=c&&o===pe.RetryRequest,g=c&&!n.resolved&&d===ke.MoveAllAlternatesMatchingHost;if(!u&&g&&ge(s)&&!s.endList)this.resetFragmentErrors(e),this.treatAsGap(s),n.resolved=!0;else if((u||g)&&l<h.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=hi(h,l);this.warn("Fragment ".concat(s.sn," of ").concat(e," ").concat(s.level," errored with ").concat(t.details,", retrying loading ").concat(l+1,"/").concat(h.maxNumRetry," in ").concat(f,"ms")),n.resolved=!0,this.retryDate=self.performance.now()+f,this.state=w.FRAG_LOADING_WAITING_RETRY}else if(h&&n)if(this.resetFragmentErrors(e),l<h.maxNumRetry)!r&&o!==pe.RemoveAlternatePermanently&&(n.resolved=!0);else{this.warn("".concat(t.details," reached or exceeded max retry (").concat(l,")"));return}else o===pe.SendAlternateToPenaltyBox?this.state=w.WAITING_LEVEL:this.state=w.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===w.PARSING||this.state===w.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(t==null?void 0:t.duration)||10);const n=!r;return n&&this.warn("Buffer full error while media.currentTime is not buffered, flush ".concat(s," buffer")),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===V.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==w.STOPPED&&(this.state=w.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=z.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===w.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==w.STOPPED&&(this.state=w.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn("The loading context changed while buffering fragment ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((d,l)=>{const h=e.elementaryStreams[l];if(h){const c=h.endPTS-h.startPTS;if(c<=0)return this.warn("Could not parse fragment ".concat(e.sn," ").concat(l," duration reliably (").concat(c,")")),d||!1;const u=i?0:Ln(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:u,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return d},!1)){var o;if(s.fragmentError===0&&this.treatAsGap(e,s),((o=this.transmuxer)==null?void 0:o.error)===null){const d=new Error("Found no media in fragment ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(e.level," resetting transmuxer to fallback to playlist timing"));if(this.warn(d.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(s.url,'"')}),!this.hls)return;this.resetTransmuxer()}}this.state=w.PARSED,this.log("Parsed ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t),")")),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===V.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(s?"part":"frag",":[").concat(((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3),"-").concat(((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3),"]").concat(s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):"")}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log("".concat(t,"->").concat(e)))}get state(){return this._state}}function vr(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class Pn{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=hl(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function hl(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var ks={exports:{}},Er;function ul(){return Er||(Er=1,function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(d,l,h){this.fn=d,this.context=l,this.once=h||!1}function r(d,l,h,c,u){if(typeof h!="function")throw new TypeError("The listener must be a function");var g=new i(h,c||d,u),f=t?t+l:l;return d._events[f]?d._events[f].fn?d._events[f]=[d._events[f],g]:d._events[f].push(g):(d._events[f]=g,d._eventsCount++),d}function n(d,l){--d._eventsCount===0?d._events=new s:delete d._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,c;if(this._eventsCount===0)return l;for(c in h=this._events)e.call(h,c)&&l.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,c=this._events[h];if(!c)return[];if(c.fn)return[c.fn];for(var u=0,g=c.length,f=new Array(g);u<g;u++)f[u]=c[u].fn;return f},o.prototype.listenerCount=function(l){var h=t?t+l:l,c=this._events[h];return c?c.fn?1:c.length:0},o.prototype.emit=function(l,h,c,u,g,f){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],v=arguments.length,E,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,c),!0;case 4:return y.fn.call(y.context,h,c,u),!0;case 5:return y.fn.call(y.context,h,c,u,g),!0;case 6:return y.fn.call(y.context,h,c,u,g,f),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];y.fn.apply(y.context,E)}else{var S=y.length,x;for(T=0;T<S;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),v){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,c);break;case 4:y[T].fn.call(y[T].context,h,c,u);break;default:if(!E)for(x=1,E=new Array(v-1);x<v;x++)E[x-1]=arguments[x];y[T].fn.apply(y[T].context,E)}}return!0},o.prototype.on=function(l,h,c){return r(this,l,h,c,!1)},o.prototype.once=function(l,h,c){return r(this,l,h,c,!0)},o.prototype.removeListener=function(l,h,c,u){var g=t?t+l:l;if(!this._events[g])return this;if(!h)return n(this,g),this;var f=this._events[g];if(f.fn)f.fn===h&&(!u||f.once)&&(!c||f.context===c)&&n(this,g);else{for(var p=0,y=[],v=f.length;p<v;p++)(f[p].fn!==h||u&&!f[p].once||c&&f[p].context!==c)&&y.push(f[p]);y.length?this._events[g]=y.length===1?y[0]:y:n(this,g)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o}(ks)),ks.exports}var fl=ul(),yi=Va(fl);const Ct="1.6.5",mt={};function gl(){return typeof __HLS_WORKER_BUNDLE__=="function"}function ml(){const a=mt[Ct];if(a)return a.clientCount++,a;const e=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return mt[Ct]=i,i}function pl(a){const e=mt[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return mt[a]=i,i}function yl(a){const e=mt[a||Ct];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete mt[a||Ct],i&&self.URL.revokeObjectURL(i),s.terminate()}}function wn(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function vi(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Ts(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function Pt(a,e){const t=e;let s=0;for(;vi(a,e);){s+=10;const i=Ts(a,e+6);s+=i,wn(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function vl(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const g=new Error("invalid ADTS sampling index:".concat(n));a.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(r>>6&3)+1,d=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let c=n;(o===5||o===29)&&(c-=3);const u=[o<<3|(c&14)>>1,(c&1)<<7|d<<3];return te.log("manifest codec:".concat(s,", parsed codec:").concat(l,", channels:").concat(d,", rate:").concat(h," (ADTS object type:").concat(o," sampling index:").concat(n,")")),{config:u,samplerate:h,channelCount:d,codec:l,parsedCodec:l,manifestCodec:s}}function On(a,e){return a[e]===255&&(a[e+1]&246)===240}function Fn(a,e){return a[e+1]&1?7:9}function Ei(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function El(a,e){return e+5<a.length}function ys(a,e){return e+1<a.length&&On(a,e)}function Tl(a,e){return El(a,e)&&On(a,e)&&Ei(a,e)<=a.length-e}function Sl(a,e){if(ys(a,e)){const t=Fn(a,e);if(e+t>=a.length)return!1;const s=Ei(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||ys(a,i)}return!1}function Mn(a,e,t,s,i){if(!a.samplerate){const r=vl(e,t,s,i);if(!r)return;re(a,r)}}function Nn(a){return 1024*9e4/a}function xl(a,e){const t=Fn(a,e);if(e+t<=a.length){const s=Ei(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function $n(a,e,t,s,i){const r=Nn(a.samplerate),n=s+i*r,o=xl(e,t);let d;if(o){const{frameLength:c,headerLength:u}=o,g=u+c,f=Math.max(0,t+g-e.length);f?(d=new Uint8Array(g-u),d.set(e.subarray(t+u,e.length),0)):d=e.subarray(t+u,t+g);const p={unit:d,pts:n};return f||a.samples.push(p),{sample:p,length:g,missing:f}}const l=e.length-t;return d=new Uint8Array(l),d.set(e.subarray(t,e.length),0),{sample:{unit:d,pts:n},length:l,missing:-1}}function Al(a,e){return vi(a,e)&&Ts(a,e+6)+10<=a.length-e}function Ll(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function Cs(a,e=0,t=1/0){return bl(a,e,t,Uint8Array)}function bl(a,e,t,s){const i=Il(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=Rl(a)?a.byteOffset:0,o=(n+a.byteLength)/r,d=(n+e)/r,l=Math.floor(Math.max(0,Math.min(d,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Il(a){return a instanceof ArrayBuffer?a:a.buffer}function Rl(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Dl(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=Se(Cs(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=Se(Cs(a.data,3+s,n));let d;return i==="-->"?d=Se(Cs(a.data,4+s+n)):d=Ll(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=d,e}function _l(a){if(a.size<2)return;const e=Se(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function kl(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=Se(a.data.subarray(t),!0);t+=s.length+1;const i=Se(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Se(a.data.subarray(1));return{key:a.type,info:"",data:e}}function Cl(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=Se(a.data.subarray(t),!0);t+=s.length+1;const i=Se(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Se(a.data);return{key:a.type,info:"",data:e}}function Pl(a){return a.type==="PRIV"?_l(a):a.type[0]==="W"?Cl(a):a.type==="APIC"?Dl(a):kl(a)}function wl(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Ts(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const Ht=10,Ol=10;function Bn(a){let e=0;const t=[];for(;vi(a,e);){const s=Ts(a,e+6);a[e+5]>>6&1&&(e+=Ht),e+=Ht;const i=e+s;for(;e+Ol<i;){const r=wl(a.subarray(e)),n=Pl(r);n&&t.push(n),e+=r.size+Ht}wn(a,e)&&(e+=Ht)}return t}function Un(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Fl(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function Ti(a){const e=Bn(a);for(let t=0;t<e.length;t++){const s=e[t];if(Un(s))return Fl(s)}}let Ee=function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a}({});function Fe(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Si{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Re(this.cachedData,e),this.cachedData=null);let s=Pt(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,d=s?Ti(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&G(d))&&(this.basePTS=Ml(d,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ee.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else Al(e,i)?(s=Pt(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ee.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=Re(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:Fe(),id3Track:o,textTrack:Fe()}}demuxSampleAes(e,t,s){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Fe(),id3Track:this._id3Track,textTrack:Fe()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Ml=(a,e,t)=>{if(G(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Wt=null;const Nl=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],$l=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Bl=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ul=[0,1,1,4];function Gn(a,e,t,s,i){if(t+24>e.length)return;const r=Vn(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,d={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(d),{sample:d,length:r.frameLength,missing:0}}}function Vn(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,d=t===3?3-s:s===3?3:4,l=Nl[d*14+i-1]*1e3,c=$l[(t===3?0:t===2?1:2)*3+r],u=o===3?1:2,g=Bl[t][s],f=Ul[s],p=g*8*f,y=Math.floor(g*l/c+n)*f;if(Wt===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Wt=T?parseInt(T[1]):0}return!!Wt&&Wt<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:c,channelCount:u,frameLength:y,samplesPerFrame:p}}}function xi(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function Kn(a,e){return e+1<a.length&&xi(a,e)}function Gl(a,e){return xi(a,e)&&4<=a.length-e}function Hn(a,e){if(e+1<a.length&&xi(a,e)){const s=Vn(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||Kn(a,r)}return!1}class Vl extends Si{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Pt(e,0);let i=(s==null?void 0:s.length)||0;if(Hn(e,i))return!1;for(let r=e.length;i<r;i++)if(Sl(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Tl(e,t)}appendFrame(e,t,s){Mn(e,this.observer,t,s,e.manifestCodec);const i=$n(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Wn=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),d=8-o;r[0]=4278190080>>>24+d<<d,i[0]=(n[0]&r[0])>>d,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Kl extends Si{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=Yn(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Pt(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Ti(t)!==void 0&&Wn(e,s)<16}}function Yn(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],d=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][d*3+r]*2;if(t+h>e.length)return-1;const c=e[t+6]>>5;let u=0;c===2?u+=2:(c&1&&c!==1&&(u+=2),c&4&&(u+=2));const g=(e[t+6]<<8|e[t+7])>>12-u&1,p=[2,1,2,3,3,4,4,5][c]+g,y=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([r<<6|y<<1|v>>2,(v&3)<<6|c<<3|g<<2|d>>4,d<<4&224]),T=1536/o*9e4,S=s+i*T,x=e.subarray(t,t+h);return a.config=E,a.channelCount=p,a.samplerate=o,a.samples.push({unit:x,pts:S}),h}class Hl extends Si{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Pt(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&Ti(t)!==void 0&&Wn(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Hn(e,s))return te.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Gl(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Gn(e,t,s,this.basePTS,this.frameIndex)}}const Wl=/\/emsg[-/]ID3/i;class Yl{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Fe("video",1),n=this.audioTrack=Fe("audio",1),o=this.txtTrack=Fe("text",1);if(this.id3Track=Fe("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const d=nn(e);if(d.video){const{id:l,timescale:h,codec:c,supplemental:u}=d.video;r.id=l,r.timescale=o.timescale=h,r.codec=c,r.supplemental=u}if(d.audio){const{id:l,timescale:h,codec:c}=d.audio;n.id=l,n.timescale=h,n.codec=c}o.id=tn.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return ja(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Re(this.remainderData,e));const o=eo(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Ui(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Ui(e,t),{videoTrack:t,audioTrack:Fe(),id3Track:i,textTrack:Fe()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Q(e.samples,["emsg"]);i&&i.forEach(r=>{const n=so(r);if(Wl.test(n.schemeIdUri)){const o=Tr(n,t);let d=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;d<=.001&&(d=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Ee.emsg,duration:d})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Tr(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:Ee.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function Tr(a,e){return G(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class jl{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new ui(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ze.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const d=new Uint8Array(o);i.set(d,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=on(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(d=>{r.data=this.getAvcDecryptedUnit(n,d),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)})}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class jn{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let d=0,l,h,c,u=-1,g=0;for(r===-1&&(u=0,g=this.getNALuType(t,0),r=0,d=1);d<i;){if(l=t[d++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=d-r-1,u>=0){const f={data:t.subarray(u,h),type:g};o.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&d<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h>0&&(f.data=Re(f.data,t.subarray(0,h)),f.state=0))}d<i?(c=this.getNALuType(t,d),u=d,g=c,r=0):r=-1}else r=0}if(u>=0&&r>=0){const f={data:t.subarray(u,i),type:g,state:r};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Re(f.data,t))}return e.naluState=r,o}}class bt{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&te.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Sr extends jn{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,d=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,c;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(d&&y.length>4){const v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var u;(u=n)!=null&&u.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=p;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,ci(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,d=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((g=e.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const v=p.subarray(1,4);let E="avc1.";for(let T=0;T<3;T++){let S=v[T].toString(16);S.length<2&&(S="0"+S),E+=S}e.codec=E}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new bt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new bt(e);let s=0,i=0,r=0,n=0,o,d,l;const h=t.readUByte.bind(t),c=t.readBits.bind(t),u=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);h();const E=h();if(c(5),f(3),h(),y(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const b=u();if(b===3&&f(1),y(),y(),f(1),g())for(d=b!==3?8:12,l=0;l<d;l++)g()&&(l<6?v(16,t):v(64,t))}y();const T=u();if(T===0)u();else if(T===1)for(f(1),p(),p(),o=u(),l=0;l<o;l++)p();y(),f(1);const S=u(),x=u(),I=c(1);I===0&&f(1),f(1),g()&&(s=u(),i=u(),r=u(),n=u());let A=[1,1];if(g()&&g())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-I)*(x+1)*16-(I?2:4)*(r+n),pixelRatio:A}}}class xr extends jn{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,d=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,c;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,d){var u;(u=n)!=null&&u.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,ci(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=re(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,d=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in g.params)e.params[f]=g.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(l.data);for(const f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new bt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new bt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),d=t.readUByte(),l=t.readUByte(),h=t.readUByte(),c=t.readUByte(),u=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),E=[],T=[];for(let ee=0;ee<s;ee++)E.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let ee=s;ee<8;ee++)t.readBits(2);for(let ee=0;ee<s;ee++)E[ee]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[ee]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const x=t.readUEG(),I=t.readUEG(),A=t.readBoolean();let b=0,k=0,L=0,F=0;A&&(b+=t.readUEG(),k+=t.readUEG(),L+=t.readUEG(),F+=t.readUEG());const U=t.readUEG(),B=t.readUEG(),N=t.readUEG(),$=t.readBoolean();for(let ee=$?0:s;ee<=s;ee++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let me=0;me<4;me++)for(let Ae=0;Ae<(me===3?2:6);Ae++)if(!t.readBoolean())t.readUEG();else{const De=Math.min(64,1<<4+(me<<1));me>1&&t.readEG();for(let rt=0;rt<De;rt++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const O=t.readUEG();let P=0;for(let ee=0;ee<O;ee++){let me=!1;if(ee!==0&&(me=t.readBoolean()),me){ee===O&&t.readUEG(),t.readBoolean(),t.readUEG();let Ae=0;for(let Xe=0;Xe<=P;Xe++){const De=t.readBoolean();let rt=!1;De||(rt=t.readBoolean()),(De||rt)&&Ae++}P=Ae}else{const Ae=t.readUEG(),Xe=t.readUEG();P=Ae+Xe;for(let De=0;De<Ae;De++)t.readUEG(),t.readBoolean();for(let De=0;De<Xe;De++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ee=t.readUEG();for(let me=0;me<ee;me++){for(let Ae=0;Ae<N+4;Ae++)t.readBits(1);t.readBits(1)}}let W=0,K=1,j=1,q=!0,X=1,J=0;t.readBoolean(),t.readBoolean();let le=!1;if(t.readBoolean()){if(t.readBoolean()){const Qe=t.readUByte(),_i=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Mt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Qe>0&&Qe<16?(K=_i[Qe-1],j=Mt[Qe-1]):Qe===255&&(K=t.readBits(16),j=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),le=t.readBoolean(),le&&(b+=t.readUEG(),k+=t.readUEG(),L+=t.readUEG(),F+=t.readUEG()),t.readBoolean()&&(X=t.readBits(32),J=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Mt=t.readBoolean(),ki=t.readBoolean();let Et=!1;(Mt||ki)&&(Et=t.readBoolean(),Et&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Et&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Ci=0;Ci<=s;Ci++){q=t.readBoolean();const xa=q||t.readBoolean();let Pi=!1;xa?t.readEG():Pi=t.readBoolean();const wi=Pi?1:t.readUEG()+1;if(Mt)for(let Tt=0;Tt<wi;Tt++)t.readUEG(),t.readUEG(),Et&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ki)for(let Tt=0;Tt<wi;Tt++)t.readUEG(),t.readUEG(),Et&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),W=t.readUEG())}let xe=x,de=I;if(A||le){let ee=1,me=1;S===1?ee=me=2:S==2&&(ee=2),xe=x-ee*k-ee*b,de=I-me*F-me*L}const yt=i?["A","B","C"][i]:"",Ft=o<<24|d<<16|l<<8|h;let vt=0;for(let ee=0;ee<32;ee++)vt=(vt|(Ft>>ee&1)<<31-ee)>>>0;let it=vt.toString(16);n===1&&it==="2"&&(it="6");const Sa=r?"H":"L";return{codecString:"hvc1.".concat(yt).concat(n,".").concat(it,".").concat(Sa).concat(v,".B0"),params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,d,l,h],general_constraint_indicator_flags:[c,u,g,f,p,y],general_level_idc:v,bit_depth:U+8,bit_depth_luma_minus8:U,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:W,chroma_format_idc:S,frame_rate:{fixed:q,fps:J/X}},width:xe,height:de,pixelRatio:[K,j]}}readPPS(e){const t=new bt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const fe=188;class je{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=je.syncOffset(e);return s>0&&t.warn("MPEG2-TS detected but first sync word found @ offset ".concat(s)),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(fe*5,t-fe)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let d=i;d<t;d+=fe)if(e[d]===71&&(t-d===fe||e[d+fe]===71)){if(o++,n===-1&&(n=d,n!==0&&(s=Math.min(n+fe*99,e.length-fe)+1)),r||(r=Js(e,d)===0),r&&o>1&&(n===0&&o>2||d+fe>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:tn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=je.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=je.createTrack("audio",i),this._id3Track=je.createTrack("id3"),this._txtTrack=je.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,d=this._id3Track,l=this._txtTrack;let h=n.pid,c=n.pesData,u=o.pid,g=d.pid,f=o.pesData,p=d.pesData,y=null,v=this.pmtParsed,E=this._pmtId,T=e.length;if(this.remainderData&&(e=Re(this.remainderData,e),T=e.length,this.remainderData=null),T<fe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:d,textTrack:l};const S=Math.max(0,je.syncOffset(e));T-=(T-S)%fe,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let x=0;for(let A=S;A<T;A+=fe)if(e[A]===71){const b=!!(e[A+1]&64),k=Js(e,A),L=(e[A+3]&48)>>4;let F;if(L>1){if(F=A+5+e[A+4],F===A+fe)continue}else F=A+4;switch(k){case h:if(b){if(c&&(r=ot(c,this.logger))){if(this.videoParser===null)switch(n.segmentCodec){case"avc":this.videoParser=new Sr;break;case"hevc":this.videoParser=new xr;break}this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)}c={data:[],size:0}}c&&(c.data.push(e.subarray(F,A+fe)),c.size+=A+fe-F);break;case u:if(b){if(f&&(r=ot(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(F,A+fe)),f.size+=A+fe-F);break;case g:b&&(p&&(r=ot(p,this.logger))&&this.parseID3PES(d,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(F,A+fe)),p.size+=A+fe-F);break;case 0:b&&(F+=e[F]+1),E=this._pmtId=ql(e,F);break;case E:{b&&(F+=e[F]+1);const U=zl(e,F,this.typeSupported,s,this.observer,this.logger);h=U.videoPid,h>0&&(n.pid=h,n.segmentCodec=U.segmentVideoCodec),u=U.audioPid,u>0&&(o.pid=u,o.segmentCodec=U.segmentAudioCodec),g=U.id3Pid,g>0&&(d.pid=g),y!==null&&!v&&(this.logger.warn("MPEG-TS PMT found at ".concat(A," after unknown PID '").concat(y,"'. Backtracking to sync byte @").concat(S," to parse all TS packets.")),y=null,A=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=k;break}}else x++;x>0&&ei(this.observer,new Error("Found ".concat(x," TS packet/s that do not start with 0x47")),void 0,this.logger),n.pesData=c,o.pesData=f,d.pesData=p;const I={audioTrack:o,videoTrack:n,id3Track:d,textTrack:l};return i&&this.extractRemainingSamples(I),I}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,d=i.pesData;let l;if(n&&(l=ot(n,this.logger))){if(this.videoParser===null)switch(s.segmentCodec){case"avc":this.videoParser=new Sr;break;case"hevc":this.videoParser=new xr;break}this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)}else s.pesData=n;if(o&&(l=ot(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;d&&(l=ot(d,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=d}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new jl(this.observer,this.config,t);return this.decrypt(i,r)}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const c=i.missing,u=i.sample.unit.byteLength;if(c===-1)r=Re(i.sample.unit,r);else{const g=u-c;i.sample.unit.set(r.subarray(0,c),g),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!ys(r,n);n++);if(n!==s){let c;const u=n<o-1;if(u?c="AAC PES did not start with ADTS header,offset:".concat(n):c="No ADTS header found in AAC PES",ei(this.observer,new Error(c),u,this.logger),!u)return}Mn(e,this.observer,r,n,this.audioCodec);let d;if(t.pts!==void 0)d=t.pts;else if(i){const c=Nn(e.samplerate);d=i.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=$n(e,r,n,d,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!ys(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(Kn(s,n)){const d=Gn(e,s,n,o,r);if(d)n+=d.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,d;for(;o<r&&(d=Yn(e,s,o,i,n++))>0;)o+=d}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=re({},t,{type:this._videoTrack?Ee.emsg:Ee.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Js(a,e){return((a[e+1]&31)<<8)+a[e+2]}function ql(a,e){return(a[e+10]&31)<<8|a[e+11]}function zl(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],d=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<d;){const h=Js(a,e),c=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){Ps("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){Ps("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){Ps("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&c>0){let u=e+5,g=c;for(;g>2;){switch(a[u]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3");break}const p=a[u+1]+2;u+=p,g-=p}}break;case 194:case 135:return ei(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=c+5}return n}function ei(a,e,t,s){s.warn("parsing error: ".concat(e.message)),a.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Ps(a,e){e.log("".concat(a," with AES-128-CBC encryption found in unencrypted stream"))}function ot(a,e){let t=0,s,i,r,n,o;const d=a.data;if(!a||a.size===0)return null;for(;d[0].length<19&&d.length>1;)d[0]=Re(d[0],d[1]),d.splice(1,1);if(s=d[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn("".concat(Math.round((n-o)/9e4),"s delta between PTS and DTS, align them")),n=o)):o=n),r=s[8];let c=r+9;if(a.size<=c)return null;a.size-=c;const u=new Uint8Array(a.size);for(let g=0,f=d.length;g<f;g++){s=d[g];let p=s.byteLength;if(c)if(c>p){c-=p;continue}else s=s.subarray(c),p-=c,c=0;u.set(s,t),t+=p}return i&&(i-=r+3),{data:u,pts:n,dts:o,len:i}}return null}class Xl{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const He=Math.pow(2,32)-1;class R{static init(){R.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in R.types)R.types.hasOwnProperty(e)&&(R.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);R.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);R.STTS=R.STSC=R.STCO=r,R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),d=new Uint8Array([0,0,0,1]);R.FTYP=R.box(R.types.ftyp,n,d,n,o),R.DINF=R.box(R.types.dinf,R.box(R.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return R.box(R.types.hdlr,R.HDLR_TYPES[e])}static mdat(e){return R.box(R.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(He+1)),i=Math.floor(t%(He+1));return R.box(R.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return R.box(R.types.mdia,R.mdhd(e.timescale||0,e.duration||0),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,s){return R.box(R.types.moof,R.mfhd(e),R.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(R.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(He+1)),i=Math.floor(t%(He+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return R.box(R.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return R.box(R.types.sdtp,s)}static stbl(e){return R.box(R.types.stbl,R.stsd(e),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=R.box(R.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),d=e.width,l=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return R.box(R.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return R.box(R.types.mp4a,R.audioStsd(e),R.box(R.types.esds,R.esds(e)))}static mp3(e){return R.box(R.types[".mp3"],R.audioStsd(e))}static ac3(e){return R.box(R.types["ac-3"],R.audioStsd(e),R.box(R.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(e));if(t==="ac3"&&e.config)return R.box(R.types.stsd,R.STSD,R.ac3(e));if(t==="mp3"&&e.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(e));if(t==="hevc"&&e.vps)return R.box(R.types.stsd,R.STSD,R.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error("unsupported ".concat(e.type," segment codec (").concat(t,"/").concat(e.codec,")"))}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(He+1)),o=Math.floor(s%(He+1));return R.box(R.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=R.sdtp(e),i=e.id,r=Math.floor(t/(He+1)),n=Math.floor(t%(He+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),R.box(R.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),R.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,d,l,h,c,u;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)d=s[o],l=d.duration,h=d.size,c=d.flags,u=d.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return R.box(R.types.trun,n)}static initSegment(e){R.types||R.init();const t=R.moov(e);return Re(R.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let p=0;p<s[f].length;p+=1)n+=2+s[f][p].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const d=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===d?128:0),0,s[f].length]),n),n+=3;for(let p=0;p<s[f].length;p+=1)o.set(new Uint8Array([s[f][p].length>>8,s[f][p].length&255]),n),n+=2,o.set(s[f][p],n),n+=s[f][p].length}const l=R.box(R.types.hvcC,o),h=e.width,c=e.height,u=e.pixelRatio[0],g=e.pixelRatio[1];return R.box(R.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,g>>24,g>>16&255,g>>8&255,g&255])))}}R.types=void 0;R.HDLR_TYPES=void 0;R.STTS=void 0;R.STSC=void 0;R.STCO=void 0;R.STSZ=void 0;R.VMHD=void 0;R.SMHD=void 0;R.STSD=void 0;R.FTYP=void 0;R.DINF=void 0;const qn=9e4;function Ai(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function Ql(a,e,t=1,s=!1){return Ai(a,e,1/t,s)}function St(a,e=!1){return Ai(a,1e3,1/qn,e)}function Zl(a,e=1){return Ai(a,qn,1/e)}const Jl=10*1e3,ed=1024,td=1152,sd=1536;let lt=null,ws=null;function Ar(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class ts{constructor(e,t,s,i){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.ISGenerated=!1,lt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);lt=n?parseInt(n[1]):0}if(ws===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);ws=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,d=o-r;return d<-4294967296&&(t=!0,o=be(o,s),d=o-r),d>0?r:o},s);return t&&this.logger.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,d){let l,h,c,u,g,f,p=r,y=r;const v=e.pid>-1,E=t.pid>-1,T=t.samples.length,S=e.samples.length>0,x=o&&T>0||T>1;if((!v||S)&&(!E||x)||this.ISGenerated||o){if(this.ISGenerated){var A,b,k,L;const N=this.videoTrackConfig;(N&&(t.width!==N.width||t.height!==N.height||((A=t.pixelRatio)==null?void 0:A[0])!==((b=N.pixelRatio)==null?void 0:b[0])||((k=t.pixelRatio)==null?void 0:k[1])!==((L=N.pixelRatio)==null?void 0:L[1]))||!N&&x||this.nextAudioPts===null&&S)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,r,n));const F=this.isVideoContiguous;let U=-1,B;if(x&&(U=id(t.samples),!F&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,U>0){this.logger.warn("[mp4-remuxer]: Dropped ".concat(U," out of ").concat(T," video samples due to a missing keyframe"));const N=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(U),t.dropped+=U,y+=(t.samples[0].pts-N)/t.inputTimeScale,B=y}else U===-1&&(this.logger.warn("[mp4-remuxer]: No keyframe found out of ".concat(T," video samples")),f=!1);if(this.ISGenerated){if(S&&x){const N=this.getVideoStartPts(t.samples),D=(be(e.samples[0].pts,N)-N)/t.inputTimeScale;p+=Math.max(0,D),y+=Math.max(0,-D)}if(S){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,p,this.isAudioContiguous,n,E||x||d===V.AUDIO?y:void 0),x){const N=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,y,F,N)}}else x&&(l=this.remuxVideo(t,y,F,0));l&&(l.firstKeyFrame=U,l.independent=U!==-1,l.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=zn(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=Xn(i,r,this._initPTS))),{audio:h,video:l,initSegment:c,independent:f,text:u,id3:g}}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,d={},l=this._initPTS;let h=!l||i,c="audio/mp4",u,g,f,p;if(h&&(u=g=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}d.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):R.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,f=e.inputTimeScale,!l||f!==l.timescale?u=g=r[0].pts-Math.round(f*s):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:R.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const y=this.getVideoStartPts(n),v=Math.round(f*s);g=Math.min(g,be(n[0].dts,y)-v),u=Math.min(u,y-v)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:u,timescale:f},this._initDTS={baseTime:g,timescale:f}):u=f=void 0,{tracks:d,initPTS:u,timescale:f,trackId:p}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],d=n.length,l=this._initPTS;let h=this.nextAvcDts,c=8,u=this.videoSampleDuration,g,f,p=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,v=!1;if(!s||h===null){const P=t*r,M=n[0].pts-be(n[0].dts,n[0].pts);lt&&h!==null&&Math.abs(P-M-h)<15e3?s=!0:h=P-M}const E=l.baseTime*r/l.timescale;for(let P=0;P<d;P++){const M=n[P];M.pts=be(M.pts-E,h),M.dts=be(M.dts-E,h),M.dts<n[P>0?P-1:P].dts&&(v=!0)}v&&n.sort(function(P,M){const W=P.dts-M.dts,K=P.pts-M.pts;return W||K}),g=n[0].dts,f=n[n.length-1].dts;const T=f-g,S=T?Math.round(T/(d-1)):u||e.inputTimeScale/30;if(s){const P=g-h,M=P>S,W=P<-1;if((M||W)&&(M?this.logger.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(St(P,!0)," ms (").concat(P,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.logger.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(St(-P,!0)," ms (").concat(P,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!W||h>=n[0].pts||lt)){g=h;const K=n[0].pts-P;if(M)n[0].dts=g,n[0].pts=K;else{let j=!0;for(let q=0;q<n.length&&!(n[q].dts>K&&j);q++){const X=n[q].pts;if(n[q].dts-=P,n[q].pts-=P,q<n.length-1){const J=n[q+1].pts,le=n[q].pts,ue=J<=le,xe=J<=X;j=ue==xe}}}this.logger.log("Video: Initial PTS/DTS adjusted: ".concat(St(K,!0),"/").concat(St(g,!0),", delta: ").concat(St(P,!0)," ms"))}}g=Math.max(0,g);let x=0,I=0,A=g;for(let P=0;P<d;P++){const M=n[P],W=M.units,K=W.length;let j=0;for(let q=0;q<K;q++)j+=W[q].data.length;I+=j,x+=K,M.length=j,M.dts<A?(M.dts=A,A+=S/4|0||1):A=M.dts,p=Math.min(M.pts,p),y=Math.max(M.pts,y)}f=n[d-1].dts;const b=I+4*x+8;let k;try{k=new Uint8Array(b)}catch(P){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:P,bytes:b,reason:"fail allocating video mdat ".concat(b)});return}const L=new DataView(k.buffer);L.setUint32(0,b),k.set(R.types.mdat,4);let F=!1,U=Number.POSITIVE_INFINITY,B=Number.POSITIVE_INFINITY,N=Number.NEGATIVE_INFINITY,$=Number.NEGATIVE_INFINITY;for(let P=0;P<d;P++){const M=n[P],W=M.units;let K=0;for(let X=0,J=W.length;X<J;X++){const le=W[X],ue=le.data,xe=le.data.byteLength;L.setUint32(c,xe),c+=4,k.set(ue,c),c+=xe,K+=4+xe}let j;if(P<d-1)u=n[P+1].dts-M.dts,j=n[P+1].pts-M.pts;else{const X=this.config,J=P>0?M.dts-n[P-1].dts:S;if(j=P>0?M.pts-n[P-1].pts:S,X.stretchShortVideoTrack&&this.nextAudioPts!==null){const le=Math.floor(X.maxBufferHole*r),ue=(i?p+i*r:this.nextAudioPts)-M.pts;ue>le?(u=ue-J,u<0?u=J:F=!0,this.logger.log("[mp4-remuxer]: It is approximately ".concat(ue/90," ms to the next segment; using duration ").concat(u/90," ms for the last video frame."))):u=J}else u=J}const q=Math.round(M.pts-M.dts);U=Math.min(U,u),N=Math.max(N,u),B=Math.min(B,j),$=Math.max($,j),o.push(Ar(M.key,u,K,q))}if(o.length){if(lt){if(lt<70){const P=o[0].flags;P.dependsOn=2,P.isNonSync=0}}else if(ws&&$-B<N-U&&S/N<.025&&o[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let P=g;for(let M=0,W=o.length;M<W;M++){const K=P+o[M].duration,j=P+o[M].cts;if(M<W-1){const q=K+o[M+1].cts;o[M].duration=q-j}else o[M].duration=M?o[M-1].duration:S;o[M].cts=0,P=K}}}u=F||!u?S:u,this.nextAvcDts=h=f+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const D=R.moof(e.sequenceNumber++,g,re(e,{samples:o})),C="video",O={data1:D,data2:k,startPTS:p/r,endPTS:(y+u)/r,startDTS:g/r,endDTS:h/r,type:C,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,O}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return td;case"ac3":return sd;default:return ed}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,d=n/o,l=this.getSamplesPerFrame(e),h=l*d,c=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=r!==void 0;let p=e.samples,y=u?0:8,v=this.nextAudioPts||-1;const E=t*n,T=c.baseTime*n/c.timescale;if(this.isAudioContiguous=s=s||p.length&&v>0&&(i&&Math.abs(E-v)<9e3||Math.abs(be(p[0].pts-T,E)-v)<20*h),p.forEach(function(D){D.pts=be(D.pts-T,E)}),!s||v<0){if(p=p.filter(D=>D.pts>=0),!p.length)return;r===0?v=0:i&&!f?v=Math.max(0,E):v=p[0].pts}if(e.segmentCodec==="aac"){const D=this.config.maxAudioFramesDrift;for(let C=0,O=v;C<p.length;C++){const P=p[C],M=P.pts,W=M-O,K=Math.abs(1e3*W/n);if(W<=-D*h&&f)C===0&&(this.logger.warn("Audio frame @ ".concat((M/n).toFixed(3),"s overlaps nextAudioPts by ").concat(Math.round(1e3*W/n)," ms.")),this.nextAudioPts=v=O=M);else if(W>=D*h&&K<Jl&&f){let j=Math.round(W/h);O=M-j*h,O<0&&(j--,O+=h),C===0&&(this.nextAudioPts=v=O),this.logger.warn("[mp4-remuxer]: Injecting ".concat(j," audio frame @ ").concat((O/n).toFixed(3),"s due to ").concat(Math.round(1e3*W/n)," ms gap."));for(let q=0;q<j;q++){const X=Math.max(O,0);let J=Xl.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);J||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),J=P.unit.subarray()),p.splice(C,0,{unit:J,pts:X}),O+=h,C++}}P.pts=O,O+=h}}let S=null,x=null,I,A=0,b=p.length;for(;b--;)A+=p[b].unit.byteLength;for(let D=0,C=p.length;D<C;D++){const O=p[D],P=O.unit;let M=O.pts;if(x!==null){const K=g[D-1];K.duration=Math.round((M-x)/d)}else if(s&&e.segmentCodec==="aac"&&(M=v),S=M,A>0){A+=y;try{I=new Uint8Array(A)}catch(K){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:K,bytes:A,reason:"fail allocating audio mdat ".concat(A)});return}u||(new DataView(I.buffer).setUint32(0,A),I.set(R.types.mdat,4))}else return;I.set(P,y);const W=P.byteLength;y+=W,g.push(Ar(!0,l,W,0)),x=M}const k=g.length;if(!k)return;const L=g[g.length-1];this.nextAudioPts=v=x+d*L.duration;const F=u?new Uint8Array(0):R.moof(e.sequenceNumber++,S/d,re({},e,{samples:g}));e.samples=[];const U=S/n,B=v/n,$={data1:F,data2:I,startPTS:U,endPTS:B,startDTS:U,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,$}}function be(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function id(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function zn(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const d=a.samples[o];d.pts=be(d.pts-t.baseTime*r/t.timescale,e*r)/r,d.dts=be(d.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function Xn(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=be(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class rd{constructor(e,t,s,i){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.logger=i}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(Qa(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=nn(e);i.audio&&(t=Lr(i.audio,ne.AUDIO,this.logger)),i.video&&(s=Lr(i.video,ne.VIDEO,this.logger));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:t+","+s,supplemental:i.video.supplemental,initSegment:e,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,supplemental:i.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,s,i,r,n){var o,d;let{initPTS:l,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};G(h)||(h=this.lastEndTime=r||0);const u=t.samples;if(!(u!=null&&u.length))return c;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(u),f=this.initData),!((d=f)!=null&&d.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=Za(u,f,this.logger),y=f.audio?p[f.audio.id]:null,v=f.video?p[f.video.id]:null,E=Yt(v,1/0),T=Yt(y,1/0),S=Yt(v,0,!0),x=Yt(y,0,!0);let I,A=r,b=0;if(y&&(!v||!l&&T<E||l&&l.trackId===f.audio.id)?(g.trackId=f.audio.id,I=y,b=x-T):v&&(g.trackId=f.video.id,I=v,b=S-E),I){const D=I.timescale;A=I.start/D,g.timescale=D,l||(g.initPTS=I.start-r*D,this.initPTS=l={baseTime:g.initPTS,timescale:D,trackId:g.trackId})}(n||!l)&&(nd(l,A,r,b)||g.timescale!==l.timescale)&&(g.initPTS=A-r,l&&l.timescale===1&&this.logger.warn("Adjusting initPTS @".concat(r," from ").concat(l.baseTime/l.timescale," to ").concat(g.initPTS)),this.initPTS=l={baseTime:g.initPTS,timescale:1});const k=e?A-l.baseTime/l.timescale:h;Ja(f,u,l.baseTime/l.timescale);const L=k+b;b>0?this.lastEndTime=L:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const F=!!f.audio,U=!!f.video;let B="";F&&(B+="audio"),U&&(B+="video");const N={data1:u,startPTS:k,startDTS:k,endPTS:L,endDTS:L,type:B,hasAudio:F,hasVideo:U,nb:1,dropped:0};c.audio=F&&!U?N:void 0,c.video=U?N:void 0;const $=v==null?void 0:v.sampleCount;if($){const D=v.keyFrameIndex,C=D!==-1;N.nb=$,N.dropped=D===0||this.isVideoContiguous?0:C?D:$,N.independent=C,N.firstKeyFrame=D,C&&v.keyFrameStart&&(N.firstKeyFramePTS=v.keyFrameStart-l.baseTime/l.timescale),this.isVideoContiguous||(c.independent=C),this.isVideoContiguous||(this.isVideoContiguous=C),N.dropped&&this.logger.warn("fmp4 does not start with IDR: firstIDR ".concat(D,"/").concat($," dropped: ").concat(N.dropped," pts: ").concat(N.firstKeyFramePTS||"NA"))}return c.initSegment=g,c.id3=zn(s,r,l,l),i.samples.length&&(c.text=Xn(i,r,l)),c}}function Yt(a,e,t=!1){return(a==null?void 0:a.start)!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function nd(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function Lr(a,e,t){const s=a==null?void 0:a.codec;return s&&s.length>4?s:e===ne.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?cs(s,!1):(t.warn('Unhandled audio codec "'.concat(s,'" in mp4 MAP')),s||"mp4a"):(t.warn('Unhandled video codec "'.concat(s,'" in mp4 MAP')),s||"avc1")}let Ve;try{Ve=self.performance.now.bind(self.performance)}catch(a){Ve=Date.now}const ss=[{demux:Yl,remux:rd},{demux:je,remux:ts},{demux:Vl,remux:ts},{demux:Hl,remux:ts}];ss.splice(2,0,{demux:Kl,remux:ts});class br{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Ve();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:d}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:c,accurateTimeOffset:u,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:v,duration:E,initSegmentData:T}=d,S=ad(n,t);if(S&&ht(S.method)){const b=this.getDecrypter(),k=gi(S.method);if(b.isSync()){let L=b.softwareDecrypt(n,S.key.buffer,S.iv.buffer,k);if(s.part>-1){const U=b.flush();L=U&&U.buffer}if(!L)return r.executeEnd=Ve(),Os(s);n=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=b.webCryptoDecrypt(n,S.key.buffer,S.iv.buffer,k).then(L=>{const F=this.push(L,null,s);return this.decryptionPromise=null,F}),this.decryptionPromise}const x=this.needsProbing(h,c);if(x){const b=this.configureTransmuxer(n);if(b)return this.logger.warn("[transmuxer] ".concat(b.message)),this.observer.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),r.executeEnd=Ve(),Os(s)}(h||c||f||x)&&this.resetInitSegment(T,p,y,E,t),(h||f||x)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const I=this.transmux(n,S,g,u,s);this.asyncResult=wt(I);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Ve(),I}flush(e){const t=e.transmuxing;t.executeStart=Ve();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const c=s.flush();c&&n.push(this.push(c.buffer,null,e))}const{demuxer:d,remuxer:l}=this;if(!d||!l){t.executeEnd=Ve();const c=[Os(e)];return this.asyncResult?Promise.resolve(c):c}const h=d.flush(o);return wt(h)?(this.asyncResult=!0,h.then(c=>(this.flushRemux(n,c,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:d,timeOffset:l}=this.currentTransmuxState;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(s.sn).concat(s.part>-1?" part: "+s.part:""," of ").concat(this.id===V.MAIN?"level":"track"," ").concat(s.level));const h=this.remuxer.remux(i,r,n,o,l,d,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Ve()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:d}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,d,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let c=0,u=ss.length;c<u;c++){var n;if((n=ss[c].demux)!=null&&n.probe(e,this.logger)){r=ss[c];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,d=this.remuxer,l=r.remux,h=r.demux;(!d||!(d instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ui(this.config)),e}}function ad(a,e){let t=null;return a.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Os=a=>({remuxResult:{},chunkMeta:a});function wt(a){return"then"in a&&a.then instanceof Function}class od{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class ld{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Ir=0;class Qn{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ir++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=d=>{const l=d.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var c;const u=(c=this.workerContext)==null?void 0:c.objectURL;u&&self.URL.revokeObjectURL(u);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=d=>{if(!this.hls)return;const l=new Error("".concat(d.message," (").concat(d.filename,":").concat(d.lineno,")"));this.hls.config.enableWorker=!1,this.hls.logger.warn('Error in "'.concat(this.id,'" Web Worker, fallback to inline')),this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(d,l)=>{l=l||{},l.frag=this.frag||void 0,d===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(d,l)};this.observer=new yi,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=Vi(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const d=this.hls.logger;if(r.workerPath||gl()){try{r.workerPath?(d.log("loading Web Worker ".concat(r.workerPath,' for "').concat(t,'"')),this.workerContext=pl(r.workerPath)):(d.log('injecting Web Worker for "'.concat(t,'"')),this.workerContext=ml());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ae(r)})}catch(h){d.warn('Error setting up "'.concat(t,'" Web Worker, fallback to inline'),h),this.terminateWorker(),this.error=null,this.transmuxer=new br(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new br(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Ir++;const t=this.hls.config,s=Vi(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ae(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),yl(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,o,d,l,h){var c,u;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,p=n?n.start:r.start,y=r.decryptdata,v=this.frag,E=!(v&&r.cc===v.cc),T=!(v&&l.level===v.level),S=v?l.sn-v.sn:-1,x=this.part?l.part-this.part.index:-1,I=S===0&&l.id>1&&l.id===(v==null?void 0:v.stats.chunkCount),A=!T&&(S===1||S===0&&(x===1||I&&x<=0)),b=self.performance.now();(T||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),n&&(x||!A)&&(n.stats.parsing.start=b);const k=!(v&&((c=r.initSegment)==null?void 0:c.url)===((u=v.initSegment)==null?void 0:u.url)),L=new ld(E,A,d,T,p,k);if(!A||E||k){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for ".concat(r.type," sn: ").concat(l.sn).concat(l.part>-1?" part: "+l.part:""," ").concat(this.id===V.MAIN?"level":"track",": ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(E,"\n trackSwitch: ").concat(T,"\n contiguous: ").concat(A,"\n accurateTimeOffset: ").concat(d,"\n timeOffset: ").concat(p,"\n initSegmentChange: ").concat(k));const F=new od(s,i,t,o,h);this.configureTransmuxer(F)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(f){const F=f.push(e,y,l,L);wt(F)?F.then(U=>{this.handleTransmuxComplete(U)}).catch(U=>{this.transmuxerError(U,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(F)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);wt(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Rr=100;class dd extends pi{constructor(e,t,s){super(e,t,s,"audio-stream-controller",V.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){if(s===V.MAIN){const n=t.cc,o=this.fragCurrent;if(this.initPTS[n]={baseTime:i,timescale:r},this.log("InitPTS for cc: ".concat(n," found from main: ").concat(i,"/").concat(r)),this.mainAnchor=t,this.state===w.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==n)&&this.syncWithAnchor(t,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&o&&o.cc!==n?(o.abortRequests(),this.syncWithAnchor(t,o)):this.state===w.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(i==null?void 0:i.cc)===t.cc)return;const r=(i||e).cc,n=this.getLevelDetails(),o=this.getLoadPosition(),d=yn(n,r,o);d&&(this.log("Waiting fragment cc (".concat(t==null?void 0:t.cc,") cancelled because video is at cc ").concat(e.cc)),this.startFragRequested=!1,this.nextLoadPosition=d.start,this.resetLoadingState(),this.state===w.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=w.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Rr),s>0&&e===-1?(this.log("Override startPosition with lastCurrentTime @".concat(s.toFixed(3))),e=s,this.state=w.IDLE):this.state=w.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case w.IDLE:this.doTickIdle();break;case w.WAITING_TRACK:{const{levels:t,trackId:s}=this,i=t==null?void 0:t[s],r=i==null?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=w.WAITING_INIT_PTS}break}case w.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:i,trackId:r}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((i==null?void 0:i[r])||null),this.state=w.IDLE}break}case w.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:s,part:i,cache:r,complete:n}=t,o=this.mainAnchor;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.state=w.FRAG_LOADING;const d=r.flush().buffer,l={frag:s,part:i,payload:d,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else o&&o.cc!==t.frag.cc&&this.syncWithAnchor(o,t.frag)}else this.state=w.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],d=o.details;if(!d||this.waitForLive(o)||this.waitForCdnTuneIn(d)){this.state=w.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ne.AUDIO,V.AUDIO));const h=this.getFwdBufferInfo(l,V.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,d)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=w.ENDED;return}const c=h.len,u=t.maxBufferLength,g=d.fragments,f=g[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){const T=p;d.PTSKnown&&T<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(c>=u&&!this.switchingTrack&&y<g[g.length-1].start)return;let v=this.getNextFragment(y,d);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,d,h,V.MAIN,u)),!v){this.bufferFlushed=!0;return}let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&ge(v)&&!v.endList&&(!d.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===he.OK&&(this.mainFragLoading=E=null),E&&ge(E))){if(v.start>E.end){const S=this.fragmentTracker.getFragAtPos(y,V.MAIN);S&&S.end>E.end&&(E=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(v.start>E.end)return}this.loadFragment(v,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Dt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==w.STOPPED&&(this.setInterval(Rr),this.state=w.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:o,track:d}=t;if(!i){this.warn("Audio tracks reset while loading track ".concat(n,' "').concat(d.name,'" of "').concat(o,'"'));return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==w.STOPPED&&(this.state=w.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log("Audio track ".concat(n,' "').concat(d.name,'" of "').concat(o,'" loaded [').concat(r.startSN,",").concat(r.endSN,"]").concat(r.lastPartSn?"[part-".concat(r.lastPartSn,"-").concat(r.lastPartIndex,"]"):"",",duration:").concat(r.totalduration));const h=i[n];let c=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var u;c=this.alignPlaylists(r,h.details,(u=this.levelLastLoaded)==null?void 0:u.details)}r.alignedSliding||(Cn(r,l),r.alignedSliding||ps(r,l),c=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===w.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=w.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:o,levels:d}=this;if(!d){this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(s.sn," of level ").concat(s.level," will not be buffered"));return}const l=d[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Qn(this.hls,V.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const y=i?i.index:-1,v=y!==-1,E=new fi(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,v);u.push(r,f,c,"",s,i,h.totalduration,!1,E,g)}else{this.log("Unknown video PTS for cc ".concat(s.cc,", waiting for video PTS before demuxing audio frag ").concat(s.sn," of [").concat(h.startSN," ,").concat(h.endSN,"],track ").concat(o));const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Pn,complete:!1};p.push(new Uint8Array(r)),this.state!==w.STOPPED&&(this.state=w.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===V.MAIN&&ge(t.frag)&&(this.mainFragLoading=t,this.state===w.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==V.AUDIO){!this.audioOnly&&s.type===V.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn("Fragment ".concat(s.sn).concat(i?" p: "+i.index:""," of level ").concat(s.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));return}if(ge(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,se({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=w.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.AUDIO,t);break;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===w.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Z.AUDIO_TRACK&&(this.state=w.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.resetLoadingState();break;case _.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ne.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ne.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===w.ENDED&&(this.state=w.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,V.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:d,part:l,level:h}=o,{details:c}=h,{audio:u,text:g,id3:f,initSegment:p}=r;if(this.fragContextChanged(d)||!c){this.fragmentTracker.removeFragment(d);return}if(this.state=w.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=d.initSegment||d;this._bufferInitSegment(h,p.tracks,y,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(u){const{startPTS:y,endPTS:v,startDTS:E,endDTS:T}=u;l&&(l.elementaryStreams[ne.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),d.setElementaryStreamInfo(ne.AUDIO,y,v,E,T),this.bufferFragmentData(u,d,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const y=re({id:s,frag:d,details:c},f);i.trigger(m.FRAG_PARSING_METADATA,y)}if(g){const y=re({id:s,frag:d,details:c},g);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==w.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=V.AUDIO;const n=e.audioCodec;this.log("Init audio buffer, container:".concat(r.container,", codecs[level/parsed]=[").concat(n,"/").concat(r.codec,"]")),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const d={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,d)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===he.NOT_LOADED||i===he.PARTIAL){var r;if(!ge(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter ".concat(e.cc," of live stream before loading audio fragment ").concat(e.sn," of level ").concat(this.trackId)),this.state=w.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&ps(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o}=this.bufferedTrack;tt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o},e,Je)||(us(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,se({},e))}}class Li extends Ke{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let d;try{d=new self.URL(o.URI,t.url).href}catch(l){this.warn("Could not construct new URL for Rendition Report: ".concat(l)),d=o.URI||""}if(d===e){r=n;break}else d===e.substring(0,d.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let d=parseInt(n["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);d>=0&&h>t.partTarget&&(d+=1)}const l=s&&Hi(s);return new Wi(o,d>=0?d:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(s))}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-o;const d=this.hls.config.timelineOffset;if(d!==i.appliedTimelineOffset){const h=Math.max(d||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(c=>{c.start=c.playlistOffset+h})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){rl(s,i);const E=i.playlistParsingError;if(E){this.warn(E);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;const{networkDetails:S}=t;T.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:E,reason:E.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:S,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,g=(i.edge-u)*1e3,f=In(i,g);if(i.requestScheduled+f<n?i.requestScheduled=n:i.requestScheduled+=f,this.log("live playlist ".concat(e," ").concat(i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED")),!this.canLoad||!i.live)return;let p,y,v;if(i.canBlockReload&&i.endSN&&i.advanced){const E=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,x=i.lastPartIndex,I=x!==-1,A=T===S;I?A?(y=S+1,v=E?0:x):(y=T,v=E?x+1:i.maxPartIndex):y=S+1;const b=i.age,k=b+i.ageHeader;let L=Math.min(k-i.partTarget,i.targetduration*1.5);if(L>0){if(k>i.targetduration*3)this.log("Playlist last advanced ".concat(b.toFixed(2),"s ago. Omitting segment and part directives.")),y=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&k-i.partTarget>s.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(s.tuneInGoal," to: ").concat(L," with playlist age: ").concat(i.age)),L=0;else{const F=Math.floor(L/i.targetduration);if(y+=F,v!==void 0){const U=Math.round(L%i.targetduration/i.partTarget);v+=U}this.log("CDN Tune-in age: ".concat(i.ageHeader,"s last advanced ").concat(b.toFixed(2),"s goal: ").concat(L," skip sn ").concat(F," to part ").concat(v))}i.tuneInGoal=L}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v),E||!A){i.requestScheduled=n,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const o=n-r;this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Hi(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Jt.No),new Wi(s,i,r)}checkRetry(e){const t=e.details,s=fs(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},d=!!i&&!!o&&(r===pe.RetryRequest||!i.resolved&&r===pe.SendAlternateToPenaltyBox);if(d){var l;if(n>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn("Retrying playlist loading ".concat(n+1,"/").concat(o.maxNumRetry,' after "').concat(t,'" without delivery-directives')),this.loadPlaylist();else{const h=hi(o,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn("Retrying playlist loading ".concat(n+1,"/").concat(o.maxNumRetry,' after "').concat(t,'" in ').concat(h,"ms"))}e.levelRetry=!0,i.resolved=!0}return d}}function Zn(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!Ot(a[t].attrs,e[t].attrs))return!1;return!0}function Ot(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function ti(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class cd extends Li{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn("Audio track with id:".concat(s," and group:").concat(i," not found in active group ").concat(n==null?void 0:n.groupId));return}const o=n.details;n.details=t.details,this.log("Audio track ".concat(s,' "').concat(n.name,'" lang:').concat(n.lang," group:").concat(i," loaded [").concat(r.startSN,"-").concat(r.endSN,"]")),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,g)=>{u.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const d=this.hls.config.audioPreference;if(!r&&d){const u=Me(d,o,Je);if(u>-1)r=o[u];else{const g=Me(d,this.tracks);r=this.tracks[g]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log("Updating audio tracks, ".concat(o.length," track(s) found in group(s): ").concat(s==null?void 0:s.join(","))),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const c=this.trackId;if(l!==-1&&c===-1)this.setAudioTrack(l);else if(o.length&&c===-1){var n;const u=new Error("No audio track selected for current audio group-ID(s): ".concat((n=this.groupIds)==null?void 0:n.join(",")," track count: ").concat(o.length));this.warn(u.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===Z.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&tt(e,i,Je))return i;const r=Me(e,this.tracksInGroup,Je);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=Lo(e,t.levels,s,n,Je);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=Me(e,s);if(n>-1)return s[n]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn("Invalid audio track id: ".concat(e));return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log("Switching to audio-track ".concat(e,' "').concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId," channels:").concat(i.channels)),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,se({},i)),r))return;const n=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||tt(e,i,Je)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:d}=e;for(let l=0;l<t.length;l++){const h=t[l];if(tt({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:d},h,Je))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Ot(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Ot(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&us(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n==null?void 0:n.age;this.log("Loading audio-track ".concat(s,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(i).concat((t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:"").concat(o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""," ").concat(r)),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class hd{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s==null?void 0:s.buffer;return i?"SourceBuffer".concat(i.updating?" updating":"").concat(s.ended?" ended":"").concat(s.ending?" ending":""):"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const Dr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Jn="HlsJsTrackRemovedError";class ud extends Error{constructor(e){super(e),this.name=Jn}}class fd extends Ke{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error("Media element src was set while attaching MediaSource (".concat(i," > ").concat(s,")"))},this.hls=e,this.fragmentTracker=t,this.appendSource=Ga(qe(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn("Transfering MediaSource with".concat(n?" operations in queue":"").concat(r?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?re(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=re({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log("".concat(i," bufferCodec event(s) expected.")),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media,i=qe(this.appendSource);if(this.transferData=this.overrides=void 0,s&&i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const d=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||d&&n instanceof d,_r(s),gd(s,o),s.load()}catch(d){s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log("".concat(((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat((s=e.constructor)==null?void 0:s.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,o=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(ae(s,(d,l)=>d==="initSegment"?void 0:l),";\ntransfer tracks: ").concat(ae(i,(d,l)=>d==="initSegment"?void 0:l),"}")),!Zr(i,s)){t.mediaSource=null,t.tracks=void 0;const d=e.currentTime,l=this.details,h=Math.max(d,(l==null?void 0:l.fragments[0].start)||0);if(h-d>1){this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(d," -> ").concat(h));return}this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(i),'"->"').concat(Object.keys(s),'") start time: ').concat(h," currentTime: ").concat(d)),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(d=>{const l=d,h=i[l];if(h){const c=h.buffer;if(c){const u=this.fragmentTracker,g=h.id;if(u.hasFragments(g)||u.hasParts(g)){const y=z.getBuffered(c);u.detectEvictedFragments(l,y,g,null,!0)}const f=Fs(l),p=[l,c];this.sourceBuffers[f]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source ".concat(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const d=r.sourceBuffers;for(let l=d.length;l--;)o&&d[l].abort(),r.removeSourceBuffer(d[l]);o&&r.endOfStream()}catch(d){this.warn("onMediaDetaching: ".concat(d.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&_r(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn("onBufferReset ".concat(e),r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Fs(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hd(this.tracks)}onBufferCodecs(e,t){const s=this.tracks,i=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(i,'" (current SB count ').concat(this.sourceBufferCount,")"));const r="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),n=!r&&this.sourceBufferCount&&this.media&&i.some(o=>!s[o]);if(r||n){this.warn('Unsupported transition between "'.concat(Object.keys(s),'" and "').concat(i,'" SourceBuffers'));return}i.forEach(o=>{var d,l,h;const c=t[o],{id:u,codec:g,levelCodec:f,container:p,metadata:y,supplemental:v}=c;let E=s[o];const T=(d=this.transferData)==null||(l=d.tracks)==null?void 0:l[o],S=T!=null&&T.buffer?T:E,x=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),I=S==null?void 0:S.levelCodec;E||(E=s[o]={buffer:void 0,listeners:[],codec:g,supplemental:v,container:p,levelCodec:f,metadata:y,id:u});const A=Zt(x,I),b=A==null?void 0:A.replace(Dr,"$1");let k=Zt(g,f);const L=(h=k)==null?void 0:h.replace(Dr,"$1");k&&A&&b!==L&&(o.slice(0,5)==="audio"&&(k=cs(k,this.appendSource)),this.log("switching codec ".concat(x," to ").concat(k)),k!==(E.pendingCodec||E.codec)&&(E.pendingCodec=k),E.container=p,this.appendChangeType(o,p,k))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i="".concat(t,";codecs=").concat(s),r={label:"change-type=".concat(i),execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log("changing ".concat(e," sourceBuffer type to ").concat(i)),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn("Failed to change ".concat(e," SourceBuffer type"),n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,V.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const d=this.tracks.video;(this.lastVideoAppendEnd>i||d!=null&&d.buffer&&z.isBuffered(d.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,V.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:d,chunkMeta:l}=t,h=l.buffering[r],c=o.sn,u=self.performance.now();h.start=u;const g=o.stats.buffering,f=d?d.stats.buffering:null;g.start===0&&(g.start=u),f&&f.start===0&&(f.start=u);const p=s.audio;let y=!1;r==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const v=this.tracks.video,E=v==null?void 0:v.buffer;if(E&&c!=="initSegment"){const x=d||o,I=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend){const b=x.start+x.duration*.05,k=E.buffered,L=this.currentOp("video");!k.length&&!L?this.blockAudio(x):!L&&!z.isBuffered(E,b)&&this.lastVideoAppendEnd<b&&this.blockAudio(x)}else if(r==="video"){const A=x.end;if(I){const b=I.frag.start;(A>b||A<this.lastVideoAppendEnd||z.isBuffered(E,b))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}const T=(d||o).start,S={label:"append-".concat(r),execute:()=>{if(h.executeStart=self.performance.now(),y){const x=this.tracks[r];if(x){const I=x.buffer;if(I){const A=T-I.timestampOffset;Math.abs(A)>=.1&&(this.log("Updating audio SourceBuffer timestampOffset to ".concat(T," (delta: ").concat(A,") sn: ").concat(c,")")),I.timestampOffset=T)}}}this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();h.executeEnd=h.end=x,g.first===0&&(g.first=x),f&&f.first===0&&(f.first=x);const I={};this.sourceBuffers.forEach(([A,b])=>{A&&(I[A]=z.getBuffered(b))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:d,chunkMeta:l,parent:o.type,timeRanges:I})},onError:x=>{var I;const A={type:H.MEDIA_ERROR,parent:o.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:d,chunkMeta:l,error:x,err:x,fatal:!1},b=(I=this.media)==null?void 0:I.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR)A.details=_.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!b)A.errorAction=_t(!0);else if(x.name===Jn&&this.sourceBufferCount===0)A.errorAction=_t(!0);else{const k=++this.appendErrors[r];this.warn("Failed ".concat(k,"/").concat(this.hls.config.appendErrorMaxRetry,' times to append segment in "').concat(r,'" sourceBuffer (').concat(b||"no media error",")")),(k>=this.hls.config.appendErrorMaxRetry||b)&&(A.fatal=!0)}this.hls.trigger(m.ERROR,A)}};this.append(S,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(s)),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn("Failed to remove ".concat(t,"-").concat(s,' from "').concat(e,'" SourceBuffer'),i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[ne.AUDIOVIDEO]?r.push("audiovideo"):(n[ne.AUDIO]&&r.push("audio"),n[ne.VIDEO]&&r.push("video"));const o=()=>{const d=self.performance.now();s.stats.buffering.end=d,i&&(i.stats.buffering.end=d);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(s.type," level: ").concat(s.level," sn: ").concat(s.sn)),this.blockBuffers(o,r).catch(d=>{this.warn("Fragment buffered callback ".concat(d)),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,s;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((s=this.tracks[e])==null?void 0:s.ending))})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log("".concat(n," buffer reached EOS"))))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})&&(i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(n.readyState));return}this.log("Calling mediaSource.endOfStream()"),n.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen(()=>this.updateMediaSource(e))}onError(e,t){if(t.details===_.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;G(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(G(o)&&o>=0){const d=Math.max(o,n),l=Math.floor(r/n)*n-d;this.flushBackBuffer(r,n,l)}if(G(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){const d=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),l=Math.max(d,n),h=Math.floor(r/n)*n+l;this.flushFrontBuffer(r,n,h)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=z.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const d=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(d!=null&&d.ended){this.log("Cannot flush ".concat(i," back buffer while SourceBuffer is in ended state"));return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=z.getBuffered(r),o=n.length;if(o<2)return;const d=n.start(o-1),l=n.end(o-1);if(s>d||e>=d&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:d,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return G(r)?{duration:r}:null;const n=this.media.duration,o=G(s.duration)?s.duration:0;return i>o&&i>n||!G(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(G(e)&&this.log("Updating MediaSource duration to ".concat(e.toFixed(3))),i.duration=e),t!==void 0&&s!==void 0&&(this.log("MediaSource duration is set to ".concat(i.duration,". Setting seekable range to ").concat(t,"-").concat(s,".")),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(ae(s))),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const d=this.getTrackCodec(o,n),l="".concat(o.container,";codecs=").concat(d);o.codec=d,this.log("creating sourceBuffer(".concat(l,")").concat(this.currentOp(n)?" Queued":""," ").concat(ae(o)));try{const h=s.addSourceBuffer(l),c=Fs(n),u=[n,h];t[c]=u,o.buffer=h}catch(h){var i;this.error("error while trying to add sourceBuffer: ".concat(h.message)),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&js(s,"video")&&(i=co(i,s));const r=Zt(i,e.levelCodec);return r?t.slice(0,5)==="audio"?cs(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat((s=this.mediaSource)==null?void 0:s.readyState));this.error("".concat(i),t),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n==null?void 0:n.buffer;if(!i||!r||!o){this.warn("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist")),this.shiftAndExecuteNext(e);return}const d=G(i.duration)?i.duration:1/0,l=G(r.duration)?r.duration:1/0,h=Math.max(0,t),c=Math.min(s,d,l);c>h&&(!n.ending||n.ended)?(n.ended=!1,this.log("Removing [".concat(h,",").concat(c,"] from the ").concat(e," SourceBuffer")),o.remove(h,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s==null?void 0:s.buffer;if(!i)throw new ud("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn("SourceBuffer blocked callback ".concat(t)),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn("Callback run without blocking ".concat(this.operationQueue," ").concat(t))}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function _r(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function gd(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function Fs(a){return a==="audio"?1:0}class bi{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&G(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(s,": ").concat(e[s].height,"p@").concat(e[s].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,bi.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(t){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,d)=>d?o.width!==d.width||o.height!==d.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const d=e[o];if((d.width>=n||d.height>=n)&&i(d,e[o+1])){r=o;break}}return r}}const md={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ye=md,pd={HLS:"h"},yd=pd,vd="CMCD-Object",Ed="CMCD-Request",Td="CMCD-Session",Sd="CMCD-Status",At={OBJECT:vd,REQUEST:Ed,SESSION:Td,STATUS:Sd},xd={[At.OBJECT]:["br","d","ot","tb"],[At.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[At.SESSION]:["cid","pr","sf","sid","st","v"],[At.STATUS]:["bs","rtp"]};class pt{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof pt?s:new pt(s))),this.value=e,this.params=t}}const Ad="Dict";function Ld(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function bd(a,e,t,s){return new Error("failed to ".concat(a,' "').concat(Ld(e),'" as ').concat(t),{cause:s})}function $e(a,e,t){return bd("serialize",a,e,t)}class ea{constructor(e){this.description=e}}const kr="Bare Item",Id="Boolean";function Rd(a){if(typeof a!="boolean")throw $e(a,Id);return a?"?1":"?0"}function Dd(a){return btoa(String.fromCharCode(...a))}const _d="Byte Sequence";function kd(a){if(ArrayBuffer.isView(a)===!1)throw $e(a,_d);return":".concat(Dd(a),":")}const Cd="Integer";function Pd(a){return a<-999999999999999||999999999999999<a}function ta(a){if(Pd(a))throw $e(a,Cd);return a.toString()}function wd(a){return"@".concat(ta(a.getTime()/1e3))}function sa(a,e){if(a<0)return-sa(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const Od="Decimal";function Fd(a){const e=sa(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw $e(a,Od);const t=e.toString();return t.includes(".")?t:"".concat(t,".0")}const Md="String",Nd=/[\x00-\x1f\x7f]+/;function $d(a){if(Nd.test(a))throw $e(a,Md);return'"'.concat(a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}function Bd(a){return a.description||a.toString().slice(7,-1)}const Ud="Token";function Cr(a){const e=Bd(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw $e(e,Ud);return e}function si(a){switch(typeof a){case"number":if(!G(a))throw $e(a,kr);return Number.isInteger(a)?ta(a):Fd(a);case"string":return $d(a);case"symbol":return Cr(a);case"boolean":return Rd(a);case"object":if(a instanceof Date)return wd(a);if(a instanceof Uint8Array)return kd(a);if(a instanceof ea)return Cr(a);default:throw $e(a,kr)}}const Gd="Key";function ii(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw $e(a,Gd);return a}function Ii(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?";".concat(ii(e)):";".concat(ii(e),"=").concat(si(t))).join("")}function ia(a){return a instanceof pt?"".concat(si(a.value)).concat(Ii(a.params)):si(a)}function Vd(a){return"(".concat(a.value.map(ia).join(" "),")").concat(Ii(a.params))}function Kd(a,e={whitespace:!0}){if(typeof a!="object")throw $e(a,Ad);const t=a instanceof Map?a.entries():Object.entries(a),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof pt||(r=new pt(r));let n=ii(i);return r.value===!0?n+=Ii(r.params):(n+="=",Array.isArray(r.value)?n+=Vd(r):n+=ia(r)),n}).join(",".concat(s))}function Hd(a,e){return Kd(a,e)}function Wd(a){return a==="ot"||a==="sf"||a==="st"}function Yd(a){return typeof a=="number"?G(a):a!=null&&a!==""&&a!==!1}function jd(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")}const is=a=>Math.round(a),qd=(a,e)=>(e!=null&&e.baseUrl&&(a=jd(a,e.baseUrl)),encodeURIComponent(a)),jt=a=>is(a/100)*100,zd={br:is,d:is,bl:jt,dl:jt,mtp:jt,nor:qd,rtp:jt,tb:is};function Xd(a,e){const t={};if(a==null||typeof a!="object")return t;const s=Object.keys(a).sort(),i=re({},zd,e==null?void 0:e.formatters),r=e==null?void 0:e.filter;return s.forEach(n=>{if(r!=null&&r(n))return;let o=a[n];const d=i[n];d&&(o=d(o,e)),!(n==="v"&&o===1)&&(n=="pr"&&o===1||Yd(o)&&(Wd(n)&&typeof o=="string"&&(o=new ea(o)),t[n]=o))}),t}function ra(a,e={}){return a?Hd(Xd(a,e),re({whitespace:!1},e)):""}function Qd(a,e={}){const t={};if(!a)return t;const s=Object.entries(a),i=Object.entries(xd).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),r=s.reduce((n,o)=>{var d,l;const[h,c]=o,u=((d=i.find(g=>g[1].includes(h)))===null||d===void 0?void 0:d[0])||At.REQUEST;return(l=n[u])!==null&&l!==void 0||(n[u]={}),n[u][h]=c,n},{});return Object.entries(r).reduce((n,[o,d])=>(n[o]=ra(d,e),n),t)}function Zd(a,e,t){return re(a,Qd(e,t))}const Jd="CMCD";function ec(a,e={}){if(!a)return"";const t=ra(a,e);return"".concat(Jd,"=").concat(encodeURIComponent(t))}const Pr=/CMCD=[^&#]+/;function tc(a,e,t){const s=ec(e,t);if(!s)return a;if(Pr.test(a))return a.replace(Pr,s);const i=a.includes("?")?"&":"?";return"".concat(a).concat(i).concat(s)}class sc{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:ye.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],d=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:d};(d===ye.VIDEO||d===ye.AUDIO||d==ye.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(d)/1e3,l.bl=this.getBufferLength(d));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:yd.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){re(t,this.createData());const s=t.ot===ye.INIT||t.ot===ye.VIDEO||t.ot===ye.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Zd(e.headers,t,r)):e.url=tc(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t,s;const{index:i,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(s=t.details)==null?void 0:s.partList;if(n){const{sn:o}=r;for(let d=n.length-1;d>=0;d--){const l=n[d];if(l.index===i&&l.fragment.sn===o)return n[d+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ye.TIMED_TEXT;if(e.sn==="initSegment")return ye.INIT;if(t==="audio")return ye.AUDIO;if(t==="main")return this.hls.audioTracks.length?ye.VIDEO:ye.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===ye.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===ye.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:z.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const ic=3e5;class rc extends Ke{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===pe.SendAlternateToPenaltyBox&&s.flags===ke.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:d,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):d&&(n=d)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),s.resolved||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(n," levels: ").concat(i&&i.length," priorities: ").concat(ae(r)," penalized: ").concat(ae(this.penalizedPathways)))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(s,'"')),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>ic&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,d=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log('Setting Pathway to "'.concat(n,'"')),this.pathwayId=n,_n(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];d&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==d.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==d.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(d.bitrate," to ").concat(l.bitrate)),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===Z.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===Z.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":d}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const c=new oe(h.attrs);c["PATHWAY-ID"]=n;const u=c.AUDIO&&"".concat(c.AUDIO,"_clone_").concat(n),g=c.SUBTITLES&&"".concat(c.SUBTITLES,"_clone_").concat(n);u&&(s[c.AUDIO]=u,c.AUDIO=u),g&&(i[c.SUBTITLES]=g,c.SUBTITLES=g);const f=na(h.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",d),p=new Dt({attrs:c,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio","".concat(h.audioGroups[y],"_clone_").concat(n));if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text","".concat(h.subtitleGroups[y],"_clone_").concat(n));return p});t.push(...l),wr(this.audioTracks,s,d,n),wr(this.subtitleTracks,i,d,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch(h){this.enabled=!1,this.log("Failed to parse Steering Manifest URI: ".concat(e));return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},d={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,c,u,g)=>{this.log('Loaded steering manifest: "'.concat(i,'"'));const f=h.data;if((f==null?void 0:f.VERSION)!==1){this.log("Steering VERSION ".concat(f.VERSION," not supported!"));return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=f;if(p)try{this.uri=new self.URL(p,i).href}catch(T){this.enabled=!1,this.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(p));return}this.scheduleRefresh(this.uri||u.url),y&&this.clonePathways(y);const E={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(h,c,u,g)=>{if(this.log("Error loading steering manifest: ".concat(h.code," ").concat(h.text," (").concat(c.url,")")),this.stopLoad(),h.code===410){this.enabled=!1,this.log("Steering manifest ".concat(c.url," no longer available"));return}let f=this.timeToLoad*1e3;if(h.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const y=p.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log("Steering manifest ".concat(c.url," rate limited"));return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(h,c,u)=>{this.log("Timeout loading steering manifest (".concat(c.url,")")),this.scheduleRefresh(this.uri||c.url)}};this.log("Requesting steering manifest: ".concat(i)),this.loader.load(r,d,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function wr(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=re({},n);return o.details=void 0,o.attrs=new oe(o.attrs),o.url=o.attrs.URI=na(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function na(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n==null?void 0:n[e],o&&(a=o));const d=new self.URL(a);return i&&!o&&(d.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&d.searchParams.set(l,r[l])}),d.href}function Te(a,e,t){Ie(a,e,t),a.addEventListener(e,t)}function Ie(a,e,t){a.removeEventListener(e,t)}class ut extends Ke{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=ut.CDMCleanupPromise?[ut.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r='"'.concat(t.type,'" event: init data type: "').concat(s,'"');if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=xt(this.config));const o=n.map(Vt).filter(d=>!!d);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=es(n);let d,l;if(s==="sinf"){if(o!==ie.FAIRPLAY){this.warn('Ignoring unexpected "'.concat(t.type,'" event with init data type: "').concat(s,'" for selected key-system ').concat(o));return}const f=ce(new Uint8Array(i));try{const p=mi(JSON.parse(f).sinf),y=an(p);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");d=new Uint8Array(y.subarray(8,24)),l=ie.FAIRPLAY}catch(p){this.warn("".concat(r," Failed to parse sinf: ").concat(p));return}}else{if(o!==ie.WIDEVINE&&o!==ie.PLAYREADY){this.warn('Ignoring unexpected "'.concat(t.type,'" event with init data type: "').concat(s,'" for selected key-system ').concat(o));return}const f=no(i),p=f.filter(v=>!!v.systemId&&Rs(v.systemId)===o);p.length>1&&this.warn("".concat(r," Using first of ").concat(p.length," pssh found for selected key-system ").concat(o));const y=p[0];if(!y){f.length===0||f.some(v=>!v.systemId)?this.warn("".concat(r," contains incomplete or invalid pssh data")):this.log("ignoring ".concat(r," for ").concat(f.map(v=>Rs(v.systemId)).join(",")," pssh data in favor of playlist keys"));return}if(l=Rs(y.systemId),y.version===0&&y.data)if(l===ie.WIDEVINE){const v=y.data.length-22;d=new Uint8Array(y.data.subarray(v,v+16))}else l===ie.PLAYREADY&&(d=xn(y.data))}if(!l||!d)return;const h=Oe.hexDump(d),{keyIdToKeySessionPromise:c,mediaKeySessions:u}=this;let g=c[h];for(let f=0;f<u.length;f++){const p=u[f],y=p.decryptdata;if(!y.keyId)continue;const v=Oe.hexDump(y.keyId);if(h===v||y.uri.replace(/-/g,"").indexOf(h)!==-1){if(g=c[v],y.pssh)break;delete c[v],y.pssh=new Uint8Array(i),y.keyId=d,g=c[h]=g.then(()=>this.generateRequestWithPreferredKeySession(p,s,i,"encrypted-event-key-match")),g.catch(E=>this.handleError(E));break}}if(!g){if(l!==o){this.log('Ignoring "'.concat(t.type,'" event with ').concat(l," init data for selected key-system ").concat(o));return}g=c[h]=this.getKeySystemSelectionPromise([l]).then(({keySystem:f,mediaKeys:p})=>{var y;this.throwIfDestroyed();const v=new kt("ISO-23001-7",h,(y=Vt(f))!=null?y:"");return v.pssh=new Uint8Array(i),v.keyId=d,this.attemptSetMediaKeys(f,p).then(()=>{this.throwIfDestroyed();const E=this.createMediaKeySessionContext({decryptdata:v,keySystem:f,mediaKeys:p});return this.generateRequestWithPreferredKeySession(E,s,i,"encrypted-event-no-match")})}),g.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=t=>{this.log('"'.concat(t.type,'" event'))},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t[e];if(i)return i.licenseUrl;if(e===ie.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error('no license server URL configured for key-system "'.concat(e,'"'));return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t[e];if(s)return s.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]'))}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,d)=>!!n&&d.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const d=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(c=>n({keySystem:h,mediaKeys:c})).catch(c=>{l.length?d(l):c instanceof Le?o(c):o(new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};d(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i="Configured requestMediaKeySystemAccess is not a function ".concat(s);return Sn===null&&self.location.protocol==="http:"&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){const i=Xo(e,t,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let n=r==null?void 0:r.keySystemAccess;if(!n){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(ae(i))),n=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(d=>{this.log('Failed to obtain access to key-system "'.concat(e,'": ').concat(d))}),n.then(d=>{this.log('Access for key-system "'.concat(d.keySystem,'" obtained'));const l=this.fetchServerCertificate(e);return this.log('Create media-keys for "'.concat(e,'"')),o.mediaKeys=d.createMediaKeys().then(h=>(this.log('Media-keys created for "'.concat(e,'"')),o.hasMediaKeys=!0,l.then(c=>c?this.setMediaKeysServerCertificate(h,e,c):h))),o.mediaKeys.catch(h=>{this.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(h))}),o.mediaKeys})}return n.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log('Creating key-system session "'.concat(t,'" keyId: ').concat(Oe.hexDump(e.keyId||[])));const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Oe.hexDump(e.keyId)}updateKeySession(e,t){var s;const i=e.mediaKeysSession;return this.log('Updating key-session "'.concat(i.sessionId,'" for keyID ').concat(Oe.hexDump(((s=e.decryptdata)==null?void 0:s.keyId)||[]),"\n } (data length: ").concat(t&&t.byteLength,")")),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Vt(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=Vt(i);r?t(r):s(new Error('Unable to find format for key-system "'.concat(i,'"')))}).catch(s))}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(e.sn," ").concat(e.type,": ").concat(e.level,") key formats ").concat(t.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=xt(this.config),s=e.map(es).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),i="(keyId: ".concat(s,' format: "').concat(t.keyFormat,'" method: ').concat(t.method," uri: ").concat(t.uri,")");this.log("Starting session for key ".concat(i));let r=this.keyIdToKeySessionPromise[s];return r||(r=this.getKeySystemForKeyPromise(t).then(({keySystem:o,mediaKeys:d})=>(this.throwIfDestroyed(),this.log("Handle encrypted media sn: ".concat(e.frag.sn," ").concat(e.frag.type,": ").concat(e.frag.level," using key ").concat(i)),this.attemptSetMediaKeys(o,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:o,mediaKeys:d,decryptdata:t}))))),(this.keyIdToKeySessionPromise[s]=r.then(o=>{const d="cenc",l=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(o,d,l,"playlist-key")})).catch(o=>this.handleError(o))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Le?this.hls.trigger(m.ERROR,e.data):this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=es(e.keyFormat),r=i?[i]:xt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=xt(this.config)),e.length===0)throw new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(ae({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));const i=Promise.all(s).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log('Media-keys set for "'.concat(e,'"')),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r,n;const o=(r=this.config.drmSystems)==null||(n=r[e.keySystem])==null?void 0:n.generateRequest;if(o)try{const f=o.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){var d;if(this.warn(f.message),(d=this.hls)!=null&&d.config.debug)throw f}if(s===null)return this.log('Skipping key-session request for "'.concat(i,'" (no initData)')),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log('Generating key-session request for "'.concat(i,'": ').concat(l," (init data type: ").concat(t," length: ").concat(s?s.byteLength:null,")"));const h=new yi,c=e._onmessage=f=>{const p=e.mediaKeysSession;if(!p){h.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=f;this.log('"'.concat(y,'" message event for session "').concat(p.sessionId,'" message size: ').concat(v.byteLength)),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(E=>{h.eventNames().length?h.emit("error",E):this.handleError(E)}):y==="license-release"?e.keySystem===ie.FAIRPLAY&&(this.updateKeySession(e,Xs("acknowledged")),this.removeSession(e)):this.warn('unhandled media key message type "'.concat(y,'"'))},u=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){h.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const y=e.keyStatus;h.emit("keyStatus",y),y==="expired"&&(this.warn("".concat(e.keySystem," expired for key ").concat(l)),this.renewKeySession(e))};Te(e.mediaKeysSession,"message",c),Te(e.mediaKeysSession,"keystatuseschange",u);const g=new Promise((f,p)=>{h.on("error",p),h.on("keyStatus",y=>{y.startsWith("usable")?f():y==="output-restricted"?p(new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?p(new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},'key status changed to "'.concat(y,'"'))):y==="expired"?p(new Error("key expired while generating request")):this.warn('unhandled key status change "'.concat(y,'"'))})});return e.mediaKeysSession.generateRequest(t,s).then(()=>{var f;this.log('Request generated for key-session "'.concat((f=e.mediaKeysSession)==null?void 0:f.sessionId,'" keyId: ').concat(l))}).catch(f=>{throw new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},"Error generating key-session request: ".concat(f))}).then(()=>g).catch(f=>{throw h.removeAllListeners(),this.removeSession(e),f}).then(()=>(h.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,s)=>{if(typeof s=="string"&&typeof t=="object"){const i=s;s=t,t=i}this.log('key status change "'.concat(t,'" for keyStatuses keyId: ').concat(Oe.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))," session keyId: ").concat(Oe.hexDump(new Uint8Array(e.decryptdata.keyId||[]))," uri: ").concat(e.decryptdata.uri)),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise((n,o)=>{const d={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,g,f,p)=>{n(u.data)},onError:(u,g,f,p)=>{o(new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:se({url:d.url,data:void 0},u)},'"'.concat(e,'" certificate request failed (').concat(r,"). Status: ").concat(u.code," (").concat(u.text,")")))},onTimeout:(u,g,f)=>{o(new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:d.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(r,")")))},onAbort:(u,g,f)=>{o(new Error("aborted"))}};i.load(d,h,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log("setServerCertificate ".concat(n?"success":"not supported by CDM"," (").concat(s==null?void 0:s.byteLength,') on "').concat(t,'"')),i(e)}).catch(n=>{r(new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let c=0,u=r.length;c<u;c++){var n,o;h=r[c];const g=(n=h.querySelector("name"))==null?void 0:n.textContent,f=(o=h.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const d=i.querySelector("Challenge"),l=d==null?void 0:d.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Xs(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log("Sending license request to URL: ".concat(n));const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let d=o.response;this.log("License received ".concat(d instanceof ArrayBuffer?d.byteLength:d));const l=this.config.licenseResponseCallback;if(l)try{d=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(d)}else{const d=s.errorRetry,l=d?d.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Le({type:H.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed (".concat(n,"). Status: ").concat(o.status," (").concat(o.statusText,")")));else{const h=l-this._requestLicenseFailureCount+1;this.warn("Retrying license request, ".concat(h," attempts left")),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:d,licenseChallenge:l})=>{e.keySystem==ie.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(d,l)),d.send(l)})})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Te(s,"encrypted",this.onMediaEncrypted),Te(s,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(Ie(e,"encrypted",this.onMediaEncrypted),Ie(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const t=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,kt.clearKeyUriToKeyIdMap();const i=s.length;ut.CDMCleanupPromise=Promise.all(s.map(r=>this.removeSession(r)).concat(t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(r=>{var n;this.log("Could not clear media keys: ".concat(r)),(n=this.hls)==null||n.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: ".concat(r))})}))).catch(r=>{var n;this.log("Could not close sessions and clear media keys: ".concat(r)),(n=this.hls)==null||n.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(r))})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log("Selecting key-system from session-keys ".concat(s.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s}=e;if(t){this.log("Remove licenses and keys and close session ".concat(t.sessionId)),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{drmSystemOptions:r}=this.config;return(Zo(r)?new Promise((o,d)=>{self.setTimeout(()=>d(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o)}):Promise.resolve()).catch(o=>{var d;this.log("Could not remove session: ".concat(o)),(d=this.hls)==null||d.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(o))})}).then(()=>t.close()).catch(o=>{var d;this.log("Could not close session: ".concat(o)),(d=this.hls)==null||d.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(o))})})}}}ut.CDMCleanupPromise=void 0;class Le extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}class nc{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,d=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),d>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function aa(a,e){let t;try{t=new Event("addtrack")}catch(s){t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function oa(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error("addCue is failed for: ".concat(e))}catch(s){te.debug("[texttrack-utils]: ".concat(s));try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){te.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(i))}}t==="disabled"&&(a.mode=t)}function ct(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function ri(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=oc(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function ac(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function oc(a,e,t){const s=[],i=ac(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function rs(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class lc extends Li{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=rs(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;rs(s.textTracks).forEach(n=>{ct(n)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn("Subtitle track with id:".concat(s," and group:").concat(i," not found in active group ").concat(n==null?void 0:n.groupId));return}const o=n.details;n.details=t.details,this.log("Subtitle track ".concat(s,' "').concat(n.name,'" lang:').concat(n.lang," group:").concat(i," loaded [").concat(r.startSN,"-").concat(r.endSN,"]")),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(n=>(i==null?void 0:i.indexOf(n))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,c)=>{h.id=c});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Me(o,n);if(h>-1)r=n[h];else{const c=Me(o,this.tracks);r=this.tracks[c]}}let d=this.findTrackId(r);d===-1&&r&&(d=this.findTrackId(null));const l={subtitleTracks:n};this.log("Updating subtitle tracks, ".concat(n.length,' track(s) found in "').concat(s==null?void 0:s.join(","),'" group-id')),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),d!==-1&&this.trackId===-1&&this.setSubtitleTrack(d)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||tt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Ot(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Ot(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(ti(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Z.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&tt(e,s))return s;const i=Me(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Me(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n==null?void 0:n.age;this.log("Loading subtitle ".concat(s,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(i).concat((t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:"").concat(o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""," ").concat(r)),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=rs(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>ti(s,r))[0],i||this.warn('Unable to find subtitle TextTrack with name "'.concat(s.name,'" and language "').concat(s.lang,'"'))),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!G(e)){this.warn("Invalid subtitle track id: ".concat(e));return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log("Switching to subtitle-track ".concat(e)+(i?' "'.concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId):""));const{id:n,groupId:o="",name:d,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:d,type:l,url:h});const c=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(c)}}function dc(){try{return crypto.randomUUID()}catch(a){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function It(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const ft=.025;let vs=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function cc(a,e,t){return"".concat(a.identifier,"-").concat(t+1,"-").concat(It(e))}class hc{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Ms(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=Ms(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=G(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Ms(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<ft))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?vs.Range:vs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return uc(this)}}function Ms(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<ft)?e.start:e.start+e.duration}function la(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Ns(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function uc(a){return'["'.concat(a.identifier,'" ').concat(a.cue.pre?"<pre>":a.cue.post?"<post>":"").concat(a.timelineStart.toFixed(2),"-").concat(a.resumeTime.toFixed(2),"]")}function dt(a){const e=a.timelineStart,t=a.duration||0;return'["'.concat(a.identifier,'" ').concat(e.toFixed(2),"-").concat((e+t).toFixed(2),"]")}class fc{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;let n=i.uri;try{n=la(n,t.primarySessionId).href}catch(d){}r.loadSource(n);const o=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,o),r.once(m.AUDIO_TRACK_LOADED,o),r.once(m.SUBTITLE_TRACK_LOADED,o),r.on(m.MEDIA_ATTACHING,(d,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,r.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){var e;return((e=this.interstitial)==null?void 0:e.appendInPlace)||!1}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const s=this.timelineOffset,i=z.bufferInfo(e,s,0);return this.getAssetTime(i.end)>=this._bufferedEosTime-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=z.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;return e||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}resetDetails(){const e=this.hls;if(this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){this.hls.on(e,t)}once(e,t,s){this.hls.once(e,t)}off(e,t,s){this.hls.off(e,t)}toString(){var e;return"HlsAssetPlayer: ".concat(dt(this.assetItem)," ").concat((e=this.hls)==null?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}const Or=.033;class gc extends Ke{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&t<o+(n.duration||0))return r}}return 0}get assetIdAtEnd(){var e,t;const s=(e=this.items)==null||(t=e[this.length-1])==null?void 0:t.event;if(s){const i=s.assetList,r=i[i.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),d=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const c=l.cue.pre,u=l.cue.post,g=h.cue.pre,f=h.cue.post;if(c&&!g)return-1;if(g&&!c||u&&!f)return 1;if(f&&!u)return-1;if(!c&&!g&&!u&&!f){const p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,d.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,d)}updateSchedule(e,t=[]){const s=this.events||[];if(s.length||t.length||this.length<2){const i=this.items,r=this.parseSchedule(s,e);(t.length||(i==null?void 0:i.length)!==r.length||r.some((o,d)=>Math.abs(o.playout.start-i[d].playout.start)>.005||Math.abs(o.playout.end-i[d].playout.end)>.005))&&(this.items=r,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],d=e[o];if(d.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(d):(l=new hc(d,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(d=>!d.error&&!(d.cue.once&&d.hasPlayed)),e.length){this.resolveOffsets(e,t);let d=0,l=0;if(e.forEach((h,c)=>{const u=h.cue.pre,g=h.cue.post,f=e[c-1]||null,p=h.appendInPlace,y=g?r:h.startOffset,v=h.duration,E=h.timelineOccupancy===vs.Range?v:0,T=h.resumptionOffset,S=(f==null?void 0:f.startTime)===y,x=y+h.cumulativeDuration;let I=p?x+v:y+T;if(u||!g&&y<=0){const b=l;l+=E,h.timelineStart=x;const k=n;n+=v,s.push({event:h,start:x,end:I,playout:{start:k,end:n},integrated:{start:b,end:l}})}else if(y<=r){if(!S){const L=y-d;if(L>Or){const F=d,U=l;l+=L;const B=n;n+=L;const N={previousEvent:e[c-1]||null,nextEvent:h,start:F,end:F+L,playout:{start:B,end:n},integrated:{start:U,end:l}};s.push(N)}else L>0&&f&&(f.cumulativeDuration+=L,s[s.length-1].end=y)}g&&(I=x),h.timelineStart=x;const b=l;l+=E;const k=n;n+=v,s.push({event:h,start:x,end:I,playout:{start:k,end:n},integrated:{start:b,end:l}})}else return;const A=h.resumeTime;g||A>r?d=r:d=A}),d<r){var o;const h=d,c=l,u=r-d;l+=u;const g=n;n+=u,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:d,end:h+u,playout:{start:g,end:n},integrated:{start:c,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,d)=>{const l=o.cue.pre,h=o.cue.post,c=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===c?o.cumulativeDuration=r:(r=0,n=c),!h&&o.snapOptions.in&&(o.resumeAnchor=st(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&d+1<e.length&&e[d+1].startTime-e[d].resumeTime<Or&&(e[d+1].appendInPlace=!1,e[d+1].appendInPlace&&this.warn("Could not change append strategy for abutting event ".concat(o)));const g=G(o.resumeOffset)?o.resumeOffset:o.duration;r+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>ft?(this.log('"'.concat(e.identifier,'" resumption ').concat(s," not aligned with estimated timeline end ").concat(i)),!1):t?!Object.keys(t).some(n=>{const o=t[n].details,d=o.edge;if(s>=d)return this.log('"'.concat(e.identifier,'" resumption ').concat(s," past ").concat(n," playlist end ").concat(d)),!1;const l=st(null,o.fragments,s);if(!l)return this.log('"'.concat(e.identifier,'" resumption ').concat(s," does not align with any fragments in ").concat(n," playlist (").concat(o.fragStart,"-").concat(o.fragmentEnd,")")),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<ft+h||Math.abs(l.end-s)<ft+h?!1:(this.log('"'.concat(e.identifier,'" resumption ').concat(s," not aligned with ").concat(n," fragment bounds (").concat(l.start,"-").concat(l.end," sn: ").concat(l.sn," cc: ").concat(l.cc,")")),!0)}):(this.log('"'.concat(e.identifier,'" resumption ').concat(s," can not be aligned with media (none selected)")),!1)}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;e.assetList.forEach((n,o)=>{const d=t+s;n.startOffset=s,n.timelineStart=d,i||(i=n.duration===null),r||(r=!!n.error);const l=n.error?0:n.duration||0;s+=l}),i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function We(a){return"[".concat(a.event?'"'+a.event.identifier+'"':"primary",": ").concat(a.start.toFixed(2),"-").concat(a.end.toFixed(2),"]")}class mc{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=la(s,this.hls.sessionId,e.baseUrl)}catch(u){const g=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,u,s);this.hls.trigger(m.ERROR,g);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),d={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,g,f,p)=>{const y=u.data,v=y==null?void 0:y.ASSETS;if(!Array.isArray(v)){const E=this.assignAssetListError(e,_.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(m.ERROR,E);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(u,g,f,p)=>{const y=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(u.code," ").concat(u.text," (").concat(g.url,")")),g.url,p,f);this.hls.trigger(m.ERROR,y)},onTimeout:(u,g,f)=>{const p=this.assignAssetListError(e,_.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(g.url,")")),g.url,u,f);this.hls.trigger(m.ERROR,p)}};return o.load(d,h,c),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:H.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Fr(a){a==null||a.play().catch(()=>{})}class pc extends Ke{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(),this.checkBuffer(),n&&s<o.start||s>=o.end){var d;const u=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(o)&&(d=this.media)!=null&&d.paused&&(this.shouldPlay=!1),!n){const g=this.findItemIndex(o);if(u>g){const f=this.schedule.findJumpRestrictedIndex(g+1,u);if(f>g){this.setSchedulePosition(f);return}}}this.setSchedulePosition(u);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const u=o.event.assetList[0];u&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,u))}return}const h=l.timelineStart,c=l.duration||0;(n&&s<h||s>=h+c)&&this.setScheduleToAssetAtTime(s,l)},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule,n=this.playingItem,o=r.events||[],d=r.items||[],l=r.durations,h=s.map(f=>f.identifier),c=!!(o.length||h.length);(c||i)&&this.log("INTERSTITIALS_UPDATED (".concat(o.length,"): ").concat(o,"\nSchedule: ").concat(d.map(f=>We(f))," pos: ").concat(this.timelinePos)),h.length&&this.log("Removed events ".concat(h)),this.playerQueue.forEach(f=>{if(f.interstitial.appendInPlace){const p=f.assetItem.timelineStart,y=f.timelineOffset-p;if(y)try{f.timelineOffset=p}catch(v){Math.abs(y)>ft&&this.warn("".concat(v,' ("').concat(f.assetId,'" ').concat(f.timelineOffset,"->").concat(p,")"))}}});let u=null;if(n){const f=this.updateItem(n,this.timelinePos);this.itemsMatch(n,f)&&(this.playingItem=f,this.waitingItem=this.endedItem=null,u=()=>this.trimInPlace(f,n))}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g){const f=this.updateItem(g,this.bufferedPos);this.itemsMatch(g,f)?(this.bufferingItem=f,u||(u=()=>this.trimInPlace(f,g))):g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))}if(s.forEach(f=>{f.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),c||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:d.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),this.primaryFallback(n.event);return}u&&u(),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new mc(e),this.schedule=new gc(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ie(e,"play",this.onPlay),Ie(e,"pause",this.onPause),Ie(e,"seeking",this.onSeeking),Ie(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Te(s,"seeking",this.onSeeking),Te(s,"timeupdate",this.onTimeupdate),Te(s,"play",this.onPlay),Te(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=c=>c&&e.getAssetPlayer(c.identifier),i=(c,u,g,f,p)=>{if(c){let y=c[u].start;const v=c.event;if(v){if(u==="playout"||v.timelineOccupancy!==vs.Point){const E=s(g);(E==null?void 0:E.interstitial)===v&&(y+=E.assetItem.startOffset+E[p])}}else{const E=f==="bufferedPos"?n():e[f];y+=E-c.start}return y}return 0},r=(c,u)=>{if(c!==0&&u!=="primary"&&e.schedule.length){var g;const f=e.schedule.findItemIndexAtTime(c),p=(g=e.schedule.items)==null?void 0:g[f];if(p){const y=p[u].start-p.start;return c+y}}return c},n=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var u;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:e.schedule.durations[c]},d=(c,u)=>{var g,f;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip)return;e.log("seek to ".concat(c,' "').concat(u,'"'));const y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,u),E=(f=e.schedule.items)==null?void 0:f[v],T=e.getBufferingPlayer(),S=T==null?void 0:T.interstitial,x=S==null?void 0:S.appendInPlace,I=y&&e.itemsMatch(y,E);if(y&&(x||I)){const b=s(e.playingAsset),k=(b==null?void 0:b.media)||e.primaryMedia;if(k){const L=u==="primary"?k.currentTime:i(y,u,e.playingAsset,"timelinePos","currentTime"),F=c-L,U=(x?L:k.currentTime)+F;if(U>=0&&(!b||x||U<=b.duration)){k.currentTime=U;return}}}if(E){let b=c;if(u!=="primary"){const L=E[u].start,F=c-L;b=E.start+F}const k=!e.isInterstitial(E);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(k||E.event.appendInPlace)){const L=e.media||(x?T==null?void 0:T.media:null);L&&(L.currentTime=b)}else if(y){const L=e.findItemIndex(y);if(v>L){const U=e.schedule.findJumpRestrictedIndex(L+1,v);if(U>L){e.setSchedulePosition(U);return}}let F=0;if(k)e.timelinePos=b,e.checkBuffer();else{var A;const U=E==null||(A=E.event)==null?void 0:A.assetList;if(U){const B=c-(E[u]||E).start;for(let N=U.length;N--;){const $=U[N];if($.duration&&B>=$.startOffset&&B<$.startOffset+$.duration){F=N;break}}}}e.setSchedulePosition(v,F)}}},l=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const u=t();return e.isInterstitial(u)?u:null},h={get currentTime(){const c=l(),u=e.effectivePlayingItem;return u&&u===c?i(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(c){const u=l(),g=e.effectivePlayingItem;g&&g===u&&d(c+g.playout.start,"playout")},get duration(){const c=l();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const u=(c=l())==null?void 0:c.event.assetList;return u?u.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var c;const u=(c=l())==null?void 0:c.event;return u&&e.effectivePlayingAsset?u.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var c,u;return((c=e.schedule)==null||(u=c.events)==null?void 0:u.slice(0))||[]},get schedule(){var c,u;return((c=e.schedule)==null||(u=c.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return n()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){d(c,"primary")},get duration(){return o("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){d(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){var c;return r(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,u=c==null?void 0:c.event;if(u&&!u.restrictions.skip){const g=e.findItemIndex(c);if(u.appendInPlace){const f=c.playout.start+c.event.duration;d(f+.001,"playout")}else e.advanceAfterAssetEnded(u,g,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t,s;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(t=e.event)!=null&&t.appendInPlace&&(r=this.primaryMedia);const n=(s=r)==null?void 0:s.currentTime;if(!(n===void 0||!G(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(ae(r))),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,o=e!==n,d=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)d&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const g=this.getBufferingPlayer();g?(r=g.transferMedia(),h="".concat(g)):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log("using detachedData: MediaSource ".concat(ae(r)));else if(!this.detachedData||n.media===t){const g=this.playerQueue;g.length>1&&g.forEach(f=>{if(o&&f.interstitial.appendInPlace!==d){const p=f.interstitial;this.clearInterstitial(f.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn("Could not change append strategy for queued assets ".concat(p))}}),this.hls.detachMedia(),this.detachedData={media:t}}}const c=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",u=c&&r?r:t;if(this.log("".concat(c?"transfering MediaSource":"attaching media"," to ").concat(o?e:"Primary"," from ").concat(h)),u===r){const g=o&&e.assetId===this.schedule.assetIdAtEnd;u.overrides={duration:this.schedule.duration,endOfStream:!o||g,cueRemoval:!o}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.timelinePos=r,t.length&&t[0].cue.pre){const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAfterAssetEnded(e,t,s){const i=Ns(e,s);if(!e.isAssetPastPlayoutLimit(i))this.setSchedulePosition(t,i);else{const r=this.schedule.items;if(r){const n=t+1,o=r.length;if(n>=o){this.setSchedulePosition(-1);return}const d=e.resumeTime;this.timelinePos<d&&(this.timelinePos=d,this.checkBuffer()),this.setSchedulePosition(n)}}}setScheduleToAssetAtTime(e,t){const s=this.schedule,i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,o-1)}}setSchedulePosition(e,t){const s=this.schedule.items;if(!s||this.playbackDisabled)return;this.log("setSchedulePosition ".concat(e,", ").concat(t));const i=e>=0?s[e]:null,r=this.playingItem,n=this.playingLastItem;if(this.isInterstitial(r)){var o;const l=r.event,h=this.playingAsset,c=h==null?void 0:h.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(r,i)||t!==void 0&&c!==((o=l.assetList)==null?void 0:o[t].identifier))){var d;const g=l.findAssetIndex(h);this.log("INTERSTITIAL_ASSET_ENDED ".concat(g+1,"/").concat(l.assetList.length," ").concat(dt(h))),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:g,event:l,schedule:s.slice(0),scheduleIndex:e,player:u}),this.retreiveMediaSource(c,i),u.media&&!((d=this.detachedData)!=null&&d.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(r,i)&&(this.endedItem=r,this.playingItem=null,this.log("INTERSTITIAL_ENDED ".concat(l," ").concat(We(r))),l.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:l,schedule:s.slice(0),scheduleIndex:e}),l.cue.once)){this.updateSchedule();const g=this.schedule.items;if(i&&g){const f=this.schedule.findItemIndex(i);this.advanceSchedule(f,g,t,r,n)}return}}this.advanceSchedule(e,s,t,r,n)}advanceSchedule(e,t,s,i,r){const n=e>=0?t[e]:null,o=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(l=>{const h=l.interstitial,c=this.schedule.findEventIndex(h.identifier);(c<e||c>e+1)&&this.clearInterstitial(h,n)}),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);const l=n.event;if(s===void 0){s=this.schedule.findAssetIndex(l,this.timelinePos);const g=Ns(l,s-1);if(l.isAssetPastPlayoutLimit(g)){this.advanceAfterAssetEnded(l,e,s);return}s=g}const h=this.waitingItem;this.assetsBuffered(n,o)||this.setBufferingItem(n);let c=this.preloadAssets(l,s);if(this.eventItemsMatch(n,h||i)||(this.waitingItem=n,this.log("INTERSTITIAL_STARTED ".concat(We(n)," ").concat(l.appendInPlace?"append in place":"")),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:l,schedule:t.slice(0),scheduleIndex:e})),!l.assetListLoaded){this.log("Waiting for ASSET-LIST to complete loading ".concat(l));return}if(l.assetListLoader&&(l.assetListLoader.destroy(),l.assetListLoader=void 0),!o){this.log("Waiting for attachMedia to start Interstitial ".concat(l));return}this.waitingItem=this.endedItem=null,this.playingItem=n;const u=l.assetList[s];if(!u){const g=t[e+1],f=this.media;g&&f&&!this.isInterstitial(g)&&f.currentTime<g.start&&(f.currentTime=this.timelinePos=g.start),this.advanceAfterAssetEnded(l,e,s||0);return}if(c||(c=this.getAssetPlayer(u.identifier)),c===null||c.destroyed){const g=l.assetList.length;this.warn("asset ".concat(s+1,"/").concat(g," player destroyed ").concat(l)),c=this.createAssetPlayer(l,u,s)}if(!this.eventItemsMatch(n,this.bufferingItem)&&l.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(c,s,t,e,o),this.shouldPlay&&Fr(c.media)}else n!==null?(this.resumePrimary(n,e,i),this.shouldPlay&&Fr(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e,t;return(e=this.mediaSelection)==null||(t=e.main)==null?void 0:t.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming ".concat(We(e))),!((i=this.detachedData)!=null&&i.mediaSource)){let n=this.timelinePos;(n<e.start||n>=e.end)&&(n=this.getPrimaryResumption(e,t),this.timelinePos=n),this.attachPrimary(n,e)}if(!s)return;const r=this.schedule.items;r&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(We(e))),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:r.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:z.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1)return;const s=this.hls.levels[t.level],i=se(se({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=se(se({},this.altSelection),{},{audio:s});return}const r=se(se({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=se(se({},this.altSelection),{},{subtitles:s});return}const r=se(se({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=ji(t);this.playerQueue.forEach(i=>i.hls.setAudioOption(t)||i.hls.setAudioOption(s))}onSubtitleTrackSwitch(e,t){const s=ji(t);this.playerQueue.forEach(i=>i.hls.setSubtitleOption(t)||t.id!==-1&&i.hls.setSubtitleOption(s))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){const s=this.schedule.items;if(e&&s){const i=this.findItemIndex(e,t);return s[i]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=z.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.attachPrimary(s,null),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e?this.schedule.findItemIndex(e,t):-1}updateSchedule(){const e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])}checkBuffer(e){const t=this.schedule.items;if(!t)return;const s=z.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,t,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,o=this.findItemIndex(n);let d=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h;const c=this.findItemIndex(r),u=Math.min(c+1,t.length-1),g=t[u];if((d===-1&&r&&e>=r.end||(l=g.event)!=null&&l.appendInPlace&&e+.01>=g.start)&&(d=u),u-o>1&&(r==null||(h=r.event)==null?void 0:h.appendInPlace)===!1)return;if(this.bufferedPos=e,d>c&&d>o)this.bufferedToItem(g);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&g.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(g)&&this.preloadAssets(g.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(d===o?this.bufferedToItem(n):d===o+1&&this.bufferedToItem(t[d]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const d=o?o.remaining:t?t.end-this.timelinePos:0;this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(We(e))+(t?" (".concat(d.toFixed(2)," remaining)"):"")),this.playbackDisabled||(n?e.event.assetList.forEach(l=>{const h=this.getAssetPlayer(l.identifier);h&&h.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering()))),this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const o=s.assetList[t],d=this.primaryMedia;o&&d&&this.bufferAssetPlayer(n,d)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const d=e.timelineStart;if(e.appendInPlace){var o;const u=this.playingItem;!this.isInterstitial(u)&&(u==null||(o=u.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(d+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const u=h-d;u>0&&(l=Math.round(u*1e3)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(s?1:i," ").concat(e).concat(l?" live-start: ".concat(h," start-offset: ").concat(l):"")),s)return this.createAsset(e,0,0,d,e.duration,s);const c=this.assetListLoader.loadAssetList(e,l);c&&(e.assetListLoader=c)}else if(!n&&i){for(let d=t;d<i;d++){const l=e.assetList[d],h=this.getAssetPlayerQueueIndex(l.identifier);(h===-1||this.playerQueue[h].destroyed)&&!l.error&&this.createAssetPlayer(e,l,d)}return this.getAssetPlayer(e.assetList[t].identifier)}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log("Removing front buffer starting at ".concat(e)),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const o={parentIdentifier:e.identifier,identifier:cc(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(n||o)&&(n=re({},n),o.videoCodec&&(n.videoCodec=o.videoCodec),o.videoRange&&(n.allowedVideoRanges=[o.videoRange]));const d=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const S=t.duration;S&&T<S&&(h=T)}}const c=t.identifier,u=se(se({},r),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:d||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));const g=u.cmcd;g!=null&&g.sessionId&&g.contentId&&(u.cmcd=re({},g,{contentId:It(t.uri)})),this.getAssetPlayer(c)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(c));const f=new fc(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[s]=t;const p=T=>{if(T.live){const I=new Error("Interstitials MUST be VOD assets ".concat(e)),A={fatal:!0,type:H.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:I};this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,I.message);return}const S=T.edge-T.fragmentStart,x=t.duration;(x===null||S>x)&&(this.log('Interstitial asset "'.concat(c,'" duration change ').concat(x," > ").concat(S)),t.duration=S,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(T,{details:S})=>p(S)),f.on(m.LEVEL_PTS_UPDATED,(T,{details:S})=>p(S));const y=(T,S)=>{const x=this.getAssetPlayer(c);if(x&&S.tracks){x.off(m.BUFFER_CODECS,y),x.tracks=S.tracks;const I=this.primaryMedia;this.bufferingAsset===x.assetItem&&I&&!x.media&&this.bufferAssetPlayer(x,I)}};f.on(m.BUFFER_CODECS,y);const v=()=>{var T;const S=this.getAssetPlayer(c);if(this.log("buffered to end of asset ".concat(S)),!S)return;const x=this.schedule.findEventIndex(e.identifier),I=(T=this.schedule.items)==null?void 0:T[x];if(this.isInterstitial(I)){const b=e.findAssetIndex(t),k=Ns(e,b);if(!e.isAssetPastPlayoutLimit(k))this.bufferedToItem(I,k);else{var A;const L=(A=this.schedule.items)==null?void 0:A[x+1];L&&this.bufferedToItem(L)}}};f.on(m.BUFFERED_TO_END,v);const E=T=>()=>{if(!this.getAssetPlayer(c))return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,T)};return f.once(m.MEDIA_ENDED,E(s)),f.once(m.PLAYOUT_LIMIT_REACHED,E(1/0)),f.on(m.ERROR,(T,S)=>{const x=this.getAssetPlayer(c);if(S.details===_.BUFFER_STALLED_ERROR){if(x!=null&&x.media){const I=x.currentTime,A=x.duration-I;I&&e.appendInPlace&&A/x.media.playbackRate<.5?(this.log("Advancing buffer past end of asset ".concat(c," ").concat(e," at ").concat(x.media.currentTime)),v()):(this.warn("Stalled at ".concat(I," of ").concat(I+A," in asset ").concat(c," ").concat(e)),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),s,"Asset player error ".concat(S.error," ").concat(e))}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(c))return;const S=new Error("Asset player destroyed unexpectedly ".concat(c)),x={fatal:!0,type:H.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:S};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,S.message)}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(dt(t))),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log('reset asset player "'.concat(e,'" after error'));const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){this.log('clear asset player "'.concat(e,'" toSegment: ').concat(t&&We(t)));const i=this.playerQueue[s];this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:o,assetId:d}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==d)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(dt(o))),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;const{interstitial:r,assetItem:n}=e,o=this.schedule.findEventIndex(r.identifier),d=(s=this.schedule.items)==null?void 0:s[o];if(!d)return;this.setBufferingItem(d),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const c=(l==null?void 0:l.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks)return;if(c&&!Zr(c,e.tracks)){const u=new Error("Asset ".concat(dt(n)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(c),"')")),g={fatal:!0,type:H.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},f=r.findAssetIndex(n);this.handleAssetItemError(g,r,o,f,u.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,s,i,r){if(e.details===_.BUFFER_STALLED_ERROR)return;const n=t.assetList[i];this.warn("INTERSTITIAL_ASSET_ERROR ".concat(n&&dt(n)," ").concat(e.error));const o=n==null?void 0:n.identifier,d=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[d]||null,h=this.schedule.items,c=re({},e,{fatal:!1,errorAction:_t(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const u=this.playingAsset,g=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=g),!t.assetList.some(f=>!f.error))t.error=g;else if(t.appendInPlace){for(let f=i;f<t.assetList.length;f++)this.resetAssetPlayer(t.assetList[f].identifier);this.updateSchedule()}t.error?this.primaryFallback(t):u&&u.identifier===o&&this.advanceAfterAssetEnded(t,s,i)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(this.updateSchedule(),s){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(this.timelinePos," playing: ").concat(s?We(s):"<none>"," error: ").concat(e.error));let i=this.timelinePos;i===-1&&(i=this.hls.startPosition);const r=this.updateItem(s,i);this.itemsMatch(s,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));const n=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(n)}else this.checkStart()}onAssetListLoaded(e,t){var s;const i=t.event,r=i.identifier,n=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(r))return;const o=i.timelineStart,d=i.duration;let l=0;n.forEach((f,p)=>{const y=parseFloat(f.DURATION);this.createAsset(i,p,l,o+l,y,f.URI),l+=y}),i.duration=l,this.log("Loaded asset-list with duration: ".concat(l," (was: ").concat(d,") ").concat(i));const h=this.waitingItem,c=(h==null?void 0:h.event.identifier)===r;this.updateSchedule();const u=(s=this.bufferingItem)==null?void 0:s.event;if(c){var g;const f=this.schedule.findEventIndex(r),p=(g=this.schedule.items)==null?void 0:g[f];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==f){i.error=new Error("Interstitial no longer within playback range ".concat(this.timelinePos," ").concat(i)),this.primaryFallback(i);return}this.setBufferingItem(p)}this.setSchedulePosition(f)}else if((u==null?void 0:u.identifier)===r&&u.appendInPlace){const f=i.assetList[0],p=this.getAssetPlayer(f.identifier),y=this.primaryMedia;f&&p&&y&&this.bufferAssetPlayer(p,y)}}onError(e,t){switch(t.details){case _.ASSET_LIST_PARSING_ERROR:case _.ASSET_LIST_LOAD_ERROR:case _.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&this.primaryFallback(s);break}case _.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Mr=500;class yc extends pi{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",V.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=w.IDLE,this.setInterval(Mr),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(ge(s)&&(this.fragPrevious=s),this.state=w.IDLE,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){n=r[l];break}const d=s.start+s.duration;n?n.end=d:(n={start:o,end:d},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,V.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===V.SUBTITLE&&(t.details===_.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==w.STOPPED&&(this.state=w.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Zn(this.levels,t)){this.levels=t.map(s=>new Dt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Dt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,V.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==w.STOPPED&&this.setInterval(Mr)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn("Subtitle tracks were reset while loading level ".concat(o));return}const d=r[o];if(o>=r.length||!d)return;this.log("Subtitle track ".concat(o," loaded [").concat(n.startSN,",").concat(n.endSN,"]").concat(n.lastPartSn?"[part-".concat(n.lastPartSn,"-").concat(n.lastPartIndex,"]"):"",",duration:").concat(n.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(s=d.details)!=null&&s.live){const c=this.mainDetails;if(n.deltaUpdateFailed||!c)return;const u=c.fragments[0];if(!d.details)n.hasProgramDateTime&&c.hasProgramDateTime?(ps(n,c),l=n.fragmentStart):u&&(l=u.start,Zs(n,l));else{var h;l=this.alignPlaylists(n,d.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&u&&(l=u.start,Zs(n,l))}}d.details=n,this.levelLastLoaded=d,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===w.IDLE&&(st(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),d.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&ht(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,gi(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const d=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:d}})}).catch(o=>{this.warn("".concat(o.name,": ").concat(o.message)),this.state=w.IDLE})}}doTick(){if(!this.media){this.state=w.IDLE;return}if(this.state===w.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=z.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:d}=n,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(d>h)return;const c=l.fragments,u=c.length,g=l.edge;let f=null;const p=this.fragPrevious;if(o<g){const E=i.maxFragLookUpTolerance,T=o>g-E?0:E;f=st(p,c,Math.max(c[0].start,o),T),!f&&p&&p.start<c[0].start&&(f=c[0])}else f=c[u-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;const y=f.sn-l.startSN,v=c[y-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===he.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===he.NOT_LOADED){const E=this.mapToInitFragWhenRequired(f);E&&this.loadFragment(E,s,o)}}}loadFragment(e,t,s){ge(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new vc(this.tracksBuffered[this.currentTrackId]||[])}}class vc{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException("Failed to execute '".concat(s,"' on 'TimeRanges': The index provided (").concat(i,") is greater than the maximum bound (").concat(r,")"));return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const Ec={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},da=a=>String.fromCharCode(Ec[a]||a),_e=15,Ue=100,Tc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Sc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},xc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ac={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Lc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class bc{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;te.log("".concat(this.time," [").concat(e,"] ").concat(s))}}}const Ze=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class ca{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Ic{constructor(){this.uchar=" ",this.penState=new ca}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Rc{constructor(e){this.chars=[],this.pos=0,this.currPenState=new ca,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ue;t++)this.chars.push(new Ic);this.logger=e}equals(e){for(let t=0;t<Ue;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ue;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ue;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ue&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ue)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=da(e);if(this.pos>=Ue){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ue;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Ue;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class $s{constructor(e){this.rows=[],this.currRow=_e-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<_e;t++)this.rows.push(new Rc(e));this.logger=e}reset(){for(let e=0;e<_e;e++)this.rows[e].clear();this.currRow=_e-1}equals(e){let t=!0;for(let s=0;s<_e;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<_e;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<_e;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ae(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<_e;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,d=this.logger.time;if(o!==null&&d!==null&&o<d)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ae(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<_e;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join("\n")),s}getTextAndFormat(){return this.rows}}class Nr{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new $s(s),this.nonDisplayedMemory=new $s(s),this.lastOutputScreen=new $s(s),this.currRollUpRow=this.displayedMemory.rows[_e-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[_e-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ae(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class $r{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=_c(),this.logger=void 0;const i=this.logger=new bc;this.channels=[null,new Nr(e,t,i),new Nr(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+Ze([t[s],t[s+1]])+"] -> ("+Ze([i,r])+")");const d=this.cmdHistory;if(i>=16&&i<=31){if(Dc(i,r,d)){qt(null,null,d),this.logger.log(3,()=>"Repeated command ("+Ze([i,r])+") is dropped");continue}qt(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else qt(null,null,d);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Ze([i,r])+" orig: "+Ze([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Ze([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?Tc[e]:xc[e]:s=n===1?Sc[e]:Ac[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+da(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+Ze(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=Lc[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}qt(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function qt(a,e,t){t.a=a,t.b=e}function Dc(a,e,t){return t.a===a&&t.b===e}function _c(){return{a:null,b:null}}var Ri=function(){if(ms!=null&&ms.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,d){if(typeof d!="string"||!Array.isArray(o))return!1;const l=d.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...d){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const c in h)o[c]=h[c]}return o}function n(o,d,l){const h=this,c={enumerable:!0};h.hasBeenReset=!1;let u="",g=!1,f=o,p=d,y=l,v=null,E="",T=!0,S="auto",x="start",I=50,A="middle",b=50,k="middle";Object.defineProperty(h,"id",r({},c,{get:function(){return u},set:function(L){u=""+L}})),Object.defineProperty(h,"pauseOnExit",r({},c,{get:function(){return g},set:function(L){g=!!L}})),Object.defineProperty(h,"startTime",r({},c,{get:function(){return f},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");f=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},c,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},c,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},c,{get:function(){return v},set:function(L){v=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},c,{get:function(){return E},set:function(L){const F=s(L);if(F===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=F,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},c,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},c,{get:function(){return S},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},c,{get:function(){return x},set:function(L){const F=i(L);if(!F)throw new SyntaxError("An invalid or illegal string was specified.");x=F,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},c,{get:function(){return I},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");I=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},c,{get:function(){return A},set:function(L){const F=i(L);if(!F)throw new SyntaxError("An invalid or illegal string was specified.");A=F,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},c,{get:function(){return b},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");b=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},c,{get:function(){return k},set:function(L){const F=i(L);if(!F)throw new SyntaxError("An invalid or illegal string was specified.");k=F,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class kc{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ha(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Cc{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function ua(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],d=n[1];e(o,d)}}const ni=new Ri(0,0,""),zt=ni.align==="middle"?"middle":"center";function Pc(a,e,t){const s=a;function i(){const o=ha(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,d){const l=new Cc;ua(o,function(u,g){let f;switch(u){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(u,t[p].region);break}break;case"vertical":l.alt(u,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(u,f[0]),l.percent(u,f[0])&&l.set("snapToLines",!1),l.alt(u,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",zt,"end"]);break;case"position":f=g.split(","),l.percent(u,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",zt,"end","line-left","line-right","auto"]);break;case"size":l.percent(u,g);break;case"align":l.alt(u,g,["start",zt,"end","left","right"]);break}},/:/,/\s/),d.region=l.get("region",null),d.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&ni.line===-1&&(h=-1),d.line=h,d.lineAlign=l.get("lineAlign","start"),d.snapToLines=l.get("snapToLines",!0),d.size=l.get("size",100),d.align=l.get("align",zt);let c=l.get("position","auto");c==="auto"&&ni.position===50&&(c=d.align==="start"||d.align==="left"?0:d.align==="end"||d.align==="right"?100:50),d.position=c}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function fa(a){return a.replace(/<br(?: \/)?>/gi,"\n")}class wc{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new kc,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,n=0;for(r=fa(r);n<r.length&&r[n]!=="\r"&&r[n]!=="\n";)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]==="\n"&&++n,t.buffer=r.slice(n),o}function i(r){ua(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Ri(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Pc(r,t.cue,t.regionList)}catch(o){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch(r){t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+="\n\n",e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Oc=/\r\n|\n\r|\n|\r/g,Bs=function(e,t,s=0){return e.slice(s,s+t.length)===t},Fc=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!G(t)||!G(s)||!G(i)||!G(r))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*s,t+=60*1e3*i,t+=60*60*1e3*r,t};function Di(a,e,t){return It(a.toString())+It(e.toString())+It(t)}const Mc=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function Nc(a,e,t,s,i,r,n){const o=new wc,d=Se(new Uint8Array(a)).trim().replace(Oc,"\n").split("\n"),l=[],h=e?Zl(e.baseTime,e.timescale):0;let c="00:00.000",u=0,g=0,f,p=!0;o.oncue=function(y){const v=t[s];let E=t.ccOffset;const T=(u-h)/9e4;if(v!=null&&v.new&&(g!==void 0?E=t.ccOffset=v.start:Mc(t,s,T)),T){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}E=T-t.presentationOffset}const S=y.endTime-y.startTime,x=be((y.startTime+E-g)*9e4,i*9e4)/9e4;y.startTime=Math.max(x,0),y.endTime=Math.max(x+S,0);const I=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(I)),y.id||(y.id=Di(y.startTime,y.endTime,I)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){n(f);return}r(l)},d.forEach(y=>{if(p)if(Bs(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(v=>{Bs(v,"LOCAL:")?c=v.slice(6):Bs(v,"MPEGTS:")&&(u=parseInt(v.slice(7)))});try{g=Fc(c)/1e3}catch(v){f=v}return}else y===""&&(p=!1);o.parse(y+"\n")}),o.flush()}const Us="stpp.ttml.im1t",ga=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ma=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,$c={left:"start",center:"center",right:"end",start:"start",end:"end"};function Br(a,e,t,s){const i=Q(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Se(o)),n=Ql(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Bc(o,n)))}catch(o){s(o)}}function Bc(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((c,u)=>(c[u]=i.getAttribute("ttp:".concat(u))||r[u],c),{}),o=i.getAttribute("xml:space")!=="preserve",d=Ur(Gs(i,"styling","style")),l=Ur(Gs(i,"layout","region")),h=Gs(i,"body","[begin]");return[].map.call(h,c=>{const u=pa(c,o);if(!u||!c.hasAttribute("begin"))return null;const g=Ks(c.getAttribute("begin"),n),f=Ks(c.getAttribute("dur"),n);let p=Ks(c.getAttribute("end"),n);if(g===null)throw Gr(c);if(p===null){if(f===null)throw Gr(c);p=g+f}const y=new Ri(g-e,p-e,u);y.id=Di(y.startTime,y.endTime,y.text);const v=l[c.getAttribute("region")],E=d[c.getAttribute("style")],T=Uc(v,E,d),{textAlign:S}=T;if(S){const x=$c[S];x&&(y.lineAlign=x),y.align=S}return re(y,T),y}).filter(c=>c!==null)}function Gs(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Ur(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function pa(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+"\n":(r=s.childNodes)!=null&&r.length?pa(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Uc(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,d)=>{const l=Vs(e,s,d)||Vs(a,s,d)||Vs(i,s,d);return l&&(o[d]=l),o},{})}function Vs(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function Gr(a){return new Error("Could not parse ttml timestamp ".concat(a))}function Ks(a,e){if(!a)return null;let t=ha(a);return t===null&&(ga.test(a)?t=Gc(a,e):ma.test(a)&&(t=Vc(a,e))),t}function Gc(a,e){const t=ga.exec(a),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function Vc(a,e){const t=ma.exec(a),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class Xt{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Kc{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Kr(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Xt(this,"textTrack1"),t=new Xt(this,"textTrack2"),s=new Xt(this,"textTrack3"),i=new Xt(this,"textTrack4");this.cea608Parser1=new $r(1,e,t),this.cea608Parser2=new $r(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const d=r[o],l=Hc(d[0],d[1],t,s);if(l>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:n}=this;s===V.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach(o=>{this.onFragLoaded(m.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Vr(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,ct(s[e]),aa(s[e],i);else{const d=this.createTextTrack("captions",r,n);d&&(d[e]=!0,s[e]=d)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{ct(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Kr(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)ct(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Us);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Zn(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?rs(n.textTracks):null;if(this.tracks.forEach((d,l)=>{let h;if(o){let c=null;for(let u=0;u<o.length;u++)if(o[u]&&Vr(o[u],d)){c=o[u],o[u]=null;break}c&&(h=c)}if(h)ct(h);else{const c=ya(d);h=this.createTextTrack(c,d.name,d.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const d=o.filter(l=>l!==null).map(l=>l.label);d.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: ".concat(d.join(", "),". Replace media element for each source to clear TextTracks and captions menu."))}}else if(this.tracks.length){const n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r="textTrack".concat(i[1]),n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===V.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:d,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||d!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=d,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===V.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],d=this.vttCCs;d[s.cc]||(d[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Us?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Br(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log("Failed to parse IMSC1: ".concat(i)),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const d=this.hls,l=(t=s.initSegment)!=null&&t.data?Re(s.initSegment.data,new Uint8Array(i)).buffer:i;Nc(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),d.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const c=h.message==="Missing initPTS for VTT MPEGTS";c?n.push(e):this._fallbackToIMSC1(s,i),d.logger.log("Failed to parse VTT cue: ".concat(h)),!(c&&o>s.cc)&&d.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Br(t,this.initPTS[e.cc],()=>{s.textCodec=Us,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>oa(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===V.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===V.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(d=>ri(o[d],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(d=>ri(o[d],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],d=127&e[i++];if(o===0&&d===0)continue;if((4&n)!==0){const h=3&n;(h===0||h===1)&&(t[h].push(o),t[h].push(d))}}return t}}function ya(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Vr(a,e){return!!a&&a.kind===ya(e)&&ti(e,a)}function Hc(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function Kr(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Wc=/\s/,Yc={newCue(a,e,t,s){const i=[];let r,n,o,d,l;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(r=s.rows[u],o=!0,d=0,l="",!r.isEmpty()){var c;for(let p=0;p<r.chars.length;p++)Wc.test(r.chars[p].uchar)&&o?d++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),d>=16?d--:d++;const g=fa(l.trim()),f=Di(e,t,g);a!=null&&(c=a.cues)!=null&&c.getCueById(f)||(n=new h(e,t,g),n.id=f,n.line=u+1,n.align="left",n.position=10+Math.min(80,Math.floor(d*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((u,g)=>u.line==="auto"||g.line==="auto"?0:u.line>8&&g.line>8?g.line-u.line:u.line-g.line),i.forEach(u=>oa(a,u))),i}};function jc(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(a){}return!1}const qc=/(\d+)-(\d+)\/(\d+)/;class Hr{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Zc,this.controller=new self.AbortController,this.stats=new di}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=zc(e,this.controller.signal),n=e.responseType==="arraybuffer",o=n?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=d&&G(d)?d:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(wt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var u;this.response=this.loader=c;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!c.ok){const{status:p,statusText:y}=c;throw new Jc(y||"fetch, bad network response",p,c)}i.loading.first=g,i.total=Qc(c.headers)||i.total;const f=(u=this.callbacks)==null?void 0:u.onProgress;return f&&G(t.highWaterMark)?this.loadProgressively(c,i,e,t.highWaterMark,f):n?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var u,g;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=c[o];p&&(i.loaded=i.total=p);const y={url:f.url,data:c,code:f.status},v=(u=this.callbacks)==null?void 0:u.onProgress;v&&!G(t.highWaterMark)&&v(i,e,c,f),(g=this.callbacks)==null||g.onSuccess(y,i,e,f)}).catch(c=>{var u;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const g=c&&c.code||0,f=c?c.message:null;(u=this.callbacks)==null||u.onError({code:g,text:f},e,c?c.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new Pn,o=e.body.getReader(),d=()=>o.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,c=h.length;return t.loaded+=c,c<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,h.buffer,e),d()}).catch(()=>Promise.reject());return d()}}function zc(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(re({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Xc(a){const e=qc.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Qc(a){const e=a.get("Content-Range");if(e){const s=Xc(e);if(G(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function Zc(a,e){return new self.Request(a.url,e)}class Jc extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const eh=/^age:\s*[\d.]+\s*$/im;class va{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new di,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&G(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=h!=null?h:t.response;if(f!=null){var n,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(n=this.callbacks)==null?void 0:n.onProgress;y&&y(s,e,f,t);const v={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}const c=r.loadPolicy.errorRetry,u=s.retry,g={url:e.url,data:void 0,code:l};if(gs(c,u,!1,g))this.retry(c);else{var d;te.error("".concat(l," while loading ").concat(e.url)),(d=this.callbacks)==null||d.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(gs(e,t,!0))this.retry(e);else{var s;te.warn("timeout while loading ".concat((s=this.context)==null?void 0:s.url));const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=hi(e,s.retry),s.retry++,te.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(t==null?void 0:t.url,", retrying ").concat(s.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&eh.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp("^".concat(e,":\\s*[\\d.]+\\s*$"),"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const th={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},sh=se(se({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:va,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:bo,bufferController:fd,capLevelController:bi,errorController:ko,fpsController:nc,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Sn,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:th},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},ih()),{},{subtitleStreamController:yc,subtitleTrackController:lc,timelineController:Kc,audioStreamController:dd,audioTrackController:cd,emeController:ut,cmcdController:sc,contentSteeringController:rc,interstitialsController:pc});function ih(){return{cueHandler:Yc,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function rh(a,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=ai(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o="".concat(n==="level"?"playlist":n,"LoadPolicy"),d=e[o]===void 0,l=[];r.forEach(h=>{const c="".concat(n,"Loading").concat(h),u=e[c];if(u!==void 0&&d){l.push(c);const g=s[o].default;switch(e[o]={default:g},h){case"TimeOut":g.maxLoadTimeMs=u,g.maxTimeToFirstByteMs=u;break;case"MaxRetry":g.errorRetry.maxNumRetry=u,g.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":g.errorRetry.retryDelayMs=u,g.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=u,g.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&t.warn('hls.js config: "'.concat(l.join('", "'),'" setting(s) are deprecated, use "').concat(o,'": ').concat(ae(e[o])))}),se(se({},s),e)}function ai(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(ai):Object.keys(a).reduce((e,t)=>(e[t]=ai(a[t]),e),{}):a}function nh(a,e){const t=a.loader;t!==Hr&&t!==va?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):jc()&&(a.loader=Hr,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const ns=2,ah=.1,oh=.05,lh=100;class dh extends vn{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(lh),this.mediaSource=t.mediaSource;const s=this.media=t.media;Te(s,"playing",this.onMediaPlaying),Te(s,"waiting",this.onMediaWaiting),Te(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Ie(s,"playing",this.onMediaPlaying),Ie(s,"waiting",this.onMediaWaiting),Ie(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,d=this.seeking&&!o,l=!this.seeking&&o,h=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||d){d&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!z.getBuffered(n).length){this.nudgeRetry=0;return}const c=z.bufferInfo(n,e,0),u=c.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const I=Wr(this.hls.inFlightFragments,e),A=c.len>ns,b=!u||I||u-e>ns&&!g.getPartialFragment(e);if(A||b)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(c.len>0)&&!u)return;const A=Math.max(u,c.start||0)-e,k=!!(f!=null&&f.live)?f.targetduration*2:ns,L=g.getPartialFragment(e);if(A>0&&(A<=k||L)){n.paused||this._trySkipBufferHole(L);return}}const p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting;let E=this.stalled;if(E===null)if(v>0&&y-v<p)E=this.stalled=v;else{this.stalled=y;return}const T=y-E;if(!o&&(T>=p||v)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-((f==null?void 0:f.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}const x=z.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(x,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(s),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=z.bufferedInfo(z.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=z.timeRangesToArray(i),o=z.bufferedInfo(n,t,0).bufferedIndex;if(o>-1&&o<n.length-1){const d=z.bufferedInfo(n,e,0).bufferedIndex,l=n[o].end,h=n[o+1].start;if((d===-1||d>o)&&h-l<1&&e-l<2){const c=new Error("nudging playhead to flush pipeline after video hole. currentTime: ".concat(e," hole: ").concat(l," -> ").concat(h," buffered index: ").concat(d));this.warn(c.message),this.media.currentTime+=1e-6;const u=this.fragmentTracker.getPartialFragment(e)||void 0,g=z.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:u,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:o}=this,d=(i=this.hls)==null?void 0:i.config;if(!o||!n||!d)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=n.getPartialFragment(s);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const c=e.buffered,u=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>d.maxBufferHole||e.nextStart&&(e.nextStart-s<d.maxBufferHole||u))&&(t>d.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,V.MAIN),n=s.getFragAtPos(i,V.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error("Playback stalling at @".concat(s.currentTime," due to low buffer (").concat(ae(e),")"));this.warn(n.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,o=z.bufferInfo(i,n,0),d=n<o.start?o.start:o.nextStart;if(d&&this.hls){const h=o.len<=r.maxBufferHole,c=o.len>0&&o.len<1&&i.readyState<3,u=d-n;if(u>0&&(h||c)){if(u>r.maxBufferHole){let f=!1;if(n===0){const p=s.getAppendedFrag(0,V.MAIN);p&&d<p.end&&(f=!0)}if(!f){const p=e||s.getAppendedFrag(n,V.MAIN);if(p){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Wr(this.hls.inFlightFragments,d))return 0;let v=!1,E=p.end;for(;E<d;){const T=s.getPartialFragment(E);if(T)E+=T.duration;else{v=!0;break}}if(v)return 0}}}const g=Math.max(d+oh,n+ah);if(this.warn("skipping hole, adjusting currentTime from ".concat(n," to ").concat(g)),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){const f=new Error("fragment loaded with buffer holes, seeking from ".concat(n," to ").concat(g));this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,frag:e||void 0,buffer:o.len,bufferInfo:o})}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t==null?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=n+(i+1)*r.nudgeOffset,d=new Error("Nudging 'currentTime' from ".concat(n," to ").concat(o));this.warn(d.message),s.currentTime=o,t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:d,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error("Playhead still not moving while enough data buffered @".concat(n," after ").concat(r.nudgeMaxRetry," nudges"));this.error(o.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Wr(a,e){const t=Yr(a.main);if(t&&t.start<=e)return t;const s=Yr(a.audio);return s&&s.start<=e?s:null}function Yr(a){if(!a)return null;switch(a.state){case w.IDLE:case w.STOPPED:case w.ENDED:case w.ERROR:return null}return a.frag}const ch=.25;function oi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function jr(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch(n){r=new a(e,t,ae(i?se({type:i},s):s))}return r}const Qt=(()=>{const a=oi();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function hh(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class uh{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(m.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&ct(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return aa(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=oi();if(n)for(let o=0;o<r.length;o++){const d=r[o].type;if(d===Ee.emsg&&!s||!i)continue;const l=Bn(r[o].data);if(l){const h=r[o].pts;let c=h+r[o].duration;c>Qt&&(c=Qt),c-h<=0&&(c=h+ch);for(let g=0;g<l.length;g++){const f=l[g];if(!Un(f)){this.updateId3CueEnds(h,d);const p=jr(n,h,c,f,d);p&&this.id3Track.addCue(p)}}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===Qt&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:d}}=n;if(r&&(o||d)){let l;i==="audio"?l=h=>h.type===Ee.audioId3&&d:i==="video"?l=h=>h.type===Ee.emsg&&o:l=h=>h.type===Ee.audioId3&&d||h.type===Ee.emsg&&o,ri(r,t,s,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:i}=e,r=Object.keys(i);let n=this.dateRangeCuesAppended;if(s&&t){var o;if((o=s.cues)!=null&&o.length){const h=Object.keys(n).filter(c=>!r.includes(c));for(let c=h.length;c--;){const u=h[c],g=n[u].cues;delete n[u],Object.keys(g).forEach(f=>{try{const p=g[f];p.removeEventListener("enter",this.onEventCueEnter),s.removeCue(p)}catch(p){}})}}else n=this.dateRangeCuesAppended={}}const d=e.fragments[e.fragments.length-1];if(r.length===0||!G(d==null?void 0:d.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=oi();for(let h=0;h<r.length;h++){const c=r[h],u=i[c],g=u.startTime,f=n[c],p=(f==null?void 0:f.cues)||{};let y=(f==null?void 0:f.durationKnown)||!1,v=Qt;const{duration:E,endDate:T}=u;if(T&&E!==null)v=g+E,y=!0;else if(u.endOnNext&&!y){const x=r.reduce((I,A)=>{if(A!==u.id){const b=i[A];if(b.class===u.class&&b.startDate>u.startDate&&(!I||u.startDate<I.startDate))return b}return I},null);x&&(v=x.startTime,y=!0)}const S=Object.keys(u.attr);for(let x=0;x<S.length;x++){const I=S[x];if(!Ko(I))continue;const A=p[I];if(A)y&&!f.durationKnown?A.endTime=v:Math.abs(A.startTime-g)>.01&&(A.startTime=g,A.endTime=v);else if(l){let b=u.attr[I];Ho(I)&&(b=hh(b));const L=jr(l,g,v,{key:I,data:b},Ee.dateRange);L&&(L.id=c,this.id3Track.addCue(L),p[I]=L,this.hls.config.interstitialsController&&(I==="X-ASSET-LIST"||I==="X-ASSET-URL")&&L.addEventListener("enter",this.onEventCueEnter))}}n[c]={cues:p,dateRange:u,durationKnown:y}}}}class fh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const d=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(d<l&&d>.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,n)),u=Math.round(2/(1+Math.exp(-.75*d-this.edgeStalled))*20)/20,g=Math.min(c,Math.max(1,u));this.changeMediaPlaybackRate(t,g)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,d=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat((i=this.targetLatency)==null?void 0:i.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(e.playbackRate," to ").concat(t)),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class gh extends Li{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let o=!1,d=!1,l=!1;t.levels.forEach(h=>{const c=h.attrs;let{audioCodec:u,videoCodec:g}=h;u&&(h.audioCodec=u=cs(u,s)||void 0),g&&(g=h.videoCodec=ho(g));const{width:f,height:p,unknownCodecs:y}=h;let v=y?y.length:0;if(y)for(let L=v;L--;){const F=y[L];this.isAudioSupported(F)?(h.audioCodec=u=u?"".concat(u,",").concat(F):F,v--,gt.audio[u.substring(0,4)]=2):this.isVideoSupported(F)&&(h.videoCodec=g=g?"".concat(g,",").concat(F):F,v--,gt.video[g.substring(0,4)]=2)}if(o||(o=!!(f&&p)),d||(d=!!g),l||(l=!!u),v||u&&!this.isAudioSupported(u)||g&&!this.isVideoSupported(g)){this.log('Some or all CODECS not supported "'.concat(c.CODECS,'"'));return}const{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":x,RESOLUTION:I,"VIDEO-RANGE":A}=c,b="".concat(x||".","-"),k="".concat(b).concat(h.bitrate,"-").concat(I,"-").concat(T,"-").concat(E,"-").concat(A,"-").concat(S);if(r[k])if(r[k].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const L=n[k]+=1;h.attrs["PATHWAY-ID"]=new Array(L+1).join(".");const F=this.createLevel(h);r[k]=F,i.push(F)}else r[k].addGroupId("audio",c.AUDIO),r[k].addGroupId("text",c.SUBTITLES);else{const L=this.createLevel(h);r[k]=L,n[k]=1,i.push(L)}}),this.filterAndSortMediaOptions(i,t,o,d,l)}createLevel(e){const t=new Dt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(s.videoCodec,'"'));this.log(i.message),t.supportedResult=fn(i,[])}return t}isAudioSupported(e){return js(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return js(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){let n=[],o=[],d=e;if((s||i)&&r&&(d=d.filter(({videoCodec:y,videoRange:v,width:E,height:T})=>(!!y||!!(E&&T))&&po(v))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",v=y;t.levels.length&&(v="one or more CODECS in variant not supported: ".concat(ae(t.levels.map(T=>T.attrs.CODECS).filter((T,S,x)=>x.indexOf(T)===S))),this.warn(v),y+=" (".concat(v,")"));const E=new Error(y);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:E,reason:v})}});return}t.audioTracks&&(n=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),qr(n)),t.subtitles&&(o=t.subtitles,qr(o));const l=d.slice(0);d.sort((y,v)=>{if(y.attrs["HDCP-LEVEL"]!==v.attrs["HDCP-LEVEL"])return(y.attrs["HDCP-LEVEL"]||"")>(v.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&y.height!==v.height)return y.height-v.height;if(y.frameRate!==v.frameRate)return y.frameRate-v.frameRate;if(y.videoRange!==v.videoRange)return hs.indexOf(y.videoRange)-hs.indexOf(v.videoRange);if(y.videoCodec!==v.videoCodec){const E=Gi(y.videoCodec),T=Gi(v.videoCodec);if(E!==T)return T-E}if(y.uri===v.uri&&y.codecSet!==v.codecSet){const E=ds(y.codecSet),T=ds(v.codecSet);if(E!==T)return T-E}return y.averageBitrate!==v.averageBitrate?y.averageBitrate-v.averageBitrate:0});let h=l[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==l.length)){for(let y=0;y<l.length;y++)if(l[y].pathwayId===d[0].pathwayId){h=l[y];break}}this._levels=d;for(let y=0;y<d.length;y++)if(d[y]===h){var c;this._firstLevel=y;const v=h.bitrate,E=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(d.length," level(s) found, first bitrate: ").concat(v)),((c=this.hls.userConfig)==null?void 0:c.abrEwmaDefaultEstimate)===void 0){const T=Math.min(v,this.hls.config.abrEwmaDefaultEstimateMax);T>E&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const u=r&&!i,g=this.hls.config,f=!!(g.audioStreamController&&g.audioTrackController),p={levels:d,audioTracks:n,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:f&&!u&&n.some(y=>!!y.url)};this.hls.trigger(m.MANIFEST_PARSED,p)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:h,reason:h.message}),c)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===o)return;this.log("Switching to level ".concat(e," (").concat(n.height?n.height+"p ":"").concat(n.videoRange?n.videoRange+" ":"").concat(n.codecSet?n.codecSet+" ":"","@").concat(n.bitrate,")").concat(o?" with Pathway "+o:""," from level ").concat(s).concat(r?" with Pathway "+r:""));const d={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,d);const l=n.details;if(!l||l.live){const h=this.switchParams(n.uri,i==null?void 0:i.details,l);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn("pathwayPriority ".concat(e," should contain at least one pathway from list: ").concat(t));return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Z.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===V.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log("Resetting level error count of ".concat(i.loadError," on frag buffered")),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var o;this.warn("Invalid level index ".concat(i)),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let d=n.details;d===t.details&&d.advanced&&(d=void 0),this.playlistLoaded(i,t,d)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,o=n==null?void 0:n.age;this.log("Loading level index ".concat(i).concat((t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:"").concat(r?" Pathway "+r:"").concat(o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""," ").concat(s)),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));_n(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function qr(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Ea(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ta(){if(!qe())return!1;const e=Ea();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function mh(){if(!Ta())return!1;const a=qe();return typeof(a==null?void 0:a.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(Rt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(Rt(e,"audio"))))}function ph(){var a;const e=Ea();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const yh=100;class vh extends pi{constructor(e,t,s){super(e,t,s,"stream-controller",V.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!G(r)||(this.log("Media seeked to ".concat(r.toFixed(3))),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,V.MAIN,0);if(n===null||n.len===0){this.warn("Main forward buffer length at ".concat(r,' on "seeked" event ').concat(n?n.len:"empty",")"));return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(yh),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log("Override startPosition with lastCurrentTime @".concat(s.toFixed(3))),e=s),this.state=w.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=w.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case w.WAITING_LEVEL:{const{levels:t,level:s}=this,i=t==null?void 0:t[s],r=i==null?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=w.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=w.IDLE;break}break}case w.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:i,level:r}=this,n=i==null?void 0:i[r];this.resetStartWhenNotLoaded(n||null),this.state=w.IDLE}}break}this.state===w.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const d=this.getLevelDetails();if(d&&this._streamEnded(o,d)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=w.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log("Adapting to level ".concat(r," from level ").concat(this.level)),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===w.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=w.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,c=this.getMaxBufferLength(n.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&ge(g)&&this.fragmentTracker.getState(g)!==he.OK){var f;const y=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,v=l.fragments[y-1];v&&g.cc===v.cc&&(g=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,u)){if(!g.gap){const y=this.audioOnly&&!this.altAudio?ne.AUDIO:ne.VIDEO,v=(y===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,V.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,V.MAIN,c)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,n,u))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===he.NOT_LOADED||i===he.PARTIAL?ge(e)?this.bitrateTest?(this.log("Fragment ".concat(e.sn," of level ").concat(e.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,V.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,d=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*d.maxBitrate/(1e3*l)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const d=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(n.end,d+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case w.KEY_LOADING:case w.FRAG_LOADING:case w.FRAG_LOADING_WAITING_RETRY:case w.PARSING:case w.PARSED:this.state=w.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Te(s,"playing",this.onMediaPlaying),Te(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Ie(s,"playing",this.onMediaPlaying),Ie(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;t.levels.forEach(r=>{const n=r.audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&i&&!ph(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==w.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=w.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,o=t.details,d=o.totalduration;if(!i){this.warn("Levels were reset while loading level ".concat(n));return}this.log("Level ".concat(n," loaded [").concat(o.startSN,",").concat(o.endSN,"]").concat(o.lastPartSn?"[part-".concat(o.lastPartSn,"-").concat(o.lastPartIndex,"]"):"",", cc [").concat(o.startCC,", ").concat(o.endCC,"] duration:").concat(d));const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===w.FRAG_LOADING||this.state===w.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,c),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:n}),this.state===w.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=w.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,o=e.edge,d=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!d)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!d&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn("Playback: ".concat(r.toFixed(3)," is located too far from the end of live sliding playlist: ").concat(o,", reset currentTime to : ").concat(i.toFixed(3))),this.config.liveSyncMode==="buffered"){var l;const c=z.bufferInfo(s,i,0);if(!(c!=null&&(l=c.buffered)!=null&&l.length)){s.currentTime=i;return}if(c.start<=r){s.currentTime=i;return}const{nextStart:g}=z.bufferedInfo(c.buffered,r,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(s.sn," of level ").concat(s.level," will not be buffered"));return}const o=n[s.level];if(!o){this.warn("Level ".concat(s.level," not found on progress"));return}const d=o.details;if(!d){this.warn("Dropping fragment ".concat(s.sn," of level ").concat(s.level," after level details were reset")),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=d.PTSKnown||!d.live,c=(t=s.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new Qn(this.hls,V.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,p=f!==-1,y=new fi(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,p),v=this.initPTS[s.cc];g.push(r,c,u,l,s,i,d.totalduration,h,y,v)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio===2;if(us(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{var n;(n=this.hls)==null||n.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=us(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const o in s){const d=s[o];if(d.id==="main"){if(r=o,i=d,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log("Alternate track found, use ".concat(r,".buffered to schedule main fragment loading")),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===V.MAIN;if(r){if(this.fragContextChanged(s)){this.warn("Fragment ".concat(s.sn).concat(i?" p: "+i.index:""," of level ").concat(s.level," finished buffering, but was aborted. state: ").concat(this.state)),this.state===w.PARSED&&(this.state=w.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ge(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&z.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=w.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===w.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Z.LEVEL&&(this.state=w.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.resetLoadingState();break;case _.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=w.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ne.AUDIO||!this.altAudio){const s=(t===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,V.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log("could not seek to ".concat(s,", already seeking at ").concat(t));return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=z.getBuffered(e),o=n.length?n.start(0):0,d=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||d>0&&(d<l||this.loadingParts&&d<2*((r==null?void 0:r.partTarget)||0)))&&(this.log("adjusting start position by ".concat(d," to match buffer start")),s+=d,this.startPosition=s),t<s&&(this.log("seek to target start position ".concat(s," from current time ").concat(t," buffer start ").concat(o)),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s==null?void 0:s.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=w.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:d,part:l,level:h}=o,{video:c,text:u,id3:g,initSegment:f}=r,{details:p}=h,y=this.altAudio?void 0:r.audio;if(this.fragContextChanged(d)){this.fragmentTracker.removeFragment(d);return}if(this.state=w.PARSING,f){if(f!=null&&f.tracks){const T=d.initSegment||d;this._bufferInitSegment(h,f.tracks,T,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:s,tracks:f.tracks})}const v=f.initPTS,E=f.timescale;G(v)&&(this.initPTS[d.cc]={baseTime:v,timescale:E},i.trigger(m.INIT_PTS_FOUND,{frag:d,id:s,initPTS:v,timescale:E}))}if(c&&p){y&&c.type==="audiovideo"&&this.logMuxedErr(d);const v=p.fragments[d.sn-1-p.startSN],E=d.sn===p.startSN,T=!v||d.cc>v.cc;if(r.independent!==!1){const{startPTS:S,endPTS:x,startDTS:I,endDTS:A}=c;if(l)l.elementaryStreams[c.type]={startPTS:S,endPTS:x,startDTS:I,endDTS:A};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!T&&(this.couldBacktrack=!0),c.dropped&&c.independent){const b=this.getMainFwdBufferInfo(),k=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,L=c.firstKeyFramePTS?c.firstKeyFramePTS:S;if(!E&&k<L-this.config.maxBufferHole&&!T){this.backtrack(d);return}else T&&(d.gap=!0);d.setElementaryStreamInfo(c.type,d.start,x,d.start,A,!0)}else E&&S-(p.appliedTimelineOffset||0)>ns&&(d.gap=!0);d.setElementaryStreamInfo(c.type,S,x,I,A),this.backtrackFragment&&(this.backtrackFragment=d),this.bufferFragmentData(c,d,l,n,E||T)}else if(E||T)d.gap=!0;else{this.backtrack(d);return}}if(y){const{startPTS:v,endPTS:E,startDTS:T,endDTS:S}=y;l&&(l.elementaryStreams[ne.AUDIO]={startPTS:v,endPTS:E,startDTS:T,endDTS:S}),d.setElementaryStreamInfo(ne.AUDIO,v,E,T,S),this.bufferFragmentData(y,d,l,n)}if(p&&g!=null&&(t=g.samples)!=null&&t.length){const v={id:s,frag:d,details:p,samples:g.samples};i.trigger(m.FRAG_PARSING_METADATA,v)}if(p&&u){const v={id:s,frag:d,details:p,samples:u.samples};i.trigger(m.FRAG_PARSING_USERDATA,v)}}logMuxedErr(e){this.warn("".concat(ge(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}_bufferInitSegment(e,t,s,i){if(this.state!==w.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:o}=t;if(r){let l=Zt(r.codec,e.audioCodec);l==="mp4a"&&(l="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const c=r.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log("Android: force audio codec to ".concat(l))),e.audioCodec&&e.audioCodec!==l&&this.log('Swapping manifest audio codec "'.concat(e.audioCodec,'" for "').concat(l,'"')),r.levelCodec=l,r.id=V.MAIN,this.log("Init audio buffer, container:".concat(r.container,", codecs[selected/level/parsed]=[").concat(l||"","/").concat(e.audioCodec||"","/").concat(r.codec,"]")),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=V.MAIN;const l=n.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log("Init video buffer, container:".concat(n.container,", codecs[level/parsed]=[").concat(e.videoCodec||"","/").concat(l,"]").concat(n.codec!==l?" parsed-corrected="+n.codec:"").concat(n.supplemental?" supplemental="+n.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:".concat(o.container,", codecs[level/parsed]=[").concat(e.codecs,"/").concat(o.codec,"]")),delete t.video,delete t.audio);const d=Object.keys(t);if(d.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;d.forEach(l=>{const c=t[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:c,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,V.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=w.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(z.isBuffered(e,s)?t=this.getAppendedFrag(s):z.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return G(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(G(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?st(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Eh{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=_.KEY_LOAD_ERROR,s,i,r){return new Ge({type:H.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length){const{sn:s,cc:i}=e;for(let r=0;r<t.length;r++){const n=t[r];if(i<=n.cc&&(s==="initSegment"||n.sn==="initSegment"||s<n.sn))return this.emeController.selectKeySystemFormat(n).then(o=>{if(n.setKeyFormat(o),this.emeController&&this.config.requireKeySystemAccessOnStart){const d=es(o);if(d)return this.emeController.getKeySystemAccess([d])}})}}else if(this.config.requireKeySystemAccessOnStart){const s=xt(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?"Expected frag.decryptdata to be defined after setting format ".concat(t):"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(n,'"'))));let o=this.keyUriToKeyInfo[n];if((s=o)!=null&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var d;switch((d=o.mediaKeySessionContext)==null?void 0:d.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(l=>(r.key=l.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(r.method,'"'))))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const d={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,g,f,p)=>{const{frag:y,keyInfo:v,url:E}=f;if(!y.decryptdata||v!==this.keyUriToKeyInfo[E])return o(this.createKeyLoadError(y,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=y.decryptdata.key=new Uint8Array(u.data),y.keyLoader=null,v.loader=null,n({frag:y,keyInfo:v})},onError:(u,g,f,p)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(u.code," loading key ").concat(u.text)),f,se({url:d.url,data:void 0},u)))},onTimeout:(u,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(u,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(d,h,c)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function zr(a){const{type:e}=a;switch(e){case Z.AUDIO_TRACK:return V.AUDIO;case Z.SUBTITLE_TRACK:return V.SUBTITLE;default:return V.MAIN}}function Hs(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Th{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Z.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o,levelInfo:d}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Z.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:d})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Z.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Z.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[Z.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[Z.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):l.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(h.url));return}l.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),i.abort()}let r;if(e.type===Z.MANIFEST?r=s.manifestLoadPolicy.default:r=re({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),G((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Z.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Z.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Z.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,c=l.targetduration;if(h&&c){const u=Math.max(h*3,c*.8)*1e3;r=re({},r,{maxTimeToFirstByteMs:Math.min(u,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},d={onSuccess:(l,h,c,u)=>{const g=this.getInternalLoader(c);this.resetInternalLoader(c.type);const f=l.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(l,c,new Error("no EXTM3U delimiter"),u||null,h);return}h.parsing.start=performance.now(),Ne.isMediaPlaylist(f)||c.type!==Z.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,c,u||null,g):this.handleMasterPlaylist(l,h,c,u)},onError:(l,h,c,u)=>{this.handleNetworkError(h,c,!1,l,u)},onTimeout:(l,h,c)=>{this.handleNetworkError(h,c,!0,void 0,l)}};i.load(e,o,d)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log("".concat(e?"auto":"force"," startLoad with configured startPosition ").concat(t)),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=Hs(e,s),d=Ne.parseMasterPlaylist(n,o);if(d.playlistParsingError){this.handleManifestParsingError(e,s,d.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:c,sessionKeys:u,startTimeOffset:g,variableList:f}=d;this.variableList=f;const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=Ne.parseMasterPlaylistMedia(n,o,d);p.length&&!p.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new oe({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:v,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:c,sessionKeys:u,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:d,type:l}=s,h=Hs(e,s),c=G(d)?d:G(o)?o:0,u=zr(s),g=Ne.parseLevelPlaylist(e.data,h,c,u,0,this.variableList);if(l===Z.MANIFEST){const f={attrs:new oe({}),bitrate:0,details:g,name:"",url:h};g.requestScheduled=t.loading.start+In(g,0),n.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:t.type===Z.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n="A network ".concat(s?"timeout":"error"+(i?" (status "+i.code+")":"")," occurred while loading ").concat(e.type);e.type===Z.LEVEL?n+=": ".concat(e.level," id: ").concat(e.id):(e.type===Z.AUDIO_TRACK||e.type===Z.SUBTITLE_TRACK)&&(n+=" id: ".concat(e.id,' group-id: "').concat(e.groupId,'"'));const o=new Error(n);this.hls.logger.warn("[playlist-loader]: ".concat(n));let d=_.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Z.MANIFEST:d=s?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,l=!0;break;case Z.LEVEL:d=s?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,l=!1;break;case Z.AUDIO_TRACK:d=s?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Z.SUBTITLE_TRACK:d=s?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const c={type:H.NETWORK_ERROR,details:d,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const u=(t==null?void 0:t.url)||e.url;c.response=se({url:u,data:void 0},i)}this.hls.trigger(m.ERROR,c)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:d,level:l,id:h,groupId:c,deliveryDirectives:u}=i,g=Hs(t,i),f=zr(i),p=typeof i.level=="number"&&f===V.MAIN?l:void 0;if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:i,level:p,parent:f,networkDetails:r,stats:s});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const y=e.playlistParsingError;if(y){if(this.hls.logger.warn(y),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:t,context:i,level:p,parent:f,networkDetails:r,stats:s});return}e.playlistParsingError=null}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),d){case Z.MANIFEST:case Z.LEVEL:o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:i.levelOrTrack||o.levels[0],level:p||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:d===Z.MANIFEST});break;case Z.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:h||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case Z.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:h||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break}}}class et{static get version(){return Ct}static isMSESupported(){return Ta()}static isSupported(){return mh()}static getMediaSource(){return qe()}static get Events(){return m}static get MetadataSchema(){return Ee}static get ErrorTypes(){return H}static get ErrorDetails(){return _}static get DefaultConfig(){return et.defaultConfig?et.defaultConfig:sh}static set DefaultConfig(e){et.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new yi,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=Ua(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=rh(et.DefaultConfig,e,t);this.userConfig=e,s.progressive&&nh(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:o,fpsController:d}=s,l=new o(this),h=this.abrController=new i(this),c=new Co(this),u=s.interstitialsController,g=u?this.interstitialsController=new u(this,et):null,f=this.bufferController=new r(this,c),p=this.capLevelController=new n(this),y=new d(this),v=new Th(this),E=s.contentSteeringController,T=E?new E(this):null,S=this.levelController=new gh(this,T),x=new uh(this),I=new Eh(this.config),A=this.streamController=new vh(this,c,I),b=this.gapController=new dh(this,c);p.setStreamController(A),y.setStreamController(A);const k=[v,S,A];g&&k.splice(1,0,g),T&&k.splice(1,0,T),this.networkControllers=k;const L=[h,f,b,p,y,x,c];this.audioTrackController=this.createController(s.audioTrackController,k);const F=s.audioStreamController;F&&k.push(this.audioStreamController=new F(this,c,I)),this.subtitleTrackController=this.createController(s.subtitleTrackController,k);const U=s.subtitleStreamController;U&&k.push(this.subtititleStreamController=new U(this,c,I)),this.createController(s.timelineController,L),I.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(fh,L),this.coreComponents=L,k.push(l);const B=l.onErrorOut;typeof B=="function"&&this.on(m.ERROR,B,l),this.on(m.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error("attachMedia failed: invalid argument (".concat(e,")"));this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:_.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=li.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(i)),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[V.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[V.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[V.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=dc()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log("set currentLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log("set nextLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log("set loadLevel:".concat(e)),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log("set firstLevel:".concat(e)),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log("set startLevel:".concat(e)),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:".concat(e)),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){mo(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=mn(t);return gn(e,s,navigator.mediaCapabilities)}}et.defaultConfig=void 0;export{et as H,Lh as a,Ah as b};
|