@openlist-frontend/openlist-frontend 4.2.0 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/dist/VERSION +1 -1
  2. package/dist/assets/polyfills-legacy-h7H8XqQx.js +1 -0
  3. package/dist/i18n.tar.gz +0 -0
  4. package/dist/index.html +1 -1
  5. package/dist/lite/VERSION +1 -1
  6. package/dist/lite/assets/{2fa-Cpwit0Sr.js → 2fa-DTutmNbf.js} +1 -1
  7. package/dist/lite/assets/{2fa-legacy-BV80Xmmb.js → 2fa-legacy-DbBySHVF.js} +1 -1
  8. package/dist/lite/assets/{About-Cu2-75RR.js → About-_hJuNaH_.js} +1 -1
  9. package/dist/lite/assets/{About-legacy-C37sOQhm.js → About-legacy-CaLm7kbI.js} +1 -1
  10. package/dist/lite/assets/{AddOrEdit-Wdbp4PWO.js → AddOrEdit-49-UQtaG.js} +1 -1
  11. package/dist/lite/assets/{AddOrEdit-BWduAPOa.js → AddOrEdit-BCTuahUP.js} +1 -1
  12. package/dist/lite/assets/{AddOrEdit-CZnPofX2.js → AddOrEdit-Bgz6_5Sb.js} +1 -1
  13. package/dist/lite/assets/{AddOrEdit-cxf_NyVS.js → AddOrEdit-CbKEYHAy.js} +1 -1
  14. package/dist/lite/assets/{AddOrEdit-legacy-DAXPEGkN.js → AddOrEdit-legacy-CcWxIJSY.js} +1 -1
  15. package/dist/lite/assets/{AddOrEdit-legacy-2bg6358l.js → AddOrEdit-legacy-DOf8eTkz.js} +1 -1
  16. package/dist/lite/assets/{AddOrEdit-legacy-BB_Q5cWC.js → AddOrEdit-legacy-DvuS1lGq.js} +1 -1
  17. package/dist/lite/assets/{AddOrEdit-legacy-Bi5RkSpR.js → AddOrEdit-legacy-SS88nL_8.js} +1 -1
  18. package/dist/lite/assets/Common-7SPE00KT.js +1 -0
  19. package/dist/lite/assets/{Common-SxI9gPMx.js → Common-DKBpZ31X.js} +1 -1
  20. package/dist/lite/assets/{Common-legacy-DlpN8uIa.js → Common-legacy-B179Edqf.js} +1 -1
  21. package/dist/lite/assets/Common-legacy-DG884Joe.js +1 -0
  22. package/dist/lite/assets/{Copy-DTFns9Y1.js → Copy-BQypLOnU.js} +1 -1
  23. package/dist/lite/assets/{Copy-legacy-B72Ffy5O.js → Copy-legacy-CHg9MrvY.js} +1 -1
  24. package/dist/lite/assets/{Decompress-legacy-CZ_oH15V.js → Decompress-legacy-Cb2O6mH9.js} +1 -1
  25. package/dist/lite/assets/{Decompress-BPew2ezc.js → Decompress-sZhi71xA.js} +1 -1
  26. package/dist/lite/assets/{DeletePopover-cSxOxJZY.js → DeletePopover-9knkuVst.js} +1 -1
  27. package/dist/lite/assets/{DeletePopover-legacy-CBtUkOSh.js → DeletePopover-legacy-KFuQEYkg.js} +1 -1
  28. package/dist/lite/assets/{File-D7bnUBYC.js → File-Cm5ZVXiU.js} +1 -1
  29. package/dist/lite/assets/{File-legacy-aPuubWt-.js → File-legacy-BghKHFM3.js} +1 -1
  30. package/dist/lite/assets/{Folder-legacy-Bp34_ra2.js → Folder-legacy-rxbbWmwF.js} +1 -1
  31. package/dist/lite/assets/{Folder-DdumvcC1.js → Folder-u_3vXWLj.js} +3 -3
  32. package/dist/lite/assets/{Grid-C9qEJXle.js → Grid-CQOeEHng.js} +1 -1
  33. package/dist/lite/assets/{Grid-legacy-DFmTlJOv.js → Grid-legacy-CZ5i1Iq2.js} +1 -1
  34. package/dist/lite/assets/{GridItem-Cb9pnioW.js → GridItem-BnM21uyA.js} +1 -1
  35. package/dist/lite/assets/{GridItem-legacy-8gNLCEoo.js → GridItem-legacy-iFmz7kDs.js} +1 -1
  36. package/dist/lite/assets/{Images-C_Ql-iwF.js → Images-DohfDDrf.js} +1 -1
  37. package/dist/lite/assets/{Images-legacy-CoWBNLGZ.js → Images-legacy-4WKrTzml.js} +1 -1
  38. package/dist/lite/assets/{Layout-BQJH47LI.js → Layout-Dq3Tblc3.js} +4 -4
  39. package/dist/lite/assets/{Layout-legacy-MFuRQRbi.js → Layout-legacy-BqI9aaEd.js} +1 -1
  40. package/dist/lite/assets/{List-Dp5qYO6K.js → List-CKWRuz8M.js} +1 -1
  41. package/dist/lite/assets/{List-legacy-LpRbqCuW.js → List-legacy-CfJa4V_M.js} +1 -1
  42. package/dist/lite/assets/{Messenger-m_DjhhjC.js → Messenger-Csg3VDhD.js} +1 -1
  43. package/dist/lite/assets/{Messenger-legacy-qy8NmzD_.js → Messenger-legacy-Aqu2TXLS.js} +1 -1
  44. package/dist/lite/assets/{Metas-BW-d9X3k.js → Metas-CFhxnUzn.js} +1 -1
  45. package/dist/lite/assets/{Metas-legacy-DF5C5c9k.js → Metas-legacy-CpZKT74d.js} +1 -1
  46. package/dist/lite/assets/{Move-Btb_epTo.js → Move-Bp7Hz-5A.js} +1 -1
  47. package/dist/lite/assets/{Move-legacy-CkLWtx_Y.js → Move-legacy-iko-6o08.js} +1 -1
  48. package/dist/lite/assets/{Other-D3tOfd7k.js → Other-CmK2wAaG.js} +1 -1
  49. package/dist/lite/assets/{Other-legacy-Cx6-rrJn.js → Other-legacy-BfsPMHAC.js} +1 -1
  50. package/dist/lite/assets/{PackageDownload-C4OIBiuO.js → PackageDownload-DAD_3hcp.js} +1 -1
  51. package/dist/lite/assets/{PackageDownload-legacy-D6wcXpsR.js → PackageDownload-legacy-CYUHsuep.js} +1 -1
  52. package/dist/lite/assets/{Password-DOgJvyE0.js → Password-CsEn2L1J.js} +1 -1
  53. package/dist/lite/assets/{Password-legacy-Dau7Rj6C.js → Password-legacy-C_ug59KC.js} +1 -1
  54. package/dist/lite/assets/{Profile-vc4L2vOh.js → Profile-DE1w63ju.js} +1 -1
  55. package/dist/lite/assets/{Profile-legacy-CG7V6K6c.js → Profile-legacy-BccA5tXg.js} +1 -1
  56. package/dist/lite/assets/{PublicKeys-BhL22dhK.js → PublicKeys-DhLQRXa5.js} +1 -1
  57. package/dist/lite/assets/{PublicKeys-legacy-w8t5s90k.js → PublicKeys-legacy-Dm2rmP-Z.js} +1 -1
  58. package/dist/lite/assets/{ResponsiveGrid--eNaea9R.js → ResponsiveGrid-CPv65KKk.js} +1 -1
  59. package/dist/lite/assets/{ResponsiveGrid-legacy-BcOgU6tQ.js → ResponsiveGrid-legacy-B09IQ8PO.js} +1 -1
  60. package/dist/lite/assets/{S3-D5KR0Y4t.js → S3-3qppG_kP.js} +1 -1
  61. package/dist/lite/assets/{S3-legacy-DwkNpjzH.js → S3-legacy-GtHjMhMP.js} +1 -1
  62. package/dist/lite/assets/{SettingItem-gAxndiQS.js → SettingItem-BNkjHZxi.js} +1 -1
  63. package/dist/lite/assets/{SettingItem-legacy-CoygdggD.js → SettingItem-legacy-DhwPjjh6.js} +1 -1
  64. package/dist/lite/assets/{Shares-DYa-7p_E.js → Shares-CxJ5bbP4.js} +1 -1
  65. package/dist/lite/assets/{Shares-legacy-CD4V2Nkm.js → Shares-legacy-bRg_GWJc.js} +1 -1
  66. package/dist/lite/assets/{Storages-B0C3wLOw.js → Storages-CiA0_Ux3.js} +1 -1
  67. package/dist/lite/assets/{Storages-legacy-Hu3NLgcV.js → Storages-legacy-nNc5p2x6.js} +1 -1
  68. package/dist/lite/assets/{Upload-CujV1cl2.js → Upload-6mLh9vS_.js} +1 -1
  69. package/dist/lite/assets/{Upload-CoXrosgy.js → Upload-LroLcc--.js} +1 -1
  70. package/dist/lite/assets/{Upload-legacy-BrGogy7u.js → Upload-legacy-DzBqXsqi.js} +1 -1
  71. package/dist/lite/assets/{Upload-legacy-ipwT0CGa.js → Upload-legacy-YbbM49hO.js} +1 -1
  72. package/dist/lite/assets/{Users-CQMS_vRF.js → Users-Cebos0QK.js} +1 -1
  73. package/dist/lite/assets/{Users-legacy-CMqmVwDR.js → Users-legacy-D4Ji7uVA.js} +1 -1
  74. package/dist/lite/assets/{aliyun_video-BPU9Winc.js → aliyun_video-DMomVZ86.js} +1 -1
  75. package/dist/lite/assets/{aliyun_video-legacy-DqXKJ6bJ.js → aliyun_video-legacy-BVrXTQ7C.js} +1 -1
  76. package/dist/lite/assets/{archive-CFoJgIJg.js → archive-iaznZ7i5.js} +1 -1
  77. package/dist/lite/assets/{archive-legacy-CbLxcvcU.js → archive-legacy-BTi-FFWj.js} +1 -1
  78. package/dist/lite/assets/{artplayer-CKFboV1K.js → artplayer-GcZA8xWm.js} +1 -1
  79. package/dist/lite/assets/{artplayer-legacy-nsuIJ8X1.js → artplayer-legacy-0q8fSTli.js} +1 -1
  80. package/dist/lite/assets/{asciinema-Co15uYSl.js → asciinema-hP2thET0.js} +1 -1
  81. package/dist/lite/assets/{asciinema-legacy-cldShqIF.js → asciinema-legacy-HM3pomQn.js} +1 -1
  82. package/dist/lite/assets/{audio-DN7yh-1u.js → audio-CEdHvJQm.js} +1 -1
  83. package/dist/lite/assets/{audio-legacy-ZcTFmCaq.js → audio-legacy-Bf3rfImY.js} +1 -1
  84. package/dist/lite/assets/{backup-restore-CyTdjYa5.js → backup-restore-BI1XH72_.js} +1 -1
  85. package/dist/lite/assets/{backup-restore-legacy-4843qwpn.js → backup-restore-legacy-o4-z3xf2.js} +1 -1
  86. package/dist/lite/assets/{cg-BoXizs5U.js → cg-Cugc4PRy.js} +1 -1
  87. package/dist/lite/assets/{cg-legacy-B6dnZxHN.js → cg-legacy-en8-FR60.js} +1 -1
  88. package/dist/lite/assets/{doc-CwFJHCye.js → doc-Dx8w2-z-.js} +1 -1
  89. package/dist/lite/assets/{doc-legacy-BcqyYqI8.js → doc-legacy-Cirxey5M.js} +1 -1
  90. package/dist/lite/assets/{download-BWIL9ZbS.js → download-D5HXXjYD.js} +1 -1
  91. package/dist/lite/assets/{download-legacy-BRxDfnJM.js → download-legacy-BtfDXiWv.js} +1 -1
  92. package/dist/lite/assets/{flash-Do4k4HF4.js → flash-D3tyxPhf.js} +1 -1
  93. package/dist/lite/assets/{flash-legacy-Dth0lnEy.js → flash-legacy-C4GlbMx5.js} +1 -1
  94. package/dist/lite/assets/{heic-BQ1sxr--.js → heic-DddGOj_0.js} +1 -1
  95. package/dist/lite/assets/{heic-legacy-D7C3AFkl.js → heic-legacy-B6Y5cyvF.js} +1 -1
  96. package/dist/lite/assets/{helper-COm3HMuR.js → helper-DZTPC0ym.js} +1 -1
  97. package/dist/lite/assets/{helper-CW89pSnh.js → helper-DcuvUci3.js} +1 -1
  98. package/dist/lite/assets/{helper-legacy-CRIrgp8-.js → helper-legacy-Cuhr9yhF.js} +1 -1
  99. package/dist/lite/assets/{helper-legacy-CmC0lRkW.js → helper-legacy-qY9yuzKw.js} +1 -1
  100. package/dist/lite/assets/{html-BH-siIo1.js → html-TrHlpF58.js} +1 -1
  101. package/dist/lite/assets/{html-legacy-C6F-KW6p.js → html-legacy-RtqGGa31.js} +1 -1
  102. package/dist/lite/assets/{icon-I31eZk5I.js → icon-TcP3LdUy.js} +1 -1
  103. package/dist/lite/assets/{icon-legacy-Cmi1b15o.js → icon-legacy-CCjPA35g.js} +1 -1
  104. package/dist/lite/assets/{im-32Y5iioc.js → im-Bfh3t-9k.js} +1 -1
  105. package/dist/lite/assets/{im-legacy-CuBPXwQP.js → im-legacy-bfeqh7q-.js} +1 -1
  106. package/dist/lite/assets/{image-Cn7F3i7p.js → image-CHfw1saX.js} +1 -1
  107. package/dist/lite/assets/{image-legacy-BdZBZ4I3.js → image-legacy-FyBUH0Wv.js} +1 -1
  108. package/dist/lite/assets/{index-BdrlLL7h.js → index-Do6wV20T.js} +4 -4
  109. package/dist/lite/assets/{index-legacy-DVVw2Tdl.js → index-legacy-DX8ZPqos.js} +1 -1
  110. package/dist/lite/assets/{index_page-CI4452wz.js → index_page-Ci6zIIEm.js} +1 -1
  111. package/dist/lite/assets/{index_page-legacy-DpZgbky_.js → index_page-legacy-Dia6n6V8.js} +1 -1
  112. package/dist/lite/assets/{info-4RJdJqGX.js → info-Eur0D5WL.js} +1 -1
  113. package/dist/lite/assets/{info-legacy-D81BT5je.js → info-legacy-DSnpfN_T.js} +1 -1
  114. package/dist/lite/assets/{ipa-BRMsKQrP.js → ipa-QQId27CM.js} +1 -1
  115. package/dist/lite/assets/{ipa-legacy-DxYHqNRr.js → ipa-legacy-Dk-qFvQl.js} +1 -1
  116. package/dist/lite/assets/{login-DSgwb8b8.js → login-DNWEpAg4.js} +1 -1
  117. package/dist/lite/assets/{login-legacy-CE4m2hrW.js → login-legacy-X5eqwtmJ.js} +1 -1
  118. package/dist/lite/assets/{manage-Bn2g6-4u.js → manage-BoJn00at.js} +2 -2
  119. package/dist/lite/assets/{manage-legacy-Ctq_PlSk.js → manage-legacy-BWRpx6eL.js} +1 -1
  120. package/dist/lite/assets/markdown-BeLwer8m.js +1 -0
  121. package/dist/lite/assets/{markdown-legacy-SrX3ihxa.js → markdown-legacy-DqCEmWHU.js} +1 -1
  122. package/dist/lite/assets/{markdown_with_word_wrap-CTF7F6kA.js → markdown_with_word_wrap-Ck5Le6kt.js} +1 -1
  123. package/dist/lite/assets/{markdown_with_word_wrap-legacy-5S3gtO5K.js → markdown_with_word_wrap-legacy-B778apZq.js} +1 -1
  124. package/dist/lite/assets/{offline_download-DplxhzId.js → offline_download-BxvK9sas.js} +1 -1
  125. package/dist/lite/assets/{offline_download-legacy-D-fNKFYv.js → offline_download-legacy-Sn7LVNoj.js} +1 -1
  126. package/dist/lite/assets/{open-with-DB-thDwq.js → open-with-Dm0Xiltd.js} +1 -1
  127. package/dist/lite/assets/{open-with-legacy-BV0zWWih.js → open-with-legacy-CzqkMUrw.js} +1 -1
  128. package/dist/lite/assets/{operations-DUc1_ZG_.js → operations-DtIJGjr3.js} +1 -1
  129. package/dist/lite/assets/{operations-legacy-D7uRiFrF.js → operations-legacy-x4qCe3Nr.js} +1 -1
  130. package/dist/lite/assets/{plist-Bdtf7mmC.js → plist-I5MRvpO4.js} +1 -1
  131. package/dist/lite/assets/{plist-legacy-BUgj41A2.js → plist-legacy-BjlqWsae.js} +1 -1
  132. package/dist/lite/assets/polyfills-legacy-CY-LI3wc.js +1 -0
  133. package/dist/lite/assets/{ppt-legacy-CfobOD2q.js → ppt-legacy-BauMuKYT.js} +1 -1
  134. package/dist/lite/assets/{ppt-CQUs3gCH.js → ppt-sj6qWvel.js} +1 -1
  135. package/dist/lite/assets/{previews-ikRB1E3g.js → previews-C3V57ws2.js} +2 -2
  136. package/dist/lite/assets/{previews-legacy-BOyZeoEk.js → previews-legacy-C_1n4grk.js} +1 -1
  137. package/dist/lite/assets/{rehype-katex-PXUO2tmG.js → rehype-katex-fpXCKXq-.js} +1 -1
  138. package/dist/lite/assets/{rehype-katex-legacy-l00blOnq.js → rehype-katex-legacy-t-Y3uu45.js} +1 -1
  139. package/dist/lite/assets/{remark-math-B2pF2g5L.js → remark-math-DmyB6UtF.js} +1 -1
  140. package/dist/lite/assets/{remark-math-legacy-C2fL8O2-.js → remark-math-legacy-BxMiMhBe.js} +1 -1
  141. package/dist/lite/assets/{ri-BpBjk-eu.js → ri-Co752El1.js} +1 -1
  142. package/dist/lite/assets/{ri-legacy-DF_J6UvM.js → ri-legacy-C5_hBj57.js} +1 -1
  143. package/dist/lite/assets/{si-CExwmFBP.js → si-8vtL5WDZ.js} +1 -1
  144. package/dist/lite/assets/{si-legacy-CM4ZmTcr.js → si-legacy-CRNlhjOc.js} +1 -1
  145. package/dist/lite/assets/{solid-contextmenu-DNoyC52a.js → solid-contextmenu-Q14whW6u.js} +1 -1
  146. package/dist/lite/assets/{solid-contextmenu-legacy-DSVwqGw2.js → solid-contextmenu-legacy-sZs92FT7.js} +1 -1
  147. package/dist/lite/assets/{store-BgSFahAe.js → store-jmqpI8w9.js} +1 -1
  148. package/dist/lite/assets/{store-legacy-DEv5m7Se.js → store-legacy-CI1UFD5I.js} +1 -1
  149. package/dist/lite/assets/test-VgTEJWSX.js +1 -0
  150. package/dist/lite/assets/{test-legacy-CwP5y5rh.js → test-legacy-BRB5AFL9.js} +1 -1
  151. package/dist/lite/assets/{text-editor-CXH-M_d8.js → text-editor-DN-5m547.js} +1 -1
  152. package/dist/lite/assets/{text-editor-legacy-Bvg6h1LG.js → text-editor-legacy-DlNbA4NX.js} +1 -1
  153. package/dist/lite/assets/{ti-DorTQHjy.js → ti-CJTnvYDC.js} +1 -1
  154. package/dist/lite/assets/{ti-legacy-BLnieiZv.js → ti-legacy-C5F9deYz.js} +1 -1
  155. package/dist/lite/assets/{url-CrBOHT0m.js → url-Dc_ERS90.js} +1 -1
  156. package/dist/lite/assets/{url-legacy-BlD6ZzNt.js → url-legacy-DqRcH2qB.js} +1 -1
  157. package/dist/lite/assets/{video-2Qz8WbEM.js → video-CMVGTs9H.js} +1 -1
  158. package/dist/lite/assets/{video-legacy-CZofzk3c.js → video-legacy-CARCtj8A.js} +1 -1
  159. package/dist/lite/assets/{video360-DUQPJklE.js → video360-Cn4J_avk.js} +1 -1
  160. package/dist/lite/assets/{video360-legacy-t7FzLnsS.js → video360-legacy-QrceD6P2.js} +1 -1
  161. package/dist/lite/assets/{video_box-wwi7WLeT.js → video_box-BpjZ-ZST.js} +1 -1
  162. package/dist/lite/assets/{video_box-legacy-B4dnjnjL.js → video_box-legacy-DJTbgfFE.js} +1 -1
  163. package/dist/lite/assets/{vs-DQyKZ4nV.js → vs-D6iduhy9.js} +1 -1
  164. package/dist/lite/assets/{vs-legacy-Gzvbg9kw.js → vs-legacy-HDoHHJI2.js} +1 -1
  165. package/dist/lite/assets/{xls-UBX1oyWL.js → xls-B0hoyRio.js} +1 -1
  166. package/dist/lite/assets/{xls-legacy-BTO_I1zz.js → xls-legacy-B5QjbgBE.js} +1 -1
  167. package/dist/lite/i18n.tar.gz +0 -0
  168. package/dist/lite/index.html +2 -2
  169. package/package.json +1 -1
  170. package/dist/assets/polyfills-legacy-3zNmgeF1.js +0 -1
  171. package/dist/lite/assets/Common-GRQCAwrU.js +0 -1
  172. package/dist/lite/assets/Common-legacy-eXCYBqpA.js +0 -1
  173. package/dist/lite/assets/markdown-BDzlyh3V.js +0 -1
  174. package/dist/lite/assets/polyfills-legacy-D9TUrbOt.js +0 -1
  175. package/dist/lite/assets/test-Bp2AX12i.js +0 -1
@@ -1 +1 @@
1
- System.register(["./chunk-legacy-D5ZT36tR.js","./store-legacy-DEv5m7Se.js"],function(t,e){var s,i,r,n,a,o,l,d,h,c,u,f,g,m,p,v,y,E,T,S,A,L,I,b,R,k,D,w,P,_,C,x,M,O,F,$,N,U,B,G,K,V,H,W,Y,j,q,z,X,Q,Z,J,tt,et,st,it,rt,nt,at,ot,lt,dt,ht,ct,ut,ft,gt,mt,pt,vt,yt,Et,Tt,St,At,Lt,It,bt,Rt,kt,Dt,wt,Pt,_t,Ct,xt,Mt,Ot,Ft,$t,Nt,Ut,Bt,Gt,Kt,Vt,Ht,Wt,Yt,jt,qt,zt,Xt,Qt,Zt,Jt,te,ee,se,ie,re,ne,ae,oe,le,de,he,ce,ue,fe,ge,me,pe,ve,ye,Ee,Te,Se,Ae,Le,Ie,be,Re,ke,De,we,Pe,_e,Ce,xe,Me,Oe,Fe,$e,Ne,Ue,Be,Ge,Ke,Ve,He,We,Ye,je,qe,ze,Xe,Qe,Ze,Je,ts,es,ss,is,rs,ns,as,os,ls,ds,hs,cs,us,fs,gs,ms,ps,vs,ys,Es,Ts,Ss,As,Ls,Is,bs,Rs,ks,Ds,ws,Ps,_s,Cs,xs,Ms,Os,Fs,$s,Ns,Us,Bs,Gs,Ks,Vs,Hs,Ws,Ys,js,qs,zs,Xs,Qs,Zs,Js,ti,ei,si,ii,ri,ni,ai,oi,li,di,hi,ci,ui,fi,gi,mi,pi,vi,yi,Ei,Ti,Si,Ai,Li,Ii,bi,Ri,ki,Di,wi,Pi,_i,Ci,xi,Mi,Oi,Fi,$i,Ni,Ui,Bi,Gi,Ki,Vi,Hi,Wi,Yi,ji,qi,zi;function Xi(t){switch(t){case 1:case 2:case 3:default:return 0;case 4:return 2;case 5:return 1}}function Qi(t){if("string"!=typeof t)return[];const e=t.matchAll(/<d[^>]*?p="(?<p>[^"]+)"[^>]*>(?<text>.*?)<\/d>/gs);return Array.from(e).map(t=>{const e=t.groups.p.split(",");return e.length>=8?{text:t.groups.text.trim().replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&"),time:Number(e[0]),mode:Xi(Number(e[1])),fontSize:Number(e[2]),color:`#${Number(e[3]).toString(16)}`,timestamp:Number(e[4]),pool:Number(e[5]),userID:e[6],rowID:Number(e[7])}:null}).filter(Boolean)}function Zi({data:t}){const{xml:e,id:s}=t;if(!s||!e)return;const i=Qi(e);globalThis.postMessage({danmus:i,id:s})}function Ji(){const t=`\n ${Xi.toString()}\n ${Qi.toString()}\n onmessage = ${Zi.toString()}\n `,e=new Blob([t],{type:"application/javascript"});return new Worker(URL.createObjectURL(e))}function tr(t){let e;try{if(e=o&&(self.URL||self.webkitURL).createObjectURL(o),!e)throw"";const s=new Worker(e,{type:"module",name:t?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),s}catch(s){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(a),{type:"module",name:t?.name})}}function er(t,e,s){const{query:i}=t.constructor.utils;t.controls.add({name:"heatmap",position:"top",html:"",style:{position:"absolute",top:"-100px",left:"0px",right:"0px",height:"100px",width:"100%",pointerEvents:"none"},mounted(r){let n=null,a=null;function o(o=[]){if(n=null,a=null,r.innerHTML="",!t.duration||t.option.isLive)return;const l={w:r.offsetWidth,h:r.offsetHeight},h={xMin:0,xMax:l.w,yMin:0,yMax:128,scale:.25,opacity:.2,minHeight:Math.floor(.05*l.h),sampling:Math.floor(l.w/100),smoothing:.2,flattening:.2};"object"==typeof s&&Object.assign(h,s);let c=[];if(Array.isArray(o)&&o.length)c=[...o];else{const s=t.duration/l.w;for(let t=0;t<=l.w;t+=h.sampling){const i=e.queue.filter(({time:e})=>e>t*s&&e<=(t+h.sampling)*s).length;c.push([t,i])}}if(0===c.length)return;const u=c[c.length-1],f=u[0],g=u[1];f!==l.w&&c.push([l.w,g]);const m=c.map(t=>t[1]),p=(Math.min(...m)+Math.max(...m))/2;for(let t=0;t<c.length;t++){const e=c[t],s=e[1];e[1]=s*(s>p?1+h.scale:1-h.scale)+h.minHeight}const v=(t,e,s,i)=>{const r=function(t,e){const s=e[0]-t[0],i=e[1]-t[1];return{length:Math.sqrt(s**2+i**2),angle:Math.atan2(i,s)}}(e||t,s||t),n=d.map(Math.cos(r.angle)*h.flattening,0,1,1,0),a=r.angle*n+(i?Math.PI:0),o=r.length*h.smoothing;return[t[0]+Math.cos(a)*o,t[1]+Math.sin(a)*o]},y=c.map(t=>[d.map(t[0],h.xMin,h.xMax,0,l.w),d.map(t[1],h.yMin,h.yMax,l.h,0)]).reduce((t,e,s,i)=>0===s?`M ${i[i.length-1][0]},${l.h} L ${e[0]},${l.h} L ${e[0]},${e[1]}`:`${t} ${((t,e,s)=>{const i=v(s[e-1],s[e-2],t),r=v(t,s[e-1],s[e+1],!0),n=e===s.length-1?" z":"";return`C ${i[0]},${i[1]} ${r[0]},${r[1]} ${t[0]},${t[1]}${n}`})(e,s,i)}`,"");r.innerHTML=`\n <svg viewBox="0 0 ${l.w} ${l.h}">\n <defs>\n <linearGradient id="heatmap-solids" x1="0%" y1="0%" x2="100%" y2="0%">\n <stop offset="0%" style="stop-color:var(--art-theme);stop-opacity:${h.opacity}" />\n <stop offset="0%" style="stop-color:var(--art-theme);stop-opacity:${h.opacity}" id="heatmap-start" />\n <stop offset="0%" style="stop-color:var(--art-progress-color);stop-opacity:1" id="heatmap-stop" />\n <stop offset="100%" style="stop-color:var(--art-progress-color);stop-opacity:1" />\n </linearGradient>\n </defs>\n <path fill="url(#heatmap-solids)" d="${y}"></path>\n </svg>\n `,n=i("#heatmap-start",r),a=i("#heatmap-stop",r),n.setAttribute("offset",100*t.played+"%"),a.setAttribute("offset",100*t.played+"%")}t.on("video:timeupdate",()=>{n&&a&&(n.setAttribute("offset",100*t.played+"%"),a.setAttribute("offset",100*t.played+"%"))}),t.on("setBar",(t,e)=>{n&&a&&"played"===t&&(n.setAttribute("offset",100*e+"%"),a.setAttribute("offset",100*e+"%"))}),t.on("ready",()=>o()),t.on("resize",()=>o()),t.on("artplayerPluginDanmuku:loaded",()=>o()),t.on("artplayerPluginDanmuku:points",t=>o(t))}})}function sr(t){return e=>{const s=new l(e,t),i=new A(e,s);return s.option.heatmap&&er(e,s,s.option.heatmap),{name:"artplayerPluginDanmuku",emit:s.emit.bind(s),load:s.load.bind(s),config:s.config.bind(s),hide:s.hide.bind(s),show:s.show.bind(s),reset:s.reset.bind(s),mount:i.mount.bind(i),get option(){return s.option},get isHide(){return s.isHide},get isStop(){return s.isStop}}}}function ir(t){return function(t){return/^https?:\/\//.test(t)}(t)?t:new URL(t,document.baseURI).toString()}function rr({workerUrl:t,wasmUrl:e}){return new Promise(s=>{fetch(t).then(t=>t.text()).then(i=>{let r=i;r=r.replace(/wasmBinaryFile\s*=\s*"(subtitles-octopus-worker\.wasm)"/g,(s,i)=>`wasmBinaryFile = "${e=e?ir(e):new URL(i,ir(t)).toString()}"`);const n=new Blob([r],{type:"text/javascript"});s(URL.createObjectURL(n))})})}function nr(t){_.canvasParent&&(_.canvasParent.style.display=t?"block":"none")}function ar(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function or(){return or=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var i in s)({}).hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},or.apply(null,arguments)}function lr(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),s.push.apply(s,i)}return s}function dr(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?lr(Object(s),!0).forEach(function(e){ar(t,e,s[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):lr(Object(s)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))})}return t}function hr(){return or({},H)}function cr(t,e,s){return e[t]?e[t].bind(e):function(t,e){const s=self.console[t];return s?s.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):V}(t,s)}function ur(t=!0){if("undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function fr(t,e){const s=Object.keys(t),i=Object.keys(e),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(t=>-1===i.indexOf(t))}function gr(t,e=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(t);if(e){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"")}const s=t.length;let i,r,n,a="",o=0;for(;o<s;){if(i=t[o++],0===i&&e)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=t[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=t[o++],n=t[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&n)}}return a}function mr(t){let e="";for(let s=0;s<t.length;s++){let i=t[s].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function pr(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function vr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function yr(t){return"initSegment"!==t.sn}function Er(t,e){const s=Object.getPrototypeOf(t);if(s){const t=Object.getOwnPropertyDescriptor(s,e);return t||Er(s,e)}}function Tr(t,e){const s=Er(t,e);s&&(s.enumerable=!0,Object.defineProperty(t,e,s))}function Sr(t){return String.fromCharCode.apply(null,t)}function Ar(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function Lr(t,e){const s=br(t,e);return s<0?4294967296+s:s}function Ir(t,e){let s=Lr(t,e);return s*=Math.pow(2,32),s+=Lr(t,e+4),s}function br(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Rr(t,e){const s=[];if(!e.length)return s;const i=t.byteLength;for(let r=0;r<i;){const n=Lr(t,r),a=n>1?r+n:i;if(Sr(t.subarray(r+4,r+8))===e[0])if(1===e.length)s.push(t.subarray(r+8,a));else{const i=Rr(t.subarray(r+8,a),e.slice(1));i.length&&st.apply(s,i)}r=a}return s}function kr(t){const e=[],s=t[0];let i=8;const r=Lr(t,i);i+=4;let n=0,a=0;0===s?(n=Lr(t,i),a=Lr(t,i+4),i+=8):(n=Ir(t,i),a=Ir(t,i+8),i+=16),i+=2;let o=t.length+a;const l=Ar(t,i);i+=2;for(let d=0;d<l;d++){let s=i;const n=Lr(t,s);s+=4;const a=2147483647&n;if((2147483648&n)>>>31==1)return Y.warn("SIDX has hierarchical references (not supported)"),null;const l=Lr(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function Dr(t){const e=[],s=Rr(t,["moov","trak"]);for(let i=0;i<s.length;i++){const t=s[i],r=Rr(t,["tkhd"])[0];if(r){let s=r[0];const i=Lr(r,0===s?12:20),n=Rr(t,["mdia","mdhd"])[0];if(n){s=n[0];const r=Lr(n,0===s?12:20),a=Rr(t,["mdia","hdlr"])[0];if(a){const s=Sr(a.subarray(8,12)),n={soun:Q.AUDIO,vide:Q.VIDEO}[s],o=wr(Rr(t,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:r,type:n,stsd:o},e[n]=dr({timescale:r,id:i},o)):e[i]={timescale:r,type:s,stsd:o}}}}}return Rr(t,["moov","mvex","trex"]).forEach(t=>{const s=e[Lr(t,4)];s&&(s.default={duration:Lr(t,12),flags:Lr(t,20)})}),e}function wr(t){const e=t.subarray(8),s=e.subarray(86),i=Sr(e.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;a&&Rr(Rr(e,[i])[0].subarray("enca"===i?28:78),["sinf"]).forEach(t=>{const e=Rr(t,["schm"])[0];if(e){const s=Sr(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=Rr(t,["frma"])[0];e&&(n=Sr(e))}}});const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Rr(s,["avcC"])[0];t&&t.length>3&&(n+="."+Cr(t[1])+Cr(t[2])+Cr(t[3]),r=Pr("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const t=Rr(e,[i])[0],s=Rr(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=_r(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=_r(s,t);const i=s[t++];if(64!==i)break;if(n+="."+Cr(i),t+=12,5!==s[t++])break;t=_r(s,t);const r=s[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=Rr(s,["hvcC"])[0];if(t&&t.length>12){const e=t[1],s=["","A","B","C"][e>>6],i=31&e,r=Lr(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+s+i,n+="."+function(t){let e=0;for(let s=0;s<32;s++)e|=(t>>s&1)<<31-s;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];(e||d)&&(d="."+e.toString(16).toUpperCase()+d)}n+=d}r=Pr("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Pr(n,s)||n;break;case"vp09":{const t=Rr(s,["vpcC"])[0];if(t&&t.length>6){const e=t[4],s=t[5],i=t[6]>>4&15;n+="."+xr(e)+"."+xr(s)+"."+xr(i)}break}case"av01":{const t=Rr(s,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2];n+="."+e+"."+xr(i)+a+"."+xr(d)+"."+h+"."+c+u+f+"."+xr(1)+"."+xr(1)+"."+xr(1)+".0",r=Pr("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function Pr(t,e){const s=Rr(e,["dvvC"]),i=s.length?s[0]:Rr(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return t+"."+xr(e)+"."+xr(s)}}function _r(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function Cr(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function xr(t){return(t<10?"0":"")+t}function Mr(t,e){Rr(t,["moov","trak"]).forEach(t=>{const s=Rr(t,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=Rr(i,["enca"]);const n=r.length>0;n||(r=Rr(i,["encv"])),r.forEach(t=>{Rr(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const s=Or(t);s&&e(s,n)})})})}function Or(t){const e=Rr(t,["schm"])[0];if(e){const s=Sr(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=Rr(t,["schi","tenc"])[0];if(e)return e}}}function Fr(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function $r(t,e){const s=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return Rr(i,["moof"]).map(o=>{const l=o.byteOffset-8;Rr(o,["traf"]).map(o=>{const d=Rr(o,["tfdt"]).map(t=>{const e=t[0];let s=Lr(t,4);return 1===e&&(s*=Math.pow(2,32),s+=Lr(t,8)),s/r})[0];return void 0!==d&&(t=d),Rr(o,["tfhd"]).map(d=>{const h=Lr(d,4),c=16777215&Lr(d,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;h===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=Lr(d,p),p+=4),f&&(g=Lr(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=Nr(e.codec)),Rr(o,["trun"]).map(n=>{const o=n[0],d=16777215&Lr(n,0),h=!!(1&d);let c=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const A=Lr(n,4);let L=8;h&&(c=Lr(n,L),L+=4),f&&(L+=4);let I=c+l;for(let l=0;l<A;l++){if(m?(p=Lr(n,L),L+=4):p=u,v?(y=Lr(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?Lr(n,L):br(n,L),L+=4),e.type===Q.VIDEO){let e=0;for(;e<y;){const n=Lr(i,I);I+=4,Ur(a,i[I])&&Br(i.subarray(I,I+n),a?2:1,t+S/r,s),I+=n,e+=n+4}}t+=p/r}}))})})}),s}function Nr(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Ur(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6==(31&e)}function Br(t,e,s,i){const r=Gr(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){Y.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Ar(r,e);if(e+=2,49===t){const t=Lr(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=r[e++]}i.push({type:t,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let s=0;s<n;s++)l[s]=r[e++];i.push({payloadType:a,pts:s,uuid:t.join(""),userData:gr(l),userDataBytes:l})}}}function Gr(t){const e=t.byteLength,s=[];let i=1;for(;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return t;const r=e-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=t[a];return n}function Kr(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,s)}function Vr(t){const e=t.getUint32(0),s=t.byteOffset,i=t.byteLength;if(i<e)return{offset:s,size:i};if(1886614376!==t.getUint32(4))return{offset:s,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=mr(new Uint8Array(n,s+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=t.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,s+32+16*t,16));d=32+16*r}if(!d)return{offset:s,size:e};const h=t.getUint32(d);return e-32<h?{offset:s,size:e}:(l=new Uint8Array(n,s+d+4,h),{version:r,systemId:a,kids:o,data:l,offset:s,size:e})}function Hr(t,e){const s=nt[e];return!!s&&!!s[t.slice(0,4)]}function Wr(t,e,s=!0){return!t.split(",").some(t=>!Yr(t,e,s))}function Yr(t,e,s=!0){var i;const r=ur(s);return null!=(i=null==r?void 0:r.isTypeSupported(jr(t,e)))&&i}function jr(t,e){return`${e}/mp4;codecs=${t}`}function qr(t){if(t){const e=t.substring(0,4);return nt.video[e]}return 2}function zr(t){const e=rt();return t.split(",").reduce((t,s)=>{const i=e&&Nr(s)?9:nt.video[s];return i?(2*i+t)/(t?3:2):(nt.audio[s]+t)/(t?2:1)},0)}function Xr(t,e=!0){return t.replace(ot,t=>function(t,e=!0){if(at[t])return at[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<s.length;r++){var i;if(Yr(s[r],"audio",e))return at[t]=s[r],s[r];if("mp3"===s[r]&&null!=(i=ur(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function Qr(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Zr(t,"audio")||Zr(t,"video")))return t;if(e){const s=e.split(",");if(s.length>1){if(t)for(let e=s.length;e--;)if(s[e].substring(0,4)===t.substring(0,4))return s[e];return s[0]}}return e||t}function Zr(t,e){return Hr(t,e)&&Yr(t,e)}function Jr(t){if(t.startsWith("av01.")){const e=t.split("."),s=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=s[t-4];return e.join(".")}return t}function tn(t){const e=ur(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function en(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function sn(t,e){return{supported:!1,configurations:e,decodingInfoResults:[lt],error:t}}function rn(t,e,s,i,r,n){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,h=d?parseInt(d):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(e=>{t[e]=(t[e]||0)+i.channels[e]})}return t},{2:0})}catch(u){return!0}return void 0!==a&&(a.split(",").some(t=>Nr(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!c&&C(h)&&Object.keys(c).some(t=>parseInt(t)>h)}function nn(t,e,s,i={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!s)return Promise.resolve(dt);const n=[],a=function(t){var e;const s=null==(e=t.videoCodec)?void 0:e.split(","),i=on(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return s?s.map(t=>{const e={contentType:jr(Jr(t),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,s){var i;const r=null==(i=t.audioCodec)?void 0:i.split(","),n=on(t);return r&&t.audioGroups?t.audioGroups.reduce((t,i)=>{var a;const o=i?null==(a=e.groups[i])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===i){const i=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:jr(e,"audio"),bitrate:s?an(e,n):n};i&&(r.channels=""+i),t.push(r)})}return t},t):t},[]):[]}(t,e,o>0),d=l.length;for(let h=o||1*d||1;h--;){const t={type:"media-source"};if(o&&(t.video=a[h%o]),d){t.audio=l[h%d];const e=t.audio.bitrate;t.video&&e&&(t.video.bitrate-=e)}n.push(t)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>Nr(t))&&rt())return Promise.resolve(sn(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:s,video:i}=t;return i&&(e+=`${en(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`),s&&(e+=`${i?"_":""}${en(s.contentType)}_c${s.channels}`),e}(t);return i[e]||(i[e]=s.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function an(t,e){if(e<=1)return 1;let s=128e3;return"ec-3"===t?s=768e3:"ac-3"===t&&(s=64e4),Math.min(e/2,s)}function on(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function ln(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i<e/2?s?ut.v2:ut.Yes:ut.No}function dn(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function hn(t,e){let s=!1,i=[];if(t&&(s="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||ct.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;s=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}function cn(t,e){Y.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function un(t){return t.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function fn(t){if(!t)return t;const{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}=t;return{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function gn(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i<e.length;i++)if(mn(t,e[i],s))return i;return-1}function mn(t,e,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===i||e.groupId===i)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){return t.length===e.length?t===e:t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const s=t.split(","),i=e.split(",");return s.length===i.length&&!s.some(t=>-1===i.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===s||s(t,e))}function pn(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function vn(t,e,s){for(let i=e;i>-1;i--)if(s(t[i]))return i;for(let i=e+1;i<t.length;i++)if(s(t[i]))return i;return-1}function yn(t,e){var s;return!!t&&t!==(null==(s=e.loadLevelObj)?void 0:s.uri)}function En(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Tn(s,i,n)||function(t,e,s){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=yt.search(e,Tn.bind(null,s,i));return!a||a===t&&n?n:a}function Tn(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function Sn(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}function An(t,e,s){if(t&&t.startCC<=e&&t.endCC>=e){let i=t.fragments;const{fragmentHint:r}=t;let n;return r&&(i=i.concat(r)),yt.search(i,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=s?1:t.start>s?-1:0)),n||null}return null}function Ln(t){switch(t.details){case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_TIMEOUT:case F.LEVEL_LOAD_TIMEOUT:case F.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function In(t){return t.details.startsWith("key")}function bn(t){return In(t)&&!!t.frag&&!t.frag.decryptdata}function Rn(t,e){const s=Ln(e);return t.default[(s?"timeout":"error")+"Retry"]}function kn(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function Dn(t){return dr(dr({},t),{errorRetry:null,timeoutRetry:null})}function wn(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return Pn(t)||!!t&&(t<400||t>499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}function Pn(t){return 0===t&&!1===navigator.onLine}function _n(t){const e={action:Et.DoNothing,flags:Tt.None};return t&&(e.resolved=!0),e}function Cn(t){var e,s,i;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(s=t.range.audio)&&s.partial||null!=(i=t.range.audiovideo)&&i.partial)}function xn(t){return`${t.type}_${t.level}_${t.sn}`}function Mn(t,e){return t.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}function On(t,e=null){const s=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(C(r)&&C(n)){var a;let e=r,s=n;if("initSegment"===t.sn&&("AES-128"===(o=null==(a=t.decryptdata)?void 0:a.method)||"AES-256"===o)){const t=n-r;t%16&&(s=n+(16-t%16)),0!==r&&(i.resetIV=!0,e=r-16)}i.rangeStart=e,i.rangeEnd=s}var o;return i}function Fn(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:O.MEDIA_ERROR,details:F.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new _t(i)}function $n(t){return Ft.test(t)}function Nn(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(Ft,e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r})}return e}function Un(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(a){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Bn(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function Gn(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function Kn(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}function Vn(t,e){return t.length===e.length&&!t.some((t,s)=>t!==e[s])}function Hn(t,e){return!t&&!e||!(!t||!e)&&Vn(t,e)}function Wn(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Yn(t){switch(t){case"AES-128":case"AES-256":return It.cbc;case"AES-256-CTR":return It.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function jn(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function qn(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function zn(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function Xn(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=jn(r)):s=function(t){const e=qn(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}function Qn(t){switch(t){case Ht.FAIRPLAY:return Vt.FAIRPLAY;case Ht.PLAYREADY:return Vt.PLAYREADY;case Ht.WIDEVINE:return Vt.WIDEVINE;case Ht.CLEARKEY:return Vt.CLEARKEY}}function Zn(t){switch(t){case Vt.FAIRPLAY:return Ht.FAIRPLAY;case Vt.PLAYREADY:return Ht.PLAYREADY;case Vt.WIDEVINE:return Ht.WIDEVINE;case Vt.CLEARKEY:return Ht.CLEARKEY}}function Jn(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[Vt.FAIRPLAY,Vt.WIDEVINE,Vt.PLAYREADY,Vt.CLEARKEY].filter(t=>!!e[t]):[];return!i[Vt.WIDEVINE]&&s&&i.push(Vt.WIDEVINE),i}function ta(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),s=String.fromCharCode.apply(null,Array.from(e)),i=s.substring(s.indexOf("<"),s.length),r=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=jn(t).subarray(0,16);return zn(e),e}}return null}function ea(t){const e=null==t?void 0:t[Ht.PLAYREADY];if(e){const t=Xn(e.uri);if(t)return ta(t)}return null}function sa(t,e){let s=t.length;if(!s){if(!e.hasProgramDateTime)return;{const i=e.fragments[e.fragments.length-1];t.push(i),s++}}const i=t[s-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=t[i])?void 0:a.sn)<e.startSN)break;const s=ia(e,d,t,i,r);if(-1!==s){l.tagAnchor=e.fragments[s].ref;break}}}}function ia(t,e,s,i,r){const n=s[i];if(n){const o=n.programDateTime;var a;if((e>=o||0===i)&&e<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-t.startSN;if(r<0)return-1;const n=t.fragments;if(n.length>s.length)for(let a=(s[i+1]||n[n.length-1]).sn-t.startSN;a>r;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}return r}}return-1}function ra(t,e,s){var i,r;const n=new Ut(t,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(r=n.KEYFORMAT)?r:"identity";return o&&n.IV&&!l&&Y.error(`Invalid IV: ${n.IV}`),new jt(a,o?Jt.resolve(o,e):"",h,(d||"1").split("/").map(Number).filter(Number.isFinite),l,n.KEYID)}function na(t){const e=new Ut(t).decimalFloatingPoint("TIME-OFFSET");return C(e)?e:null}function aa(t,e){let s=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const i=s.filter(e=>Hr(e,t));i.length&&(e[`${t}Codec`]=i.map(t=>t.split("/")[0]).join(","),s=s.filter(t=>-1===i.indexOf(t)))}),e.unknownCodecs=s}function oa(t,e,s){const i=e[s];i&&(t[s]=i)}function la(t,e,s){t.rawProgramDateTime?s.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function da(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function ha(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||i.push(t)}function ca(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${s[0]})`)}function ua(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${s[0]})`)}function fa(t,e){const s=e.startPTS;if(C(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&i.setDuration(r)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration):e.setStart(Math.max(t.start-e.duration,0))}function ga(t,e,s,i,r,n,a){i-s<=0&&(a.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let o=s,l=i;const d=e.startPTS,h=e.endPTS;if(C(d)){const c=Math.abs(d-s);t&&c>t.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${e.level} ${t.url}`):C(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,o=Math.max(s,d),s=Math.min(s,d),r=void 0!==e.startDTS?Math.min(r,e.startDTS):r,l=Math.min(i,h),i=Math.max(i,h),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}const c=s-e.start;0!==e.start&&e.setStart(s),e.setDuration(i-e.start),e.startPTS=s,e.maxStartPTS=o,e.startDTS=r,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let f;const g=u-t.startSN,m=t.fragments;for(m[g]=e,f=g;f>0;f--)fa(m[f],m[f-1]);for(f=g;f<m.length-1;f++)fa(m[f],m[f+1]);return t.fragmentHint&&fa(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function ma(t,e,s){if(t===e)return;let i=null;const r=t.fragments;for(let h=r.length-1;h>=0;h--){const t=r[h].initSegment;if(t){i=t;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,s){const i=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let d=r;d<=n;d++){const r=l[a+d];let n=o[d];if(i&&!n&&r&&(n=e.fragments[d]=r),r&&n){s(r,n,d,o);const i=r.relurl,a=n.relurl;if(i&&Ia(i,a))return void(e.playlistParsingError=pa(`media sequence mismatch ${n.sn}:`,t,e,0,n));if(r.cc!==n.cc)return void(e.playlistParsingError=pa(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,t,e,0,n))}}}(t,e,(t,s,r,a)=>{if((!e.startCC||e.skippedSegments)&&s.cc!==t.cc){const i=t.cc-s.cc;for(let t=r;t<a.length;t++)a[t].cc+=i;e.endCC=a[a.length-1].cc}C(t.startPTS)&&C(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(n=s),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,i=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const{dateRanges:i,recentlyRemovedDateranges:r}=e,n=or({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;return a?(Object.keys(i).forEach(t=>{const e=n[t],r=new Bt(i[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${pt(i[t].attr)}"`)}),n):i}(t.dateRanges,e,s));const i=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&la(o[t],o[t-1],i);sa(i,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const s=Ta(t,e.startSN-1);e.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}!function(t,e,s){if(t&&e){let i=0;for(let r=0,n=t.length;r<=n;r++){const n=t[r],a=e[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),n?ga(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):va(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const t=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=t),e.driftEndTime=d,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function pa(t,e,s,i,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function va(t,e,s=!0){const i=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&s)a=t.fragmentStart+i*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}ya(e,a)}function ya(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i<s.length;i++)s[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function Ea(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments;if(i.length&&4*s>e){const t=1e3*i[i.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}function Ta(t,e,s){if(!t)return null;let i=t.fragments[e-t.startSN];return i||(i=t.fragmentHint,i&&i.sn===e?i:e<t.startSN&&s&&s.sn===e?s:null)}function Sa(t,e,s){return t?Aa(t.partList,e,s):null}function Aa(t,e,s){if(t)for(let i=t.length;i--;){const r=t[i];if(r.index===s&&r.fragment.sn===e)return r}return null}function La(t){t.forEach((t,e)=>{var s;null==(s=t.details)||s.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function Ia(t,e){return!(t===e||!e)&&ba(t)!==ba(e)}function ba(t){return t.replace(/\?[^?]*$/,"")}function Ra(t,e){for(let i=0,r=t.length;i<r;i++){var s;if((null==(s=t[i])?void 0:s.cc)===e)return t[i]}return null}function ka(t,e){const s=t.start+e;t.startPTS=s,t.setStart(s),t.endPTS=s+t.duration}function Da(t,e){const s=e.fragments;for(let i=0,r=s.length;i<r;i++)ka(s[i],t);e.fragmentHint&&ka(e.fragmentHint,t),e.alignedSliding=!0}function wa(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const s=Math.min(e.endCC,t.endCC),i=Ra(e.fragments,s),r=Ra(t.fragments,s);i&&r&&(Y.log(`Aligning playlist at start of dicontinuity sequence ${s}`),Da(i.start-r.start,t))}function Pa(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=Ra(i,a),n=Ra(s,a)),r&&n||(r=i[Math.floor(i.length/2)],n=Ra(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;o&&l&&Da((l-o)/1e3-(n.start-r.start),t)}function _a(t,e,s){Ca(t,e,s),t.addEventListener(e,s)}function Ca(t,e,s){t.removeEventListener(e,s)}function xa(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}function Ma(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Oa(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Fa(t,e){let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s}function $a(t,e){const s=e;let i=0;for(;Oa(t,e);)i+=10,i+=Fa(t,e+6),Ma(t,e+10)&&(i+=10),e+=i;if(i>0)return t.subarray(s,s+i)}function Na(t,e){return 255===t[e]&&240==(246&t[e+1])}function Ua(t,e){return 1&t[e+1]?7:9}function Ba(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Ga(t,e){return e+1<t.length&&Na(t,e)}function Ka(t,e){if(Ga(t,e)){const s=Ua(t,e);if(e+s>=t.length)return!1;const i=Ba(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||Ga(t,r)}return!1}function Va(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){const r=e[s+2],n=r>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit($.ERROR,$.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[s+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h=n;5!==a&&29!==a||(h-=3);const c=[a<<3|(14&h)>>1,(1&h)<<7|o<<3];return Y.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(e,s,i,r);if(!n)return;or(t,n)}}function Ha(t){return 9216e4/t}function Wa(t,e,s,i,r){const n=i+r*Ha(t.samplerate),a=function(t,e){const s=Ua(t,e);if(e+s<=t.length){const i=Ba(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,d=Math.max(0,s+l-e.length);d?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,s+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-s;return o=new Uint8Array(l),o.set(e.subarray(s,e.length),0),{sample:{unit:o,pts:n},length:l,missing:-1}}function Ya(t,e){return Oa(t,e)&&Fa(t,e+6)+10<=t.length-e}function ja(t,e=0,s=1/0){return function(t,e,s,i){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=(h=t)&&h.buffer instanceof ArrayBuffer&&void 0!==h.byteLength&&void 0!==h.byteOffset?t.byteOffset:0,o=(a+t.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o)));var h;return new i(r,d,Math.floor(Math.min(d+Math.max(s,0),o))-d)}(t,e,s,Uint8Array)}function qa(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=t.data.subarray(1).indexOf(0);if(-1===s)return;const i=gr(ja(t.data,1,s)),r=t.data[2+s],n=t.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=gr(ja(t.data,3+s,n));let o;return o="--\x3e"===i?gr(ja(t.data,4+s+n)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=a,e.data=o,e}function za(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=gr(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=gr(t.data.subarray(e),!0);e+=s.length+1;const i=gr(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=gr(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?qa(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=gr(t.data.subarray(e),!0);e+=s.length+1;const i=gr(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=gr(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function Xa(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=Fa(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}}function Qa(t){let e=0;const s=[];for(;Oa(t,e);){const i=Fa(t,e+6);t[e+5]>>6&1&&(e+=de),e+=de;const r=e+i;for(;e+he<r;){const i=Xa(t.subarray(e)),r=za(i);r&&s.push(r),e+=i.size+de}Ma(t,e)&&(e+=de)}return s}function Za(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Ja(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function to(t){const e=Qa(t);for(let s=0;s<e.length;s++){const t=e[s];if(Za(t))return Ja(t)}}function eo(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}function so(t,e,s,i,r){if(s+24>e.length)return;const n=io(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function io(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*me[14*(3===s?3-i:3===i?3:4)+r-1],d=pe[3*(3===s?0:2===s?1:2)+n],h=3===o?1:2,c=ve[s][i],u=ye[i],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===ge){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ge=t?parseInt(t[1]):0}return ge&&ge<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function ro(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function no(t,e){return e+1<t.length&&ro(t,e)}function ao(t,e){if(e+1<t.length&&ro(t,e)){const s=4,i=io(t,e);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===t.length||no(t,n)}return!1}function oo(t,e,s,i,r){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const d=e[s+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(e[s+6]<<8|e[s+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}function lo(t,e){return C(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}function ho(t,e){return((31&t[e+1])<<8)+t[e+2]}function co(t,e){return(31&t[e+10])<<8|t[e+11]}function uo(t,e,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=ho(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){go("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!i){go("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){go("AC-3",n);break}case 129:s.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let i=e+5,r=l;for(;r>2;){106===t[i]&&(!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3"));const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return fo(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=l+5}return a}function fo(t,e,s,i){i.warn(`parsing error: ${e.message}`),t.emit($.ERROR,$.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:e,reason:e.message})}function go(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function mo(t,e){let s,i,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Fr(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>t.size-6)return null;const d=s[7];192&d&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&d?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let h=r+9;if(t.size<=h)return null;t.size-=h;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){s=l[t];let e=s.byteLength;if(h){if(h>e){h-=e;continue}s=s.subarray(h),e-=h,h=0}c.set(s,o),o+=e}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}function po(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function vo(t,e=!1){return po(t,1e3,1/Oe,e)}function yo(t){const{baseTime:e,timescale:s,trackId:i}=t;return`${e/s} (${e}/${s}) trackId: ${i}`}function Eo(t,e,s,i){return{duration:e,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function To(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function So(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let o=0;o<r;o++){const r=t.samples[o];r.pts=To(r.pts-s.baseTime*n/s.timescale,e*n)/n,r.dts=To(r.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Ao(t,e,s){const i=t.samples.length;if(!i)return;const r=t.inputTimeScale;for(let a=0;a<i;a++){const i=t.samples[a];i.pts=To(i.pts-s.baseTime*r/s.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function Lo(t,e,s=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(s?t.duration:0))/t.timescale:e}function Io(t,e,s){const i=t.codec;return i&&i.length>4?i:e===Q.AUDIO?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?Xr(i,!1):(s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}function bo(t){return"then"in t&&t.then instanceof Function}function Ro(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!ko(t[s].attrs,e[s].attrs))return!1;return!0}function ko(t,e,s){const i=t["STABLE-RENDITION-ID"];return i&&!s?i===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>t[s]!==e[s])}function Do(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}function wo(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function Po(t){return"audio"===t?1:0}function _o(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}function Co(t,e,s){return _o("serialize",t,e,s)}function xo(t){if(!1===ArrayBuffer.isView(t))throw Co(t,hs);return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Mo(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw Co(t,cs);return t.toString()}function Oo(t,e){if(t<0)return-Oo(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)<Number.EPSILON){const e=Math.floor(t*s);return(e%2==0?e:e+1)/s}return Math.round(t*s)/s}function Fo(t){const e=Oo(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Co(t,us);const s=e.toString();return s.includes(".")?s:`${s}.0`}function $o(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Co(e,ms);return e}function No(t){switch(typeof t){case"number":if(!C(t))throw Co(t,ls);return Number.isInteger(t)?Mo(t):Fo(t);case"string":return function(t){if(gs.test(t))throw Co(t,fs);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return $o(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Co(t,ds);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Mo(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return xo(t);if(t instanceof os)return $o(t);default:throw Co(t,ls)}}function Uo(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Co(t,ps);return t}function Bo(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${Uo(t)}`:`;${Uo(t)}=${No(e)}`).join("")}function Go(t){return t instanceof ns?`${No(t.value)}${Bo(t.params)}`:No(t)}function Ko(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw Co(t,as);const s=t instanceof Map?t.entries():Object.entries(t),i=(null==e?void 0:e.whitespace)?" ":"";return Array.from(s).map(([t,e])=>{e instanceof ns==0&&(e=new ns(e));let s=Uo(t);var i;return!0===e.value?s+=Bo(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(Go).join(" ")})${Bo(i.params)}`:s+=Go(e)),s}).join(`,${i}`)}function Vo(t,e){return Ko(t,e)}function Ho(t,e){const s={};if(!t)return s;const i=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var s;return null===(s=n[e])||void 0===s||s.forEach(s=>t[s]=e),t},{})):{};var n;return i.reduce((e,s)=>{var i;const n=Ss[s]||r[s]||As.REQUEST;return(null!==(i=e[n])&&void 0!==i?i:e[n]={})[s]=t[s],e},s)}function Wo(t){return Cs.test(t)}function Yo(t){return Ps.includes(t)||_s.includes(t)||Wo(t)}function jo(t){return Ps.includes(t)||xs.includes(t)||Wo(t)}function qo(t){return Ps.includes(t)||xs.includes(t)||Ms.includes(t)||Wo(t)}function zo(t){return Os.includes(t)||Wo(t)}function Xo(t,e={}){const s={};if(null==t||"object"!=typeof t)return s;const i=e.version||t.v||1,r=e.reportingMode||Ds,n=1===i?zo:Fs[r];let a=Object.keys(t).filter(n);const o=e.filter;"function"==typeof o&&(a=a.filter(o));const l=r===ws||r===Ls;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const d=or({},ks,e.formatters),h={version:i,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(e=>{let r=t[e];const n=d[e];if("function"==typeof n&&(r=n(r,h)),"v"===e){if(1===i)return;r=i}"pr"==e&&1===r||(l&&"ts"===e&&!C(r)&&(r=Date.now()),function(t){return"number"==typeof t?C(t):null!=t&&""!==t&&!1!==t}(r)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(e)&&"string"==typeof r&&(r=new os(r)),s[e]=r))}),s}function Qo(t,e,s){return or(t,function(t,e={}){const s={};if(!t)return s;const i=Ho(Xo(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(i).reduce((t,[e,s])=>{const i=Vo(s,{whitespace:!1});return i&&(t[e]=i),t},s)}(e,s))}function Zo(t,e={}){if(!t)return"";const s=function(t,e={}){return t?Vo(Xo(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(s)}function Jo(t,e,s){const i=function(t,e={}){return t?`${$s}=${Zo(t,e)}`:""}(e,s);return i?Ns.test(t)?t.replace(Ns,i):`${t}${t.includes("?")?"&":"?"}${i}`:t}function tl(t,e,s,i){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=or({},t);return n.details=void 0,n.attrs=new Ut(n.attrs),n.url=n.attrs.URI=el(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n});t.push(...n)})}function el(t,e,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}function sl(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return mr(t.keyId)}function il(t,e){return t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId)?e.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(e.decryptdata)?e.keyStatus:void 0}function rl(t,e){const s="output-restricted"===t,i=s?F.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:F.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ks({type:O.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},s?"HDCP level output restricted":`key status changed to "${t}"`)}function nl(t,e){let s;try{s=new Event("addtrack")}catch(i){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function al(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Y.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(r){Y.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}"disabled"===s&&(t.mode=s)}function ol(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===s&&(t.mode=s)}function ll(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(e<=t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&r<s))return i;r=i+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e<r.length;e++)i&&!i(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function dl(t){const e=[];for(let s=0;s<t.length;s++){const i=t[s];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||e.push(t[s])}return e}function hl(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()}function cl(t,e,s){return`${t.identifier}-${s+1}-${hl(e)}`}function ul(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Ws)?e.start:e.start+e.duration}function fl(t,e,s){const i=new self.URL(t,s);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",e),i}function gl(t,e){for(;null!=(s=t.assetList[++e])&&s.error;)var s;return e}function ml(t){const e=t.timelineStart,s=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+s).toFixed(2)}]`}function pl(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}function vl(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function yl(t,e){return`[${t}] Advancing timeline position to ${e}`}function El(t,e,s){s.a=t,s.b=e}function Tl(t,e,s){return s.a===t&&s.b===e}function Sl(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}function Al(t,e,s,i){const r=i?t.split(i):[t];for(const n in r){if("string"!=typeof r[n])continue;const t=r[n].split(s);2===t.length&&e(t[0],t[1])}}function Ll(t,e,s){const i=t;function r(){const e=Sl(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new Ei;Al(t,function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",Si,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",Si,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Si,"end","left","right"])}},/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===Ti.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Si);let n=i.get("position","auto");"auto"===n&&50===Ti.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Il(t){return t.replace(/<br(?: \/)?>/gi,"\n")}function bl(t,e,s){return hl(t.toString())+hl(e.toString())+hl(s)}function Rl(t,e,s,i,r,n,a){const o=new Ai,l=gr(new Uint8Array(t)).trim().replace(Li,"\n").split("\n"),d=[],h=e?function(t,e=1){return po(t,Oe,1/e)}(e.baseTime,e.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(f-h)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:Ri(s,i,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,u=To(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=bl(t.startTime,t.endTime,m)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(d)},l.forEach(t=>{if(m){if(Ii(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach(t=>{Ii(t,"LOCAL:")?u=t.slice(6):Ii(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=bi(u)/1e3}catch(e){c=e}return}""===t&&(m=!1)}o.parse(t+"\n")}),o.flush()}function kl(t,e,s,i){const r=Rr(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>gr(t)),a=function(t,e,s=1,i=!1){return po(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach(t=>s(function(t,e){const s=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(i).reduce((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||i[e],t),{}),n="preserve"!==s.getAttribute("xml:space"),a=wl(Dl(s,"styling","style")),o=wl(Dl(s,"layout","region")),l=Dl(s,"body","[begin]");return[].map.call(l,t=>{const s=Pl(t,n);if(!s||!t.hasAttribute("begin"))return null;const i=xl(t.getAttribute("begin"),r),l=xl(t.getAttribute("dur"),r);let d=xl(t.getAttribute("end"),r);if(null===i)throw Cl(t);if(null===d){if(null===l)throw Cl(t);d=i+l}const h=new vi(i-e,d-e,s);h.id=bl(h.startTime,h.endTime,h.text);const c=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&s.hasOwnProperty(a)&&(r=s[a]),n.reduce((s,n)=>{const a=_l(e,i,n)||_l(t,i,n)||_l(r,i,n);return a&&(s[n]=a),s},{})}(o[t.getAttribute("region")],a[t.getAttribute("style")],a),{textAlign:u}=c;if(u){const t=Pi[u];t&&(h.lineAlign=t),h.align=u}return or(h,c),h}).filter(t=>null!==t)}(t,a)))}catch(o){i(o)}}function Dl(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function wl(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function Pl(t,e){return[].slice.call(t.childNodes).reduce((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?Pl(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function _l(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function Cl(t){return new Error(`Could not parse ttml timestamp ${t}`)}function xl(t,e){if(!t)return null;let s=Sl(t);return null===s&&(Di.test(t)?s=function(t,e){const s=Di.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):wi.test(t)&&(s=function(t,e){const s=wi.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}function Ml(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Ol(t,e){return!!t&&t.kind===Ml(e)&&Do(e,t)}function Fl(t,e,s,i){return Math.min(e,i)-Math.max(t,s)}function $l(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Oi.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(C(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}function Nl(t,e){return new self.Request(t.url,e)}function Ul(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Ul):Object.keys(t).reduce((e,s)=>(e[s]=Ul(t[s]),e),{}):t}function Bl(t,e){const s=t.loader;s!==Fi&&s!==Ui?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=Fi,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}function Gl(t,e){const s=Kl(t.main);if(s&&s.start<=e)return s;const i=Kl(t.audio);return i&&i.start<=e?i:null}function Kl(t){if(!t)return null;switch(t.state){case ee.IDLE:case ee.STOPPED:case ee.ENDED:case ee.ERROR:return null}return t.frag}function Vl(t,e){return e.getAppendedFrag(t,U.MAIN)||e.getPartialFragment(t)}function Hl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Wl(t,e,s,i,r){let n=new t(e,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new t(e,s,pt(r?dr({type:r},i):i))}return n}function Yl(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function jl(){return self.SourceBuffer||self.WebKitSourceBuffer}function ql(){if(!ur())return!1;const t=jl();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}function zl(t){if(t.keyFormat!==Ht.FAIRPLAY){const e=t.keyId;if(e)return mr(e)}return t.uri}function Xl(t){const{type:e}=t;switch(e){case N.AUDIO_TRACK:return U.AUDIO;case N.SUBTITLE_TRACK:return U.SUBTITLE;default:return U.MAIN}}function Ql(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}return t({n:function(t){return async e=>((_=new I.default({availableFonts:{"times new roman":ir(w)},workerUrl:await rr({workerUrl:k,wasmUrl:D}),fallbackFont:ir(P),video:e.template.$video,...t})).canvasParent.className="artplayer-plugin-ass",_.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=>{_.freeTrack(),_.setTrackByUrl(t),nr(!0)}),e.on("subtitle",t=>nr(t)),e.on("artplayer-plugin-ass:visible",t=>nr(t)),e.on("subtitleOffset",t=>_.timeOffset=t),e.on("destroy",()=>_.dispose()),{name:"artplayerPluginAss",instance:_})},r:sr}),{setters:[function(t){s=t.i,i=t.t},function(t){r=t.B}],execute:function(){if((n=document.createElement("style")).textContent="@media (max-width:440px){.art-control.art-control-previous-button,.art-control.art-control-next-button{display:none}}@media (max-width:360px){.art-control.art-control-time{display:none}}\n/*$vite$:1*/",document.head.appendChild(n),a='/*!\n * artplayer-plugin-danmuku.js v5.3.0\n * Github: https://github.com/zhw2590582/ArtPlayer\n * (c) 2017-2026 Harvey Zhao\n * Released under the MIT License.\n */\nfunction getDanmuTop({ target, visibles, clientWidth, clientHeight, marginBottom, marginTop, antiOverlap }) {\n const maxTop = clientHeight - marginBottom;\n const danmus = visibles.filter((item) => item.mode === target.mode && item.top <= maxTop).sort((prev, next) => prev.top - next.top);\n if (danmus.length === 0) {\n if (target.mode === 2) {\n return maxTop - target.height;\n } else {\n return marginTop;\n }\n }\n danmus.unshift({\n type: "top",\n top: 0,\n left: 0,\n right: 0,\n height: marginTop,\n width: clientWidth,\n speed: 0,\n distance: clientWidth\n });\n danmus.push({\n type: "bottom",\n top: maxTop,\n left: 0,\n right: 0,\n height: marginBottom,\n width: clientWidth,\n speed: 0,\n distance: clientWidth\n });\n if (target.mode === 2) {\n for (let index = danmus.length - 2; index >= 0; index -= 1) {\n const item = danmus[index];\n const prev = danmus[index + 1];\n const itemBottom = item.top + item.height;\n const diff = prev.top - itemBottom;\n if (diff >= target.height) {\n return prev.top - target.height;\n }\n }\n } else {\n for (let index = 1; index < danmus.length; index += 1) {\n const item = danmus[index];\n const prev = danmus[index - 1];\n const prevBottom = prev.top + prev.height;\n const diff = item.top - prevBottom;\n if (diff >= target.height) {\n return prevBottom;\n }\n }\n }\n const topMap = [];\n for (let index = 1; index < danmus.length - 1; index += 1) {\n const item = danmus[index];\n if (topMap.length) {\n const last = topMap[topMap.length - 1];\n if (last[0].top === item.top) {\n last.push(item);\n } else {\n topMap.push([item]);\n }\n } else {\n topMap.push([item]);\n }\n }\n if (antiOverlap) {\n switch (target.mode) {\n case 0: {\n const result = topMap.find((list) => {\n return list.every((danmu) => {\n if (clientWidth < danmu.distance)\n return false;\n if (target.speed < danmu.speed)\n return true;\n const overlapTime = danmu.right / (target.speed - danmu.speed);\n if (overlapTime > danmu.time)\n return true;\n return false;\n });\n });\n return result && result[0] ? result[0].top : void 0;\n }\n // 静止弹幕没有重叠问题\n case 1:\n case 2:\n return void 0;\n }\n } else {\n switch (target.mode) {\n case 0:\n topMap.sort((prev, next) => {\n const nextMinRight = Math.min(...next.map((item) => item.right));\n const prevMinRight = Math.min(...prev.map((item) => item.right));\n return nextMinRight * next.length - prevMinRight * prev.length;\n });\n break;\n case 1:\n case 2:\n topMap.sort((prev, next) => {\n const nextMaxWidth = Math.max(...next.map((item) => item.width));\n const prevMaxWidth = Math.max(...prev.map((item) => item.width));\n return prevMaxWidth * prev.length - nextMaxWidth * next.length;\n });\n break;\n }\n return topMap[0][0].top;\n }\n}\nonmessage = (event) => {\n const { data } = event;\n if (!data.id || !data.type)\n return;\n const fns = { getDanmuTop };\n const fn = fns[data.type];\n const result = fn(data);\n globalThis.postMessage({\n result,\n id: data.id\n });\n};\n',o="undefined"!=typeof self&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",a],{type:"text/javascript;charset=utf-8"}),l=class t{constructor(e,s){const{constructor:i,template:r}=e;this.utils=i.utils,this.validator=i.validator,this.$danmuku=r.$danmuku,this.$player=r.$player,this.art=e,this.queue=[],this.$refs=[],this.isStop=!1,this.isHide=!1,this.timer=null,this.index=0,this.option=t.option,this.states={wait:[],ready:[],emit:[],stop:[]},this.config(s,!0),this.worker=new tr,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),e.on("video:play",this.start),e.on("video:playing",this.start),e.on("video:pause",this.stop),e.on("video:waiting",this.stop),e.on("destroy",this.destroy),e.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'\n user-select: none;\n position: absolute;\n white-space: pre;\n pointer-events: none;\n perspective: 500px;\n display: inline-block;\n will-change: transform;\n font-weight: normal;\n line-height: 1.125;\n visibility: hidden;\n font-family: SimHei, "Microsoft JhengHei", Arial, Helvetica, sans-serif;\n 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;\n '}get isRotate(){return this.art.plugins?.autoOrientation?.state}get marginTop(){const{clamp:e}=this.utils,s=this.option.margin[0],{clientHeight:i}=this.$player;return"number"==typeof s?e(s,0,i):"string"==typeof s&&s.endsWith("%")?e(i*(Number.parseFloat(s)/100),0,i):t.option.margin[0]}get marginBottom(){const{clamp:e}=this.utils,s=this.option.margin[1],{clientHeight:i}=this.$player;return"number"==typeof s?e(s,0,i):"string"==typeof s&&s.endsWith("%")?e(i*(Number.parseFloat(s)/100),0,i):t.option.margin[1]}get fontSize(){const{clamp:e}=this.utils,{clientHeight:s}=this.$player,i=this.option.fontSize;if("number"==typeof i)return Math.round(e(i,12,s));if("string"==typeof i&&i.endsWith("%")){const t=Number.parseFloat(i)/100;return Math.round(e(s*t,12,s))}return t.option.fontSize}get $ref(){const e=this.$refs.pop()||document.createElement("div");return e.style.cssText=t.cssText,e.dataset.mode="",e.dataset.id="",e.className="",e}get readys(){const{currentTime:t}=this.art,e=[];return this.filter("ready",t=>e.push(t)),this.filter("wait",s=>{t+.1>=s.time&&s.time>=t-.1&&e.push(s)}),e}get visibles(){const t=[],{clientWidth:e}=this.$player,s=this.getLeft(this.$player);return this.filter("emit",i=>{const r=i.$ref.offsetTop,n=this.getLeft(i.$ref)-s,a=i.$ref.clientHeight,o=i.$ref.clientWidth,l=n+o,d=e-l,h=l/i.$restTime,c={};c.top=r,c.left=n,c.height=a,c.width=o,c.right=d,c.speed=h,c.distance=l,c.time=i.$restTime,c.mode=i.mode,t.push(c)}),t}get speed(){return this.option.synchronousPlayback&&this.art.playbackRate?this.option.speed/Number(this.art.playbackRate):this.option.speed}async load(t){const{errorHandle:e}=this.utils;let s=[];const i=t||this.option.danmuku;try{"function"==typeof i?s=await i():i instanceof Promise?s=await i:"string"==typeof i?s=await(r=i,new Promise(async t=>{const e=await(await fetch(r)).text();try{const s=Ji();s.onmessage=e=>{const{danmus:i,id:r}=e.data;r&&i&&(t(i),s.terminate())},s.postMessage({xml:e,id:Date.now()})}catch(s){console.error("Error parsing Bilibili Danmu:",s),t(Qi(e))}})):Array.isArray(i)&&(s=i),e(Array.isArray(s),"Danmuku need return an array as result"),void 0===t&&(this.reset(),this.queue=[],this.states={wait:[],ready:[],emit:[],stop:[]},this.$refs=[],this.$danmuku.textContent="");for(let t=0;t<s.length;t++){const e=s[t];await this.emit(e)}this.art.emit("artplayerPluginDanmuku:loaded",this.queue)}catch(n){throw this.art.emit("artplayerPluginDanmuku:error",n),n}var r;return this}async emit(t){const{clamp:e}=this.utils;if(this.validator(t,{id:"?string",text:"string",mode:"?number",color:"?string",time:"?number",border:"?boolean",style:"?object"}),!t.text.trim())return this;if(t.time?t.time=e(t.time,0,1/0):t.time=this.art.currentTime+.5,void 0===t.mode&&(t.mode=this.option.mode),void 0===t.style&&(t.style={}),void 0===t.color&&(t.color=this.option.color),![0,1,2].includes(t.mode))return this;if(!this.option.filter(t))return this;const s={...t,$state:"wait",$index:this.index++,$ref:null,$restTime:0,$lastStartTime:0};return this.setState(s,"wait"),this.queue.push(s),this}config(e,s=!1){const{clamp:i}=this.utils,{$controlsCenter:r}=this.art.template;return Object.keys(e).some(t=>JSON.stringify(this.option[t])!==JSON.stringify(e[t]))||s?(this.option=Object.assign({},t.option,this.option,e),this.validator(this.option,t.scheme),this.option.mode=i(this.option.mode,0,2),this.option.speed=i(this.option.speed,1,10),this.option.opacity=i(this.option.opacity,0,1),this.option.lockTime=i(this.option.lockTime,1,60),this.option.maxLength=i(this.option.maxLength,1,1e3),this.option.mount=this.option.mount||r,e.fontSize&&this.reset(),this.option.visible?this.show():this.hide(),this.art.emit("artplayerPluginDanmuku:config",this.option),this):this}getLeft(t){const e=t.getBoundingClientRect();return this.isRotate?e.top:e.left}postMessage(t={}){return new Promise(e=>{t.id=Date.now(),this.worker.postMessage(t),this.worker.onmessage=s=>{const{data:i}=s;i.id===t.id&&e(i)}})}filter(t,e){const s=this.states[t]||[];for(let i=0;i<s.length;i++)e(s[i]);return s}setState(t,e){this.states[t.$state]=this.states[t.$state].filter(e=>e!==t),t.$state=e,t.$ref&&(t.$ref.dataset.state=e),this.states[e].push(t)}makeWait(e){this.setState(e,"wait"),e.$ref&&(e.$ref.style.cssText=t.cssText,e.$ref.style.visibility="hidden",e.$ref.style.marginLeft="0px",e.$ref.style.transform="translateX(0px)",e.$ref.style.transition="transform 0s linear 0s",this.$refs.push(e.$ref),e.$ref=null)}update(){const{setStyles:t}=this.utils;return this.timer=window.requestAnimationFrame(async()=>{if(this.art.playing&&!this.isHide){this.filter("emit",t=>{const e=(Date.now()-t.$lastStartTime)/1e3;t.$restTime-=e,t.$lastStartTime=Date.now(),t.$restTime<=0&&this.makeWait(t)});const e=this.readys;for(let s=0;s<e.length;s++){const i=e[s];if(await this.option.beforeVisible(i)){const{clientWidth:e,clientHeight:s}=this.$player;i.$ref=this.$ref,i.$ref.textContent=i.text,this.$danmuku.appendChild(i.$ref),i.$ref.style.opacity=this.option.opacity,i.$ref.style.fontSize=`${this.fontSize}px`,i.$ref.style.color=i.color,i.$ref.style.border=i.border?`1px solid ${i.color}`:null,i.$ref.style.backgroundColor=i.border?"rgb(0 0 0 / 50%)":null,t(i.$ref,i.style),i.$lastStartTime=Date.now(),i.$restTime=this.speed;const r=e+i.$ref.clientWidth,{result:n}=await this.postMessage({type:"getDanmuTop",target:{mode:i.mode,height:i.$ref.clientHeight,speed:r/i.$restTime},visibles:this.visibles,antiOverlap:this.option.antiOverlap,clientWidth:e,clientHeight:s,marginBottom:this.marginBottom,marginTop:this.marginTop});if(i.$ref)if(this.isStop||void 0===n)this.setState(i,"ready"),this.$refs.push(i.$ref),i.$ref=null;else{switch(this.setState(i,"emit"),i.$ref.style.top=`${n}px`,i.$ref.style.visibility="visible",i.$ref.dataset.mode=i.mode,i.$ref.dataset.id=i.id||"",i.mode){case 0:i.$ref.style.left=`${e}px`,i.$ref.style.marginLeft="0px",i.$ref.style.transform=`translateX(${-r}px)`,i.$ref.style.transition=`transform ${i.$restTime}s linear 0s`;break;case 1:case 2:i.$ref.style.left="50%",i.$ref.style.marginLeft=`-${i.$ref.clientWidth/2}px`}this.art.emit("artplayerPluginDanmuku:visible",i)}}}}this.isStop||this.update()}),this}resize(){const{clientWidth:t}=this.$player;this.filter("stop",e=>{0===e.mode&&(e.$ref.style.left=`${t}px`)}),this.filter("emit",e=>{switch(e.$lastStartTime=Date.now(),e.mode){case 0:{const s=t+e.$ref.clientWidth;e.$ref.style.left=`${t}px`,e.$ref.style.transform=`translateX(${-s}px)`,e.$ref.style.transition=`transform ${e.$restTime}s linear 0s`;break}}})}continue(){const{clientWidth:t}=this.$player;return this.filter("stop",e=>{switch(this.setState(e,"emit"),e.$lastStartTime=Date.now(),e.mode){case 0:{const s=t+e.$ref.clientWidth;e.$ref.style.transform=`translateX(${-s}px)`,e.$ref.style.transition=`transform ${e.$restTime}s linear 0s`;break}}}),this}suspend(){const{clientWidth:t}=this.$player;return this.filter("emit",e=>{switch(this.setState(e,"stop"),e.mode){case 0:{const s=t-(this.getLeft(e.$ref)-this.getLeft(this.$player));e.$ref.style.transform=`translateX(${-s}px)`,e.$ref.style.transition="transform 0s linear 0s";break}}}),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(t=>this.makeWait(t)),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")}},d={map:(t,e,s,i,r)=>(t-e)*(r-i)/(s-e)+i,range(t,e,s){const i=Math.round(t/s)*s;return Array.from({length:Math.floor((e-t)/s)},(t,e)=>e*s+i)}},h='<svg class="apd-icon apd-check-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',c='<svg class="apd-icon apd-check-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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"></path></svg>',u='<svg class="apd-icon apd-config-icon" xmlns:xlink="http://www.w3.org/1999/xlink" 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.363c1.903.094 3.317.141 5.513.141a.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.09-.002.056-.004.112-.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-.305c-.228-.501-.5-.959-.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"></path></svg>',f='<svg class="apd-icon apd-mode-0-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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"></path></svg>',g='<svg class="apd-icon apd-mode-0-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',m='<svg class="apd-icon apd-mode-1-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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"></path></svg>',p='<svg class="apd-icon apd-mode-1-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',v='<svg class="apd-icon apd-mode-2-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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"></path></svg>',y='<svg class="apd-icon apd-mode-2-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',E='<svg class="apd-icon apd-toggle-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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.813-2.444-.087-4.466-.13-6.064-.131-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.975c-2.196 0-3.61-.047-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"></path></svg>',T='<svg class="apd-icon apd-toggle-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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.005c.407.315 1 .27 1.354-.124l5.81-6.505.08-.102.005-.008a1 1 0 0 0-.166-1.295Z" clip-rule="evenodd"></path></svg>',S='<svg class="apd-icon apd-style-icon" xmlns:xlink="http://www.w3.org/1999/xlink" 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"></path></svg>',A=class{constructor(t,e){this.art=t,this.danmuku=e,this.utils=t.constructor.utils;const{setStyle:s}=this.utils,{$controlsCenter:i}=t.template;s(i,"display","flex"),this.template={$controlsCenter:i,$mount:i,$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),t.on("resize",()=>this.resize()),t.on("fullscreen",t=>this.onFullscreen(t)),t.on("fullscreenWeb",t=>this.onFullscreen(t)),t.proxy(this.template.$config,"mouseenter",()=>{this.onMouseEnter({$control:this.template.$config,$panel:this.template.$configPanel})}),t.proxy(this.template.$style,"mouseenter",()=>{this.onMouseEnter({$control:this.template.$style,$panel:this.template.$stylePanel})})}static get icons(){return{$on:T,$off:E,$config:u,$style:S,$mode_0_off:f,$mode_0_on:g,$mode_1_off:m,$mode_1_on:p,$mode_2_off:v,$mode_2_on:y,$check_on:c,$check_off:h}}get option(){return this.danmuku.option}get outside(){return this.template.$mount!==this.template.$controlsCenter}get TEMPLATE(){const{option:t}=this;return`\n <div class="apd-toggle">\n ${T}${E}\n </div>\n <div class="apd-config">\n ${u}\n <div class="apd-config-panel">\n <div class="apd-config-panel-inner">\n <div class="apd-config-mode">\n 按类型屏蔽\n <div class="apd-modes">\n <div data-mode="0" class="apd-mode">\n ${f}${g}\n <div>滚动</div>\n </div>\n <div data-mode="1" class="apd-mode">\n ${m}${p}\n <div>顶部</div>\n </div>\n <div data-mode="2" class="apd-mode">\n ${v}${y}\n <div>底部</div>\n </div>\n </div>\n </div>\n <div class="apd-config-other">\n <div class="apd-other apd-anti-overlap">\n ${c}${h}\n 防止弹幕重叠\n </div>\n <div class="apd-other apd-sync-video">\n ${c}${h}\n 同步视频速度\n </div>\n </div>\n <div class="apd-config-slider apd-config-opacity">\n 不透明度\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n <div class="apd-config-slider apd-config-margin">\n 显示区域\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n <div class="apd-config-slider apd-config-fontSize">\n 弹幕字号\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n <div class="apd-config-slider apd-config-speed">\n 弹幕速度\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n </div>\n </div>\n </div>\n <div class="apd-emitter">\n <div class="apd-style">\n ${S}\n <div class="apd-style-panel">\n <div class="apd-style-panel-inner">\n <div class="apd-style-mode">\n 模式\n <div class="apd-modes">\n <div data-mode="0" class="apd-mode">\n ${g}\n <div>滚动</div>\n </div>\n <div data-mode="1" class="apd-mode">\n ${p}\n <div>顶部</div>\n </div>\n <div data-mode="2" class="apd-mode">\n ${y}\n <div>底部</div>\n </div>\n </div>\n </div>\n <div class="apd-style-color">\n 颜色\n <div class="apd-colors">\n ${this.COLOR.map(t=>`<div data-color="${t}" class="apd-color" style="background-color: ${t}"></div>`).join("")}\n </div>\n </div>\n </div>\n </div>\n </div>\n <input class="apd-input" placeholder="发个友善的弹幕见证当下" autocomplete="off" maxLength="${t.maxLength}" />\n <div class="apd-send">发送</div>\n </div>\n `}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(t){const{query:e}=this.utils,{$danmuku:s}=this.template;return e(t,s)}append(t,e){const{append:s}=this.utils;[...t.children].includes(e)||s(t,e)}setData(t,e){const{$player:s}=this.art.template,{$mount:i}=this.template;s.dataset[t]=e,this.outside&&(i.dataset[t]=e)}createTemplate(){const{createElement:t,tooltip:e}=this.utils,s=t("div");s.className="artplayer-plugin-danmuku",s.innerHTML=this.TEMPLATE,this.template.$danmuku=s,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");const{$toggle:i}=this.template;this.art.on("artplayerPluginDanmuku:show",()=>{e(i,"关闭弹幕")}),this.art.on("artplayerPluginDanmuku:hide",()=>{e(i,"打开弹幕")})}createEvents(){const{$toggle:t,$configModes:e,$styleModes:s,$colors:i,$antiOverlap:r,$syncVideo:n,$send:a,$input:o}=this.template;this.art.proxy(t,"click",()=>{this.danmuku.config({visible:!this.option.visible}),this.reset()}),this.art.proxy(e,"click",t=>{const e=t.target.closest(".apd-mode");if(!e)return;const s=Number(e.dataset.mode);this.option.modes.includes(s)?this.danmuku.config({modes:this.option.modes.filter(t=>t!==s)}):this.danmuku.config({modes:[...this.option.modes,s]}),this.reset()}),this.art.proxy(r,"click",()=>{this.danmuku.config({antiOverlap:!this.option.antiOverlap}),this.reset()}),this.art.proxy(n,"click",()=>{this.danmuku.config({synchronousPlayback:!this.option.synchronousPlayback}),this.reset()}),this.art.proxy(s,"click",t=>{const e=t.target.closest(".apd-mode");if(!e)return;const s=Number(e.dataset.mode);this.danmuku.config({mode:s}),this.reset()}),this.art.proxy(i,"click",t=>{const e=t.target.closest(".apd-color");e&&(this.danmuku.config({color:e.dataset.color}),this.reset())}),this.art.proxy(a,"click",()=>this.emit()),this.art.proxy(o,"keypress",t=>{"Enter"===t.key&&(t.preventDefault(),this.emit())})}createSliders(){this.slider.opacity=this.createSlider({...this.OPACITY,container:this.template.$opacitySlider,findIndex:()=>Math.round(100*this.option.opacity),onChange:t=>{const{$opacityValue:e}=this.template;e.textContent=`${t}%`,this.danmuku.config({opacity:t/100})}}),this.slider.margin=this.createSlider({...this.MARGIN,container:this.template.$marginSlider,findIndex:()=>this.MARGIN.steps.findIndex(t=>t.value[0]===this.option.margin[0]&&t.value[1]===this.option.margin[1]),onChange:t=>{const e=this.MARGIN.steps[t];if(!e)return;const{$marginValue:s}=this.template;s.textContent=e.name,this.danmuku.config({margin:e.value})}}),this.slider.fontSize=this.createSlider({...this.FONT_SIZE,container:this.template.$fontSizeSlider,findIndex:()=>this.danmuku.fontSize,onChange:t=>{const{$fontSizeValue:e}=this.template;e.textContent=`${t}px`,t!==this.danmuku.fontSize&&this.danmuku.config({fontSize:t})}}),this.slider.speed=this.createSlider({...this.SPEED,container:this.template.$speedSlider,findIndex:()=>this.SPEED.steps.findIndex(t=>t.value===this.option.speed),onChange:t=>{const e=this.SPEED.steps[t];if(!e)return;const{$speedValue:s}=this.template;s.textContent=e.name,this.danmuku.config({speed:e.value})}})}createSlider({min:t,max:e,container:s,findIndex:i,onChange:r,steps:n=[]}){const{query:a,clamp:o,setStyle:l}=this.utils;l(s,"touch-action","none"),s.innerHTML=`\n <div class="apd-slider-line">\n <div class="apd-slider-points">\n ${n.map(()=>'<div class="apd-slider-point"></div>').join("")}\n </div>\n <div class="apd-slider-progress"></div>\n </div>\n <div class="apd-slider-dot"></div>\n <div class="apd-slider-steps">\n ${n.map(t=>t.hide?"":`<div class="apd-slider-step">${t.name}</div>`).join("")}\n </div>\n `;const d=a(".apd-slider-dot",s),h=a(".apd-slider-progress",s);let c=!1;function u(s=i()){if(s<t||s>e)return;const a=(s-t)/(e-t);d.style.left=100*a+"%",0===n.length&&(h.style.width=d.style.left),r(s)}function f(i){const{top:r,height:n,left:a,width:l}=s.getBoundingClientRect();if(this.art.isRotate){const s=o(i.clientY-r,0,n);u(Math.round(s/n*(e-t)+t))}else{const s=o(i.clientX-a,0,l);u(Math.round(s/l*(e-t)+t))}}return this.art.proxy(s,"click",t=>{f.call(this,t)}),this.art.proxy(s,"pointerdown",t=>{c=0===t.button}),this.art.on("document:pointermove",t=>{c&&f.call(this,t)}),this.art.on("document:pointerup",t=>{c&&(c=!1,f.call(this,t))}),{reset:u}}onFullscreen(t){const{$danmuku:e,$controlsCenter:s,$mount:i}=this.template;this.outside?t?this.append(s,e):this.append(i,e):this.append(s,e)}onMouseEnter({$control:t,$panel:e}){const{$player:s}=this.art.template,i=t.getBoundingClientRect(),r=e.getBoundingClientRect(),n=s.getBoundingClientRect(),a=r.width/2-i.width/2,o=n.left-(i.left-a),l=i.right+a-n.right;e.style.left=o>0?`${-a+o}px`:l>0?-a-l+"px":-a+"px"}async emit(){const{$input:t}=this.template,e=t.value.trim();if(!e.length)return;if(this.isLock)return;if(this.emitting)return;const s={text:e,mode:this.option.mode,color:this.option.color,time:this.art.currentTime};try{this.emitting=!0;const e=await this.option.beforeEmit(s);if(this.emitting=!1,!0!==e)return;s.border=!0,delete s.time,this.danmuku.emit(s),t.value="",this.lock()}catch(i){console.error("Error emitting danmuku:",i),this.emitting=!1}}lock(){const{addClass:t}=this.utils,{$send:e}=this.template;this.isLock=!0;let s=this.option.lockTime;e.textContent=s,t(e,"apd-lock");const i=()=>{this.timer=setTimeout(()=>{0===s?this.unlock():(s-=1,e.textContent=s,i())},1e3)};i()}unlock(){const{removeClass:t}=this.utils,{$send:e}=this.template;clearTimeout(this.timer),this.isLock=!1,e.textContent="发送",t(e,"apd-lock")}resize(){if(this.outside)return;if(this.art.fullscreen)return;if(this.art.fullscreenWeb)return;const{$player:t,$controlsCenter:e}=this.art.template,{$danmuku:s}=this.template;this.art.width<this.option.width?this.append(t,s):this.append(e,s)}reset(){const{inverseClass:t,tooltip:e}=this.utils,{$toggle:s,$colors:i}=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);const r=i.children,n=Array.from(r).find(t=>t.dataset.color===this.option.color.toUpperCase());n&&t(n,"apd-active"),e(s,this.option.visible?"关闭弹幕":"打开弹幕"),this.resize()}mount(t){const{errorHandle:e}=this.utils,s="string"==typeof t?document.querySelector(t):t;e(s,`Can not find the mount point: ${t}`),this.append(s,this.template.$danmuku),this.template.$mount=s,this.reset()}},"undefined"!=typeof document){const t="artplayer-plugin-danmuku";let e=document.getElementById(t);e||(e=document.createElement("style"),e.id=t,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{document.head.appendChild(e)}):(document.head||document.documentElement).appendChild(e)),e.textContent=".artplayer-plugin-danmuku {\n display: flex;\n position: relative;\n z-index: 99;\n align-items: center;\n justify-content: center;\n font-size: 12px;\n height: 32px;\n width: 100%;\n color: #fff;\n font-weight: 300;\n flex-shrink: 0;\n gap: 10px;\n}\n.artplayer-plugin-danmuku .apd-icon {\n cursor: pointer;\n opacity: 0.75;\n transition: all 0.2s ease;\n fill: #fff;\n}\n.artplayer-plugin-danmuku .apd-icon:hover {\n opacity: 1;\n}\n.artplayer-plugin-danmuku .apd-config {\n display: flex;\n position: relative;\n}\n.artplayer-plugin-danmuku .apd-config .apd-config-panel {\n position: absolute;\n bottom: 24px;\n left: 0;\n width: 320px;\n padding: 10px;\n opacity: 0;\n pointer-events: none;\n}\n.artplayer-plugin-danmuku .apd-config .apd-config-panel .apd-config-panel-inner {\n width: 100%;\n border-radius: 3px;\n background-color: rgba(0, 0, 0, 0.85);\n padding: 10px;\n}\n.artplayer-plugin-danmuku .apd-config:hover .apd-config-panel {\n opacity: 100;\n pointer-events: all;\n}\n.artplayer-plugin-danmuku .apd-config-mode,\n.artplayer-plugin-danmuku .apd-config-slider,\n.artplayer-plugin-danmuku .apd-config-other,\n.artplayer-plugin-danmuku .apd-style-mode {\n margin-bottom: 15px;\n}\n.artplayer-plugin-danmuku .apd-modes {\n display: flex;\n align-items: center;\n margin-top: 5px;\n gap: 20px;\n}\n.artplayer-plugin-danmuku .apd-modes .apd-mode {\n cursor: pointer;\n text-align: center;\n}\n.artplayer-plugin-danmuku .apd-modes .apd-mode:hover {\n color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-config-slider {\n display: flex;\n align-items: center;\n gap: 12px;\n}\n.artplayer-plugin-danmuku .apd-config-slider .apd-value {\n width: 32px;\n text-align: right;\n}\n.artplayer-plugin-danmuku .apd-slider {\n position: relative;\n flex: 1;\n display: flex;\n height: 20px;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-line {\n position: relative;\n height: 2px;\n width: 100%;\n overflow: hidden;\n border-radius: 3px;\n background-color: rgba(255, 255, 255, 0.25);\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-points {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: space-between;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-points .apd-slider-point {\n width: 2px;\n height: 2px;\n border-radius: 50%;\n background-color: rgba(255, 255, 255, 0.5);\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-progress {\n width: 0%;\n height: 100%;\n background-color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-dot {\n position: absolute;\n transform: translateX(-6px);\n left: 0%;\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background-color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-steps {\n display: flex;\n align-items: center;\n justify-content: space-between;\n position: absolute;\n bottom: -12px;\n width: calc(100% + 32px);\n color: #777;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-steps .apd-slider-step {\n flex-shrink: 0;\n width: 36px;\n text-align: center;\n scale: 0.95;\n}\n.artplayer-plugin-danmuku .apd-config-other {\n display: flex;\n align-items: center;\n gap: 20px;\n}\n.artplayer-plugin-danmuku .apd-config-other .apd-check-off,\n.artplayer-plugin-danmuku .apd-config-other .apd-check-on {\n width: 16px;\n height: 16px;\n}\n.artplayer-plugin-danmuku .apd-config-other .apd-other {\n display: flex;\n align-items: center;\n cursor: pointer;\n gap: 2px;\n}\n.artplayer-plugin-danmuku .apd-config-other .apd-other:hover {\n color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-emitter {\n display: flex;\n flex: 1;\n align-items: center;\n height: 100%;\n background-color: rgba(255, 255, 255, 0.25);\n border-radius: 5px;\n}\n.artplayer-plugin-danmuku .apd-style {\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.artplayer-plugin-danmuku .apd-style .apd-style-panel {\n position: absolute;\n bottom: 24px;\n left: 0;\n width: 200px;\n padding: 10px;\n opacity: 0;\n pointer-events: none;\n}\n.artplayer-plugin-danmuku .apd-style .apd-style-panel .apd-style-panel-inner {\n width: 100%;\n border-radius: 3px;\n background-color: rgba(0, 0, 0, 0.85);\n padding: 10px;\n}\n.artplayer-plugin-danmuku .apd-style:hover .apd-style-panel {\n opacity: 100;\n pointer-events: all;\n}\n.artplayer-plugin-danmuku .apd-colors {\n display: flex;\n flex-wrap: wrap;\n margin-top: 5px;\n gap: 8px;\n}\n.artplayer-plugin-danmuku .apd-colors .apd-color {\n width: 16px;\n height: 16px;\n border-radius: 2px;\n cursor: pointer;\n}\n.artplayer-plugin-danmuku .apd-colors .apd-color.apd-active {\n border: 1px solid black;\n box-shadow: 0 0 0 1px #fff;\n}\n.artplayer-plugin-danmuku .apd-input {\n outline: none;\n height: 100%;\n flex: 1;\n min-width: 0;\n width: auto;\n border: none;\n line-height: 1;\n color: #fff;\n background-color: transparent;\n}\n.artplayer-plugin-danmuku .apd-input::placeholder {\n color: rgba(255, 255, 255, 0.5);\n}\n.artplayer-plugin-danmuku .apd-send {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 60px;\n flex-shrink: 0;\n cursor: pointer;\n text-shadow: none;\n border-top-right-radius: 5px;\n border-bottom-right-radius: 5px;\n background-color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-send.apd-lock {\n cursor: not-allowed;\n color: #666;\n background-color: #e7e7e7;\n}\n.art-controls-center .apd-emitter {\n width: 260px;\n flex: none;\n}\n.art-fullscreen .artplayer-plugin-danmuku,\n.art-fullscreen-web .artplayer-plugin-danmuku {\n height: 38px;\n gap: 16px;\n}\n.art-fullscreen .artplayer-plugin-danmuku .apd-config-icon,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-config-icon,\n.art-fullscreen .artplayer-plugin-danmuku .apd-toggle-off,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-toggle-off,\n.art-fullscreen .artplayer-plugin-danmuku .apd-toggle-on,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-toggle-on {\n width: 28px;\n height: 28px;\n}\n.art-fullscreen .artplayer-plugin-danmuku .apd-emitter,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-emitter {\n width: 400px;\n flex: none;\n}\n.art-video-player > .artplayer-plugin-danmuku {\n position: absolute;\n left: 0;\n right: 0;\n bottom: -40px;\n padding: 0 10px;\n}\n.art-video-player:has(> .artplayer-plugin-danmuku) {\n margin-bottom: 40px;\n}\n[data-danmuku-emitter='false'] .apd-emitter {\n display: none !important;\n}\n[data-danmuku-emitter='false'] .art-controls-center .artplayer-plugin-danmuku {\n justify-content: flex-end;\n gap: 18px;\n}\n[data-danmuku-emitter='false'].art-fullscreen .art-controls-center .artplayer-plugin-danmuku,\n[data-danmuku-emitter='false'].art-fullscreen-web .art-controls-center .artplayer-plugin-danmuku {\n gap: 24px;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-icon {\n fill: #333;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-emitter {\n background-color: #f1f2f3;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-input {\n color: #000;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-input::placeholder {\n color: rgba(0, 0, 0, 0.3);\n}\n[data-danmuku-visible='false'] .apd-toggle-off {\n display: block;\n}\n[data-danmuku-visible='false'] .apd-toggle-on {\n display: none;\n}\n[data-danmuku-visible='true'] .apd-toggle-off {\n display: none;\n}\n[data-danmuku-visible='true'] .apd-toggle-on {\n display: block;\n}\n[data-danmuku-anti-overlap='false'] .apd-anti-overlap .apd-check-on {\n display: none;\n}\n[data-danmuku-anti-overlap='false'] .apd-anti-overlap .apd-check-off {\n display: block;\n}\n[data-danmuku-anti-overlap='true'] .apd-anti-overlap .apd-check-on {\n display: block;\n}\n[data-danmuku-anti-overlap='true'] .apd-anti-overlap .apd-check-off {\n display: none;\n}\n[data-danmuku-sync-video='false'] .apd-sync-video .apd-check-on {\n display: none;\n}\n[data-danmuku-sync-video='false'] .apd-sync-video .apd-check-off {\n display: block;\n}\n[data-danmuku-sync-video='true'] .apd-sync-video .apd-check-on {\n display: block;\n}\n[data-danmuku-sync-video='true'] .apd-sync-video .apd-check-off {\n display: none;\n}\n[data-danmuku-mode0='false'] .apd-config-mode .apd-mode-0-off {\n display: block;\n}\n[data-danmuku-mode0='false'] .apd-config-mode .apd-mode-0-on {\n display: none;\n}\n[data-danmuku-mode0='false'] .art-danmuku [data-mode='0'] {\n opacity: 0 !important;\n}\n[data-danmuku-mode0='true'] .apd-config-mode .apd-mode-0-off {\n display: none;\n}\n[data-danmuku-mode0='true'] .apd-config-mode .apd-mode-0-on {\n display: block;\n}\n[data-danmuku-mode='0'] .apd-style-mode [data-mode='0'] {\n color: #00a1d6;\n}\n[data-danmuku-mode='0'] .apd-style-mode [data-mode='0'] path {\n fill: #00a1d6;\n}\n[data-danmuku-mode1='false'] .apd-config-mode .apd-mode-1-off {\n display: block;\n}\n[data-danmuku-mode1='false'] .apd-config-mode .apd-mode-1-on {\n display: none;\n}\n[data-danmuku-mode1='false'] .art-danmuku [data-mode='1'] {\n opacity: 0 !important;\n}\n[data-danmuku-mode1='true'] .apd-config-mode .apd-mode-1-off {\n display: none;\n}\n[data-danmuku-mode1='true'] .apd-config-mode .apd-mode-1-on {\n display: block;\n}\n[data-danmuku-mode='1'] .apd-style-mode [data-mode='1'] {\n color: #00a1d6;\n}\n[data-danmuku-mode='1'] .apd-style-mode [data-mode='1'] path {\n fill: #00a1d6;\n}\n[data-danmuku-mode2='false'] .apd-config-mode .apd-mode-2-off {\n display: block;\n}\n[data-danmuku-mode2='false'] .apd-config-mode .apd-mode-2-on {\n display: none;\n}\n[data-danmuku-mode2='false'] .art-danmuku [data-mode='2'] {\n opacity: 0 !important;\n}\n[data-danmuku-mode2='true'] .apd-config-mode .apd-mode-2-off {\n display: none;\n}\n[data-danmuku-mode2='true'] .apd-config-mode .apd-mode-2-on {\n display: block;\n}\n[data-danmuku-mode='2'] .apd-style-mode [data-mode='2'] {\n color: #00a1d6;\n}\n[data-danmuku-mode='2'] .apd-style-mode [data-mode='2'] path {\n fill: #00a1d6;\n}\n"}var e,Xi,Zi,er,ir,rr;sr.icons=A.icons,L=i((t,e)=>{"function"==typeof SubtitlesOctopusOnLoad&&SubtitlesOctopusOnLoad(),void 0!==t&&void 0!==e&&e.exports&&(t=e.exports=function(t){var e=!1;try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){const t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));t instanceof WebAssembly.Module&&(e=new WebAssembly.Instance(t)instanceof WebAssembly.Instance)}}catch(f){}console.log("WebAssembly support detected: "+(e?"yes":"no"));var s=this;function i(){s.setCurrentTime(s.video.currentTime+s.timeOffset)}function r(){s.setIsPaused(!1,s.video.currentTime+s.timeOffset)}function n(){s.setIsPaused(!0,s.video.currentTime+s.timeOffset)}function a(){s.video.removeEventListener("timeupdate",i,!1)}function o(){s.video.addEventListener("timeupdate",i,!1);var t=s.video.currentTime+s.timeOffset;s.setCurrentTime(t)}function l(){s.setRate(s.video.playbackRate)}function d(){s.setIsPaused(!0,s.video.currentTime+s.timeOffset)}function h(t){t.target.removeEventListener(t.type,h,!1),s.resize()}function c(){var t=s.renderFramesData,e=performance.now();s.ctx.clearRect(0,0,s.canvas.width,s.canvas.height);for(var i=0;i<t.canvases.length;i++){var r=t.canvases[i];s.bufferCanvas.width=r.w,s.bufferCanvas.height=r.h;var n=new Uint8ClampedArray(r.buffer);if(s.hasAlphaBug)for(var a=3;a<n.length;a+=4)n[a]=n[a]>=1?n[a]:1;var o=new ImageData(n,r.w,r.h);s.bufferCanvasCtx.putImageData(o,0,0),s.ctx.drawImage(s.bufferCanvas,r.x,r.y)}if(s.debug){var l=Math.round(performance.now()-e),d=t.blendTime;void 0!==d?console.log("render: "+Math.round(t.spentTime-d)+" ms, blend: "+Math.round(d)+" ms, draw: "+l+" ms; TOTAL="+Math.round(t.spentTime+l)+" ms"):console.log(Math.round(t.spentTime)+" ms (+ "+l+" ms draw)"),s.renderStart=performance.now()}}function u(){var t=s.renderFramesData,e=performance.now();s.ctx.clearRect(0,0,s.canvas.width,s.canvas.height);for(var i=0;i<t.bitmaps.length;i++){var r=t.bitmaps[i];s.ctx.drawImage(r.bitmap,r.x,r.y)}if(s.debug){var n=Math.round(performance.now()-e);console.log(t.bitmaps.length+" bitmaps, libass: "+Math.round(t.libassTime)+"ms, decode: "+Math.round(t.decodeTime)+"ms, draw: "+n+"ms"),s.renderStart=performance.now()}}s.canvas=t.canvas,s.renderMode=t.renderMode||(t.lossyRender?"lossy":"wasm-blend"),s.libassMemoryLimit=t.libassMemoryLimit||0,s.libassGlyphLimit=t.libassGlyphLimit||0,s.targetFps=t.targetFps||24,s.prescaleFactor=t.prescaleFactor||1,s.prescaleHeightLimit=t.prescaleHeightLimit||1080,s.maxRenderHeight=t.maxRenderHeight||0,s.dropAllAnimations=t.dropAllAnimations||!1,s.isOurCanvas=!1,s.video=t.video,s.canvasParent=null,s.fonts=t.fonts||[],s.availableFonts=t.availableFonts||[],s.fallbackFont=t.fallbackFont||"default.woff2",s.lazyFileLoading=t.lazyFileLoading||!1,s.onReadyEvent=t.onReady,s.workerUrl=e?t.workerUrl||"subtitles-octopus-worker.js":t.legacyWorkerUrl||"subtitles-octopus-worker-legacy.js",s.subUrl=t.subUrl,s.subContent=t.subContent||null,s.onErrorEvent=t.onError,s.debug=t.debug||!1,s.lastRenderTime=0,s.pixelRatio=window.devicePixelRatio||1,s.timeOffset=t.timeOffset||0,s.hasAlphaBug=!1,function(){if("function"==typeof ImageData.prototype.constructor)try{return void new window.ImageData(new Uint8ClampedArray([0,0,0,0]),1,1)}catch(f){console.log("detected that ImageData is not constructable despite browser saying so")}var t=document.createElement("canvas").getContext("2d");window.ImageData=function(){var e=0;if(arguments[0]instanceof Uint8ClampedArray)var s=arguments[e++];var i=arguments[e++],r=arguments[e],n=t.createImageData(i,r);return s&&n.data.set(s),n}}(),s.workerError=function(t){if(console.error("Worker error: ",t),s.onErrorEvent&&s.onErrorEvent(t),!s.debug)throw s.dispose(),new Error("Worker error: "+t)},s.init=function(){window.Worker?(s.worker||(s.worker=new Worker(s.workerUrl),s.worker.addEventListener("message",s.onWorkerMessage),s.worker.addEventListener("error",s.workerError)),s.workerActive=!1,s.createCanvas(),s.setVideo(t.video),s.setSubUrl(t.subUrl),s.worker.postMessage({target:"worker-init",width:s.canvas.width,height:s.canvas.height,URL:document.URL,currentScript:s.workerUrl,preMain:!0,renderMode:s.renderMode,subUrl:s.subUrl,subContent:s.subContent,fonts:s.fonts,availableFonts:s.availableFonts,fallbackFont:s.fallbackFont,lazyFileLoading:s.lazyFileLoading,debug:s.debug,targetFps:s.targetFps,libassMemoryLimit:s.libassMemoryLimit,libassGlyphLimit:s.libassGlyphLimit,dropAllAnimations:s.dropAllAnimations})):s.workerError("worker not supported")},s.createCanvas=function(){s.canvas||(s.video?(s.isOurCanvas=!0,s.canvas=document.createElement("canvas"),s.canvas.className="libassjs-canvas",s.canvas.style.display="none",s.canvasParent=document.createElement("div"),s.canvasParent.className="libassjs-canvas-parent",s.canvasParent.appendChild(s.canvas),s.video.nextSibling?s.video.parentNode.insertBefore(s.canvasParent,s.video.nextSibling):s.video.parentNode.appendChild(s.canvasParent)):s.canvas||s.workerError("Don't know where to render: you should give video or canvas in options.")),s.ctx=s.canvas.getContext("2d"),s.bufferCanvas=document.createElement("canvas"),s.bufferCanvasCtx=s.bufferCanvas.getContext("2d"),s.bufferCanvas.width=1,s.bufferCanvas.height=1;var t=new Uint8ClampedArray([0,255,0,0]),e=new ImageData(t,1,1);s.bufferCanvasCtx.clearRect(0,0,1,1),s.ctx.clearRect(0,0,1,1);var i=s.ctx.getImageData(0,0,1,1).data;s.bufferCanvasCtx.putImageData(e,0,0),s.ctx.drawImage(s.bufferCanvas,0,0);var r=s.ctx.getImageData(0,0,1,1).data;s.hasAlphaBug=i[1]!=r[1],s.hasAlphaBug&&console.log("Detected a browser having issue with transparent pixels, applying workaround")},s.setVideo=function(t){s.video=t,s.video&&(s.video.addEventListener("timeupdate",i,!1),s.video.addEventListener("playing",r,!1),s.video.addEventListener("pause",n,!1),s.video.addEventListener("seeking",a,!1),s.video.addEventListener("seeked",o,!1),s.video.addEventListener("ratechange",l,!1),s.video.addEventListener("waiting",d,!1),document.addEventListener("fullscreenchange",s.resizeWithTimeout,!1),document.addEventListener("mozfullscreenchange",s.resizeWithTimeout,!1),document.addEventListener("webkitfullscreenchange",s.resizeWithTimeout,!1),document.addEventListener("msfullscreenchange",s.resizeWithTimeout,!1),window.addEventListener("resize",s.resizeWithTimeout,!1),"undefined"!=typeof ResizeObserver&&(s.ro=new ResizeObserver(s.resizeWithTimeout),s.ro.observe(s.video)),s.video.videoWidth>0?s.resize():s.video.addEventListener("loadedmetadata",h,!1))},s.getVideoPosition=function(){var t=s.video.videoWidth/s.video.videoHeight,e=s.video.offsetWidth,i=s.video.offsetHeight,r=e,n=i;return e/i>t?r=Math.floor(i*t):n=Math.floor(e/t),{width:r,height:n,x:(e-r)/2,y:(i-n)/2}},s.setSubUrl=function(t){s.subUrl=t},s.renderFrameData=null,s.workerActive=!1,s.frameId=0,s.onWorkerMessage=function(t){s.workerActive||(s.workerActive=!0,s.onReadyEvent&&s.onReadyEvent());var e=t.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":s.ctx=s.canvas.getContext(e.type,e.attributes);break;case"resize":s.resize(e.width,e.height);break;case"renderCanvas":s.lastRenderTime<e.time&&(s.lastRenderTime=e.time,s.renderFramesData=e,window.requestAnimationFrame(c));break;case"renderFastCanvas":s.lastRenderTime<e.time&&(s.lastRenderTime=e.time,s.renderFramesData=e,window.requestAnimationFrame(u));break;case"setObjectProperty":s.canvas[e.object][e.property]=e.value;break;default:throw"eh?"}break;case"tick":s.frameId=e.id,s.worker.postMessage({target:"tock",id:s.frameId});break;case"custom":if(!s.onCustomMessage)throw"Custom message received but client onCustomMessage not implemented.";s.onCustomMessage(t);break;case"setimmediate":s.worker.postMessage({target:"setimmediate"});break;case"get-events":case"get-styles":case"ready":break;default:throw"what? "+e.target}},s.resize=function(t,e,i,r){var n=null;if(i=i||0,r=r||0,(!t||!e)&&s.video){var a=function(t,e){var i=s.prescaleFactor<=0?1:s.prescaleFactor;if(e<=0||t<=0)t=0,e=0;else{var r=i<1?-1:1,n=e;r*n*i<=r*s.prescaleHeightLimit?n*=i:r*n<r*s.prescaleHeightLimit&&(n=s.prescaleHeightLimit),s.maxRenderHeight>0&&n>s.maxRenderHeight&&(n=s.maxRenderHeight),t*=n/e,e=n}return{width:t,height:e}}((n=s.getVideoPosition()).width*s.pixelRatio,n.height*s.pixelRatio);t=a.width,e=a.height;var o=s.canvasParent.getBoundingClientRect().top-s.video.getBoundingClientRect().top;i=n.y-o,r=n.x}t&&e?s.canvas.width==t&&s.canvas.height==e&&s.canvas.style.top==i&&s.canvas.style.left==r||(s.canvas.width=t,s.canvas.height=e,null!=n&&(s.canvasParent.style.position="relative",s.canvas.style.display="block",s.canvas.style.position="absolute",s.canvas.style.width=n.width+"px",s.canvas.style.height=n.height+"px",s.canvas.style.top=i+"px",s.canvas.style.left=r+"px",s.canvas.style.pointerEvents="none"),s.worker.postMessage({target:"canvas",width:s.canvas.width,height:s.canvas.height})):s.video||console.error("width or height is 0. You should specify width & height for resize.")},s.resizeWithTimeout=function(){s.resize(),setTimeout(s.resize,100)},s.runBenchmark=function(){s.worker.postMessage({target:"runBenchmark"})},s.customMessage=function(t,e){e=e||{},s.worker.postMessage({target:"custom",userData:t,preMain:e.preMain})},s.setCurrentTime=function(t){s.worker.postMessage({target:"video",currentTime:t})},s.setTrackByUrl=function(t){s.worker.postMessage({target:"set-track-by-url",url:t})},s.setTrack=function(t){s.worker.postMessage({target:"set-track",content:t})},s.freeTrack=function(t){s.worker.postMessage({target:"free-track"})},s.render=s.setCurrentTime,s.setIsPaused=function(t,e){s.worker.postMessage({target:"video",isPaused:t,currentTime:e})},s.setRate=function(t){s.worker.postMessage({target:"video",rate:t})},s.dispose=function(){s.worker.postMessage({target:"destroy"}),s.worker.terminate(),s.worker.removeEventListener("message",s.onWorkerMessage),s.worker.removeEventListener("error",s.workerError),s.workerActive=!1,s.worker=null,s.video&&(s.video.removeEventListener("timeupdate",i,!1),s.video.removeEventListener("playing",r,!1),s.video.removeEventListener("pause",n,!1),s.video.removeEventListener("seeking",a,!1),s.video.removeEventListener("seeked",o,!1),s.video.removeEventListener("ratechange",l,!1),s.video.removeEventListener("waiting",d,!1),s.video.removeEventListener("loadedmetadata",h,!1),document.removeEventListener("fullscreenchange",s.resizeWithTimeout,!1),document.removeEventListener("mozfullscreenchange",s.resizeWithTimeout,!1),document.removeEventListener("webkitfullscreenchange",s.resizeWithTimeout,!1),document.removeEventListener("msfullscreenchange",s.resizeWithTimeout,!1),window.removeEventListener("resize",s.resizeWithTimeout,!1),s.video.parentNode.removeChild(s.canvasParent),s.video=null),s.ro&&(s.ro.disconnect(),s.ro=null),s.onCustomMessage=null,s.onErrorEvent=null,s.onReadyEvent=null},s.fetchFromWorker=function(t,e,i){try{var r=t.target,n=setTimeout(function(){o(Error("Error: Timeout while try to fetch "+r))},5e3),a=function(t){t.data.target==r&&(e(t.data),s.worker.removeEventListener("message",a),s.worker.removeEventListener("error",o),clearTimeout(n))},o=function(t){i(t),s.worker.removeEventListener("message",a),s.worker.removeEventListener("error",o),clearTimeout(n)};s.worker.addEventListener("message",a),s.worker.addEventListener("error",o),s.worker.postMessage(t)}catch(l){i(l)}},s.createEvent=function(t){s.worker.postMessage({target:"create-event",event:t})},s.getEvents=function(t,e){s.fetchFromWorker({target:"get-events"},function(e){t(e.events)},e)},s.setEvent=function(t,e){s.worker.postMessage({target:"set-event",event:t,index:e})},s.removeEvent=function(t){s.worker.postMessage({target:"remove-event",index:t})},s.createStyle=function(t){s.worker.postMessage({target:"create-style",style:t})},s.getStyles=function(t,e){s.fetchFromWorker({target:"get-styles"},function(e){t(e.styles)},e)},s.setStyle=function(t,e){s.worker.postMessage({target:"set-style",style:t,index:e})},s.removeStyle=function(t){s.worker.postMessage({target:"remove-style",index:t})},s.init()})}),I=s(L(),1),({fontsPath:b,libAssPath:R}=r()),k=`${R()}/subtitles-octopus-worker.js`,D=`${R()}/subtitles-octopus-worker.wasm`,w=`${b()}/TimesNewRoman.ttf`,P=`${b()}/SourceHanSansCN-Bold.woff2`,_=null,C=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},x=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=M},M=Number.MAX_SAFE_INTEGER||9007199254740991,O=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),F=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),$=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({}),N={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},U={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},B=class{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}},G=class{constructor(t,e,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new B(t),this.fast_=new B(e),this.defaultTTFB_=i,this.ttfb_=new B(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new B(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new B(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new B(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},K=class{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${t}]:`;this.trace=V,this.debug=e.debug.bind(null,s),this.log=e.log.bind(null,s),this.warn=e.warn.bind(null,s),this.info=e.info.bind(null,s),this.error=e.error.bind(null,s)}},H={trace:V=function(){},debug:V,log:V,warn:V,info:V,error:V},W=hr(),Y=W,j={exports:{}},q||(q=1,e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,Xi=/^(?=([^\/?#]*))\1([^]*)$/,Zi=/(?:\/|^)\.(?=\/)/g,er=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,ir={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var i=ir.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=ir.normalizePath(i.path),ir.buildURLFromParts(i)}var r=ir.parseURL(e);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return s.alwaysNormalize?(r.path=ir.normalizePath(r.path),ir.buildURLFromParts(r)):e;var n=ir.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=Xi.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,d=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=ir.normalizePath(d)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=s.alwaysNormalize?ir.normalizePath(r.path):r.path),ir.buildURLFromParts(o)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(Zi,"");t.length!==(t=t.replace(er,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},j.exports=ir),z=j.exports,X=class{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}}},Q={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Z=class{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,Tr(this,"stats")}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Q.AUDIO]:null,[Q.VIDEO]:null,[Q.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new X),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=z.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Q.AUDIO]=null,t[Q.VIDEO]=null,t[Q.AUDIOVIDEO]=null}},J=class extends Z{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(C(t)&&C(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const s=this._decryptdata=e[t[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=C(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),s=t.length;if(s>1||1===s&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){C(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return yr(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var s;const i=e[t];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}},tt=class extends Z{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}},et=Math.pow(2,32)-1,st=[].push,it={video:1,audio:2,id3:3,text:4},rt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),nt={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}},at={},ot=/flac|opus|mp4a\.40\.34/i,lt={supported:!1,smooth:!1,powerEfficient:!1},dt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},ht=["NONE","TYPE-0","TYPE-1",null],ct=["SDR","PQ","HLG"],ut={No:"",Yes:"YES",v2:"v2"},ft=class{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}},gt=class{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const s=null==(e=t.supplemental)?void 0:e.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return dn(this._audioGroups,t)}hasSubtitleGroup(t){return dn(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}},mt=t=>{const e=new WeakSet;return(s,i)=>{if(t&&(i=t(s,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}},pt=(t,e)=>JSON.stringify(t,mt(e)),vt=class extends K{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:s,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,d=i?i.duration:s.duration,h=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,m=!!t||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=r.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(h<=Math.max(v,d/(2*y)*1e3))return;const E=p?p.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,A=this.getBwEstimate(),L=r.levels,I=L[u],b=Math.max(l.loaded,Math.round(d*(s.bitrate||I.averageBitrate)/8));let R=S?h-T:h;R<1&&S&&(R=Math.min(h,8*l.loaded/A));const k=S?1e3*l.loaded/R:0,D=v/1e3,w=k?(b-l.loaded)/k:8*b/A+D;if(w<=E)return;const P=k?8*k:A,_=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),x=this.hls.config.abrBandWidthUpFactor;let M,O=Number.POSITIVE_INFINITY;for(M=u-1;M>c;M--){const t=L[M].maxBitrate,e=!L[M].details||_;if(O=this.getTimeToLoadFrag(D,P,d*t,e),O<Math.min(E,d+D))break}if(O>=w)return;if(O>10*d)return;S?this.bwEstimator.sample(h-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(h);const F=L[M].maxBitrate;this.getBwEstimate()*x>F&&this.resetEstimator(F);const N=this.findBestLevel(F,c,M,0,E,1,1);N>-1&&(M=N),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${w.toFixed(3)} s\n Estimated load time for down switch fragment: ${O.toFixed(3)} s\n TTFB estimate: ${0|T} ms\n Current BW estimate: ${C(A)?0|A:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|F} bps`),r.nextLoadLevel=r.nextAutoLevel=M,this.clearTimer();const U=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===M&&M>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,M>c){let e=this.findBestLevel(this.hls.levels[c].bitrate,c,M,0,t,1,1);-1===e&&(e=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};g||w>2*O?U():this.timer=self.setInterval(U,1e3*O),r.trigger($.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new G(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.FRAG_LOADING,this.onFragLoading,this),t.on($.FRAG_LOADED,this.onFragLoaded,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this),t.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.FRAG_LOADING,this.onFragLoading,this),t.off($.FRAG_LOADED,this.onFragLoaded,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this),t.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off($.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;var i;this.ignoreFragment(s)||(s.bitrateTest||(this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case F.BUFFER_ADD_CODEC_ERROR:case F.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case F.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.first;C(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===U.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:s,id:e.type};this.onFragBuffered($.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==U.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,e,t,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;t&&(c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1)}const u=this.findBestLevel(o,n,i,l,c,d,h);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,i,r,n,a){var o;const l=i+r,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[h],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===m||-1===d;let T,S="SDR",A=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:I}=p,b=this.audioTracksByGroup||(this.audioTracksByGroup=un(g));let R=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let h=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=hn(e,r);for(let L=n.length;L--;){const e=t[n[L]];h||(h=e.channels[2]>0),u=Math.min(u,e.minHeight),f=Math.min(f,e.minFramerate),g=Math.min(g,e.minBitrate),E.filter(t=>e.videoRanges[t]>0).length>0&&(c=!0)}u=C(u)?u:0,f=C(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=C(g)?g:s,s=Math.max(g,s),c||(e=void 0);const A=n.length>1;return{codecSet:n.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(v=c?E.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return cn(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return cn(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return cn(i,`audio codec preference "${o}" not found`),e;if(a&&!d){if(!r.channels[a])return cn(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||d)&&h&&0===r.channels[2])return cn(i,"no renditions with stereo sound found"),e;if(r.minHeight>T)return cn(i,`min resolution of ${r.minHeight} > maximum of ${T}`),e;if(r.minFramerate>S)return cn(i,`min framerate of ${r.minFramerate} > maximum of ${S}`),e;if(!v.some(t=>r.videoRanges[t]>0))return cn(i,`no variants with VIDEO-RANGE of ${pt(v)} found`),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return cn(i,`video codec preference "${l}" not found`),e;if(r.maxScore<p)return cn(i,`max score of ${r.maxScore} < selected max of ${p}`),e}return e&&(zr(i)>=zr(e)||r.fragmentError>t[e].fragmentError)?e:(m=r.minIndex,p=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce((t,s,i)=>{if(!s.codecSet)return t;const r=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const s=e.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]}))}),t},{})}(f,b,e,s)),S,t,L,I),{codecSet:r,videoRanges:n,minFramerate:a,minBitrate:o,minIndex:l,preferHDR:d}=i;R=l,T=r,S=d?n[n.length-1]:n[0],A=a,t=Math.max(t,o),this.log(`picked start tier ${pt(i)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const k=u?u.duration:c?c.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let _=s;_>=e;_--){var P;const e=f[_],o=_>h;if(!e)continue;if(p.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&rn(e,b,S,A,t,L)?(e.supportedPromise=nn(e,b,s,this.supportedCache),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${pt(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${pt(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${pt(t)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):e.supportedResult=dt}if((T&&e.codecSet!==T||S&&e.videoRange!==S||o&&A>e.frameRate||!o&&A>0&&A<e.frameRate||null!=(P=e.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some(t=>!1===t.smooth))&&(!E||_!==R)){w.push(_);continue}const c=e.details,g=(u?null==c?void 0:c.partTarget:null==c?void 0:c.averagetargetduration)||k;let v;v=o?a*t:n*t;const I=k&&i>=2*k&&0===r?e.averageBitrate:e.maxBitrate,x=this.getTimeToLoadFrag(D,v,I*g,void 0===c);if(v>=I&&(_===d||0===e.loadError&&0===e.fragmentError)&&(x<=D||!C(x)||y&&!this.bitrateTestDelay||x<l)){const t=this.forcedAutoLevel;return _===m||-1!==t&&t===m||(w.length&&this.trace(`Skipped level(s) ${w.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[w[0]].codecs}" ${f[w[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${h}->${_} adjustedbw(${Math.round(v)})-bitrate=${Math.round(v-I)} ttfb:${D.toFixed(1)} avgDuration:${g.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${E} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=_),_}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),e)}},yt={search:function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null}},Et={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Tt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},St=class extends K{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on($.ERROR,this.onError,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off($.ERROR,this.onError,this),t.off($.ERROR,this.onErrorOut,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===U.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,s=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===s?e.loadLevel:s}variantHasKey(t,e){if(t){var s;if(null!=(s=t.details)&&s.hasKey(e))return!0;const i=t.audioGroups;if(i)return this.hls.allAudioTracks.filter(t=>i.indexOf(t.groupId)>=0).some(t=>{var s;return null==(s=t.details)?void 0:s.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var s;if(e.fatal)return;const i=this.hls,r=e.context;switch(e.details){case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case F.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction=_n());case F.FRAG_GAP:case F.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Et.SendAlternateToPenaltyBox);case F.LEVEL_EMPTY_ERROR:case F.LEVEL_PARSING_ERROR:{var n;const t=e.parent===U.MAIN?e.level:i.loadLevel;e.details===F.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case F.LEVEL_LOAD_ERROR:case F.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case F.AUDIO_TRACK_LOAD_ERROR:case F.AUDIO_TRACK_LOAD_TIMEOUT:case F.SUBTITLE_LOAD_ERROR:case F.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=i.loadLevelObj;if(t&&(r.type===N.AUDIO_TRACK&&t.hasAudioGroup(r.groupId)||r.type===N.SUBTITLE_TRACK&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Et.SendAlternateToPenaltyBox,void(e.errorAction.flags=Tt.MoveAllAlternatesMatchingHost)}return;case F.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:Et.SendAlternateToPenaltyBox,flags:Tt.MoveAllAlternatesMatchingHDCP});case F.KEY_SYSTEM_SESSION_UPDATE_FAILED:case F.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case F.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:Et.SendAlternateToPenaltyBox,flags:Tt.MoveAllAlternatesMatchingKey});case F.BUFFER_ADD_CODEC_ERROR:case F.REMUX_ALLOC_ERROR:case F.BUFFER_APPEND_ERROR:var a;return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,null!=(a=e.level)?a:i.loadLevel)));case F.INTERNAL_EXCEPTION:case F.BUFFER_APPENDING_ERROR:case F.BUFFER_FULL_ERROR:case F.LEVEL_SWITCH_ERROR:case F.BUFFER_STALLED_ERROR:case F.BUFFER_SEEK_OVER_HOLE:case F.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=_n())}e.type===O.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=_n())}getPlaylistRetryOrSwitchAction(t,e){const s=Rn(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(wn(s,i,Ln(t),t.response))return{action:Et.RetryRequest,flags:Tt.None,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Rn(In(t)?n:r,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(i&&(t.details!==F.FRAG_GAP&&i.fragmentError++,!bn(t)&&wn(a,o,Ln(t),t.response)))return{action:Et.RetryRequest,flags:Tt.None,retryConfig:a,retryCount:o};const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,e===F.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===U.AUDIO&&e===F.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===F.BUFFER_ADD_CODEC_ERROR||e===F.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:t})=>i.audioCodec!==t),m="video"===t.sourceBufferName&&(e===F.BUFFER_ADD_CODEC_ERROR||e===F.BUFFER_APPEND_ERROR)&&d.some(({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let s=d.length;s--;){const r=(s+h)%d.length;if(r!==h&&r>=c&&r<=u&&0===d[r].loadError){var a,o;const s=d[r];if(e===F.FRAG_GAP&&f===U.MAIN&&t.frag){const e=d[r].details;if(e){const s=En(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===N.AUDIO_TRACK&&s.hasAudioGroup(v)||p===N.SUBTITLE_TRACK&&s.hasSubtitleGroup(v))continue;if(f===U.AUDIO&&null!=(a=i.audioGroups)&&a.some(t=>s.hasAudioGroup(t))||f===U.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(t=>s.hasSubtitleGroup(t))||g&&i.audioCodec===s.audioCodec||m&&i.codecSet===s.codecSet||!g&&i.codecSet!==s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Et.SendAlternateToPenaltyBox,flags:Tt.None,nextAutoLevel:l}}return{action:Et.SendAlternateToPenaltyBox,flags:Tt.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Et.DoNothing:break;case Et.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===F.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0;case Et.RetryRequest:}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Tt.None:this.switchLevel(t,r);break;case Tt.MoveAllAlternatesMatchingHDCP:{const i=this.getVariantLevelIndex(t.frag),r=e.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(s.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){e.maxHdcpLevel=ht[ht.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case Tt.MoveAllAlternatesMatchingKey:{const e=t.decryptdata;if(e){const i=this.hls.levels,r=i.length;for(let s=r;s--;)if(this.variantHasKey(i[s],e)){var n,a;this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(n=i[s].audioGroups)?void 0:n.join(",")}" (${null==(a=t.frag)?void 0:a.type} fragment) ${mr(e.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${t.error})`),this.hls.removeLevel(s)}const o=t.frag;if(this.hls.levels.length<r)s.resolved=!0;else if(o&&o.type!==U.MAIN){const t=o.decryptdata;t&&!e.matches(t)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===F.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=en(t.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${i} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(i))}}},At={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Lt=class{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.BUFFER_APPENDED,this.onBufferAppended,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this),t.on($.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.BUFFER_APPENDED,this.onBufferAppended,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this),t.off($.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let i=s.length;i--;){const e=s[i];if(!e)break;if(e.start<=t&&t<=e.end&&e.loaded)return e}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===e&&(!s||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i,r){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(a.body),s}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const s=t.frag,i=xn(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(e).forEach(i=>{const a=s.elementaryStreams[i];if(!a)return;const o=e[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,t.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),Cn(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(t,e){t.buffered=!0,(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=Mn(s,e=>e.fragment.sn>=t))}fragBuffered(t,e){const s=xn(t);let i=this.fragments[s];!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t))}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let d=0;d<i.length;d++){const t=i.start(d)-this.bufferPadding,e=i.end(d)+this.bufferPadding;if(l>=t&&o<=e){r.time.push({startPTS:Math.max(n,i.start(d)),endPTS:Math.min(a,i.end(d))});break}if(n<e&&a>t){const t=Math.max(n,i.start(d)),e=Math.min(a,i.end(d));e>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:e}))}else if(a<=t)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Cn(d)&&(s=d.body.start-a,i=d.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=d.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Cn(e))}getState(t){const e=xn(t),s=this.fragments[e];return s?s.buffered?Cn(s)?At.PARTIAL:At.OK:At.APPENDING:At.NOT_LOADED}isTimeBuffered(t,e,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,t>=i&&e<=r)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const s=e.frag,i=e.part?null:e,r=xn(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r,type:n}=e;if("initSegment"===s.sn)return;const a=s.type;if(i){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=xn(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,s=Object.keys(e);if(!t)return s.length>0;for(let i=s.length;i--;){const r=e[s[i]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=xn(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=Mn(s,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}},It={cbc:0,ctr:1},bt=class{constructor(t,e,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=s}decrypt(t,e){switch(this.aesMode){case It.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case It.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}},Rt=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=e.getUint32(4*i);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,d[s]=v<<16|v>>>16,h[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,A,L,I,b,R,k,D,w,P,_;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(R=C(p[e]),k=C(p[e+1]),D=C(p[e+2]),w=C(p[e+3]),A=R^r[0],L=w^r[1],I=D^r[2],b=k^r[3],P=4,_=1;_<i;_++)y=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&b]^r[P],E=o[L>>>24]^l[I>>16&255]^d[b>>8&255]^h[255&A]^r[P+1],T=o[I>>>24]^l[b>>16&255]^d[A>>8&255]^h[255&L]^r[P+2],S=o[b>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^r[P+3],A=y,L=E,I=T,b=S,P+=4;y=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&b]^r[P],E=n[L>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[P+1],T=n[I>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^r[P+2],S=n[b>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^r[P+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^m),u=R,f=k,g=D,m=w,e+=4}return v.buffer}},kt=class{constructor(t,e,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=s}expandKey(){const t=function(t){switch(t){case It.cbc:return"AES-CBC";case It.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}},Dt=class{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.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:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?t.slice(0,e-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s,i){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s,i)}softwareDecrypt(t,e,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==It.cbc||16!==e.byteLength)return Y.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Fr(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Rt),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,s,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s,i));this.key=e,this.fastAesKey=new kt(this.subtle,e,i)}return this.fastAesKey.expandKey().then(e=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bt(this.subtle,new Uint8Array(s),i).decrypt(t.buffer,e)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Y.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s,i)))}onWebCryptoError(t,e,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=t.slice(0,s),this.remainderData=t.slice(s)),e}logOnce(t){this.logEnabled&&(Y.log(`[decrypter]: ${t}`),this.logEnabled=!1)}},wt=Math.pow(2,17),Pt=class{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const s=t.url;if(!s)return Promise.reject(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void o(Fn(t));t.gap=!1}const l=this.loader=r?new r(i):new n(i),d=On(t);t.loader=l;const h=Dn(i.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:wt};t.stats=l.stats;const u={onSuccess:(e,s,i,r)=>{this.resetLoader(t,l);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,r,n)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:dr({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:e}))}};e&&(u.onProgress=(s,i,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})),l.load(d,c,u)})}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Fn(t,e));const l=this.loader=r?new r(i):new n(i),d=On(t,e);t.loader=l;const h=Dn(i.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:wt};e.stats=l.stats,l.load(d,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:i.data,networkDetails:o};s(d),a(d)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:dr({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}},_t=class extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}},Ct=class extends K{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},xt=class{constructor(t,e,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={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=s,this.size=i,this.part=r,this.partial=n}},Mt={length:0,start:()=>0,end:()=>0},Ot=class t{static isBuffered(e,s){if(e){const i=t.getBuffered(e);for(let t=i.length;t--;)if(s>=i.start(t)&&s<=i.end(t))return!0}return!1}static bufferedRanges(e){if(e){const s=t.getBuffered(e);return t.timeRangesToArray(s)}return[]}static timeRangesToArray(t){const e=[];for(let s=0;s<t.length;s++)e.push({start:t.start(s),end:t.end(s)});return e}static bufferInfo(e,s,i){if(e){const r=t.bufferedRanges(e);if(r.length)return t.bufferedInfo(r,s,i)}return{len:0,start:s,end:s,bufferedIndex:-1}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let i=-1,r=[];if(s)for(let d=0;d<t.length;d++){e>=t[d].start&&e<=t[d].end&&(i=d);const n=r.length;if(n){const e=r[n-1].end;t[d].start-e<s?t[d].end>e&&(r[n-1].end=t[d].end):r.push(t[d])}else r.push(t[d])}else r=t;let n,a=0,o=e,l=e;for(let d=0;d<r.length;d++){const t=r[d].start,h=r[d].end;if(-1===i&&e>=t&&e<=h&&(i=d),e+s>=t&&e<h)o=t,l=h,a=l-e;else if(e+s<t){n=t;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||Mt}catch(e){return Y.log("failed to get media.buffered",e),Mt}}},Ft=/\{\$([a-zA-Z0-9-_]+)\}/g,$t=/^(\d+)x(\d+)$/,Nt=/(.+?)=(".*?"|.*?)(?:,|$)/g,Ut=class t{constructor(e,s){"string"==typeof e&&(e=t.parseAttrList(e,s)),or(this,e)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const s=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)s[t]=parseInt(e.slice(2*t,2*t+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=$t.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let s;const i={};for(Nt.lastIndex=0;null!==(s=Nt.exec(t));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=Nn(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)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":Y.warn(`${t}: attribute ${r} is missing quotes`)}i[r]=n}return i}},Bt=class{constructor(t,e,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=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(i=null==e?void 0:e.tagOrder)?i:s,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){Y.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=or(new Ut({}),s,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);C(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(Y.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(C(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&C(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},Gt=class{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let s=e.decryptdata;return s||(e.setKeyFormat(t.keyFormat),s=e.decryptdata),!!s&&t.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&C(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let s=t.length;s--;)if(t[s].index>e)return t[s].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}},Kt="undefined"!=typeof self?self:void 0,Vt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ht={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"},Wt=null!=Kt&&null!=(rr=Kt.navigator)&&rr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null,Yt={},jt=class t{static clearKeyUriToKeyIdMap(){Yt={}}static setKeyIdForUri(t,e){Yt[t]=e}static addKeyIdForUri(t){const e=Object.keys(Yt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,e),Yt[t]=s,s}constructor(t,e,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Wn(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(pr(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Vn(t.keyFormatVersions,this.keyFormatVersions)&&Hn(t.iv,this.iv)&&Hn(t.keyId,this.keyId)}isSupported(){if(this.method){if(Wn(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ht.FAIRPLAY:case Ht.WIDEVINE:case Ht.PLAYREADY:case Ht.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,s){if(!this.encrypted||!this.uri)return null;if(Wn(this.method)){let s=this.iv;return s||("number"!=typeof e&&(Y.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),s=function(t){const e=new Uint8Array(16);for(let s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(e)),new t(this.method,this.uri,"identity",this.keyFormatVersions,s)}if(this.keyId){const e=Yt[this.uri];if(e&&!Vn(this.keyId,e)&&t.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Xn(this.uri);if(i)switch(this.keyFormat){case Ht.WIDEVINE:if(this.pssh=i,!this.keyId){const t=function(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32<s;){const s=Vr(new DataView(t,i));e.push(s),i+=s.size}}return e}(i.buffer);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=ea(s));break;case Ht.PLAYREADY:this.pssh=Kr(new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]),0,i),this.keyId=ta(i);break;default:{let t=i.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(t){const e=null==t?void 0:t[Ht.WIDEVINE];return e?e.keyId:null}(s),e||(e=ea(s),e||(e=Yt[this.uri])),e&&(this.keyId=e,t.setKeyIdForUri(this.uri,e))}return this}},qt=/#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,zt=/#EXT-X-MEDIA:(.*)/g,Xt=/^#EXT(?:INF|-X-TARGETDURATION):/m,Qt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Zt=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("|")),Jt=class t{static findGroup(t,e){for(let s=0;s<t.length;s++){const i=t[s];if(i.id===e)return i}}static resolve(t,e){return z.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Xt.test(t)}static parseMasterPlaylist(e,s){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:$n(e)},r=[];if(qt.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;null!=(n=qt.exec(e));)if(n[1]){var a;const e=new Ut(n[1],i),o=Nn(i,n[2]),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:t.resolve(o,s)},d=e.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),aa(e.CODECS,l);const h=e["SUPPLEMENTAL-CODECS"];h&&(l.supplemental={},aa(h,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),i.levels.push(l)}else if(n[3]){const e=n[3],r=n[4];switch(e){case"SESSION-DATA":{const t=new Ut(r,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=ra(r,s,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):Y.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":Un(i,new Ut(r,i),s);break;case"CONTENT-STEERING":{const e=new Ut(r,i);i.contentSteering={uri:t.resolve(e["SERVER-URI"],s),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=na(r)}}return i.levels=r.length>0&&r.length<i.levels.length?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,s,i){let r;const n={},a=i.levels,o={AUDIO:a.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:a.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(zt.lastIndex=0;null!==(r=zt.exec(e));){const e=new Ut(r[1],i),a=e.TYPE;if(a){const i=o[a],r=n[a]||[];n[a]=r;const d=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],c=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],g={attrs:e,bitrate:0,id:l++,groupId:e["GROUP-ID"]||"",name:e.NAME||d||"",type:a,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:d,url:e.URI?t.resolve(e.URI,s):""};if(h&&(g.assocLang=h),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const e=t.findGroup(i,g.groupId)||i[0];oa(g,e,"audioCodec"),oa(g,e,"textCodec")}r.push(g)}}return n}static parseLevelPlaylist(t,e,s,i,r,n){var a;const o={url:e},l=new Gt(e),d=l.fragments,h=[];let c,u,f,g,m=null,p=0,v=0,y=0,E=0,T=0,S=null,A=new J(i,o),L=-1,I=!1,b=null;if(Qt.lastIndex=0,l.m3u8=t,l.hasVariableRefs=$n(t),"#EXTM3U"!==(null==(a=Qt.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Qt.exec(t));){I&&(I=!1,A=new J(i,o),A.playlistOffset=y,A.setStart(y),A.sn=p,A.cc=E,T&&(A.bitrate=T),A.level=s,m&&(A.initSegment=m,m.rawProgramDateTime&&(A.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),b&&(A.setByteRange(b),b=null)));const t=c[1];if(t){A.duration=parseFloat(t);const e=(" "+c[2]).slice(1);A.title=e||null,A.tagList.push(e?["INF",t,e]:["INF",t])}else if(c[3]){if(C(A.duration)){A.playlistOffset=y,A.setStart(y),f&&ha(A,f,l),A.sn=p,A.level=s,A.cc=E,d.push(A);const t=(" "+c[3]).slice(1);A.relurl=Nn(l,t),la(A,S,h),S=A,y+=A.duration,p++,v=0,I=!0}}else{if(c=c[0].match(Zt),!c){Y.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const t=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(t){case"BYTERANGE":S?A.setByteRange(r,S):A.setByteRange(r);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=r,A.tagList.push(["PROGRAM-DATE-TIME",r]),-1===L&&(L=d.length);break;case"PLAYLIST-TYPE":l.type&&ca(l,t,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?ca(l,t,c):d.length>0&&ua(l,t,c),p=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&ca(l,t,c);const e=new Ut(r,l),s=e.decimalInteger("SKIPPED-SEGMENTS");if(C(s)){l.skippedSegments+=s;for(let t=s;t--;)d.push(null);p+=s}const i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&ca(l,t,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&ca(l,t,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||ca(l,t,c),l.live=!1;break;case"#":(r||a)&&A.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([t]);break;case"BITRATE":A.tagList.push([t,r]),T=1e3*parseInt(r),C(T)?A.bitrate=T:T=0;break;case"DATERANGE":{const t=new Ut(r,l),e=new Bt(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:Y.warn(`Ignoring invalid DATERANGE tag: "${r}"`),A.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new Ut(r,l);"IMPORT"in t?Bn(l,t,n):Un(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?ca(l,t,c):d.length>0&&ua(l,t,c),l.startCC=E=parseInt(r);break;case"KEY":{const t=ra(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=or({},f)),f[t.keyFormat]=t)}else Y.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=na(r);break;case"MAP":{const t=new Ut(r,l);if(A.duration){const e=new J(i,o);da(e,t,s,f),m=e,A.initSegment=m,m.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=m.rawProgramDateTime)}else{const e=A.byteRangeEndOffset;if(e){const t=A.byteRangeStartOffset;b=`${e-t}@${t}`}else b=null;da(A,t,s,f),m=A,I=!0}m.cc=E;break}case"SERVER-CONTROL":g&&ca(l,t,c),g=new Ut(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":l.partTarget&&ca(l,t,c),l.partTarget=new Ut(r).decimalFloatingPoint("PART-TARGET");break;case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,s=v++,i=new tt(new Ut(r,l),A,o,s,e);t.push(i),A.duration+=i.duration;break}case"PRELOAD-HINT":l.preloadHint=new Ut(r,l);break;case"RENDITION-REPORT":{const t=new Ut(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:Y.warn(`line parsed but not handled: ${c}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(la(A,S,h),A.cc=E,l.fragmentHint=A,f&&ha(A,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const R=d.length,k=d[0],D=d[R-1];if(y+=l.skippedSegments*l.targetduration,y>0&&R&&D){l.averagetargetduration=y/R;const t=D.sn;l.endSN="initSegment"!==t?t:0,l.live||(D.endList=!0),L>0&&(function(t,e){let s=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(d,L),k&&h.unshift(k))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,h.length&&l.dateRangeTagCount&&k&&sa(h,l),l.endCC=E,l}},te={toString:function(t){let e="";const s=t.length;for(let i=0;i<s;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e}},ee={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"},se=class extends Ct{constructor(t,e,s,i,r){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ee.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=Ot.bufferInfo(i||s,n,t.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${C(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===ee.ENDED)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,i=e.start-s,r=e.start+e.duration+s;if(o||r<a.start||i>a.end){const t=n>r;(n<i||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts)){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===ee.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Pt(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Dt(t.config)}registerListeners(){const{hls:t}=this;t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===ee.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ee.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const s=t.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=Ot.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>i&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return Ot.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;_a(s,"seeking",this.onMediaSeeking),_a(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===ee.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ca(i,"seeking",this.onMediaSeeking),Ca(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ee.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,s){this.startFragRequested=!0,this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,s=t.frag;this.fragContextChanged(s)?(e===ee.FRAG_LOADING||!this.fragCurrent&&e===ee.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=ee.IDLE):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger($.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==ee.STOPPED&&this.state!==ee.ERROR&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===At.APPENDING){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===At.PARTIAL&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger($.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:s,payload:i}=t,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&Wn(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,Yn(r.method)).catch(t=>{throw e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),t}).then(i=>{const r=self.performance.now();return e.trigger($.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),t.payload=i,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==ee.STOPPED&&this.state!==ee.ERROR&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state!==ee.STOPPED&&(this.state=ee.IDLE),t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var s,i;const r=t.tracks;if(r&&!e.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(s.message),!(!t||t.mediaKeys)&&(this.hls.trigger($.ERROR,{type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${s?te.toString(Ot.getBuffered(s)):"(detached)"})`),yr(t)){var i;if(t.type!==U.SUBTITLE){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=ee.IDLE)}const e=null==(i=this.levels)?void 0:i[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=ee.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),a=new xt(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,i){var r;this.fragCurrent=t;const n=e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key)t.encrypted||(a=this.keyLoader.loadClear(t,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=ee.KEY_LOADING,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger($.KEY_LOADED,t),this.state===ee.KEY_LOADING&&(this.state=ee.IDLE),t}),this.hls.trigger($.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(yr(t)&&(!o||t.sn!==o.sn)){const s=this.shouldLoadParts(e.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts&&yr(t)){const r=n.partList;if(r&&i){s>n.fragmentEnd&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,s);if(o>-1){const l=r[o];let d;return t=this.fragCurrent=l.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(t,!1,l)}) cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=ee.FRAG_LOADING,d=a?a.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,i)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,i).catch(t=>this.handleFragLoadError(t)),this.hls.trigger($.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}var l;if(yr(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),C(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ee.FRAG_LOADING;const d=this.config.progressive&&t.type!==U.SUBTITLE;let h;return h=d&&a?a.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,i)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,d?i:void 0),a]).then(([t])=>(!d&&i&&i(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger($.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,i).then(i=>{o[e.index]=i;const n=i.part;this.hls.trigger($.FRAG_LOADED,i);const a=Sa(s.details,t.sn,e.index+1)||Aa(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});d(a)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===F.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===O.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger($.ERROR,e)}else this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==ee.PARSING)return void(this.fragCurrent||this.state===ee.STOPPED||this.state===ee.ERROR||(this.state=ee.IDLE));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var s;const r=t.partList[0];if(r.fragment.type===U.SUBTITLE)return!1;var i;if(e>=r.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0)&&(this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?Sa(o,r,n):null,d=l?l.fragment:Ta(o,r,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,s,i,r){if(this.state!==ee.PARSING)return;const{data1:n,data2:a}=t;let o=n;if(a&&(o=Fr(n,a)),!o.length)return;const l=this.initPTS[e.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:t.type,frag:e,part:s,chunkMeta:i,offset:d,parent:e.type,data:o};if(this.hls.trigger($.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Ot.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const s=e.currentTime,i=Ot.bufferInfo(e,s,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,i.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var s;const i=this.getLoadPosition();if(!C(i))return null;const r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,r)}getFwdBufferInfoAtPos(t,e,s,i){const r=Ot.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-e,i);return Ot.bufferInfo(t,e,s)}}return r}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e),r=Math.max(t-3*e,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=U.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const s=this.hls.startPosition,i=this.hls.liveSyncPosition,r=o?(-1!==s&&s>=n?s:i)||o.start:t;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else t<=n&&(o=s[0]);if(!o){const s=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,s,e)}let d=this.filterReplacedPrimary(o,e);if(!d&&o){const t=o.sn-e.startSN;d=this.filterReplacedPrimary(s[t+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===At.OK||s===At.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,i,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==t&&s.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){var t;return!(!xa(this.config)||!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event))}filterReplacedPrimary(t,e){if(!t)return t;if(xa(this.config)&&t.type!==U.SUBTITLE){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(s.appendInPlace||Math.abs(t.start-i.start)>1||0===i.start)return null}else{if(t.end<=i.start&&!1===(null==e?void 0:e.live))return null;if(t.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||t.start-i.end>1))return null}}const r=null==s?void 0:s.playerQueue;if(r)for(let e=r.length;e--;){const s=r[e].interstitial;if(s.appendInPlace&&t.start>=s.startTime&&t.end<=s.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||(o.independent||n)&&o.fragment===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${o.start}`),i=a),r=l}return i}loadedEndOfParts(t,e){let s;for(let i=t.length;i--;){if(s=t[i],!s.loaded)return!1;if(e>s.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!C(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let i=0;i<t.length;++i){const r=t[i];if(Sn(e,s,r))return r}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=An(t,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,d=s.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;var u;(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),t<e)?c=En(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l):c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===At.OK||e===At.PARTIAL&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!h||d[0].fragment.sn>c.sn||!s.live)&&c.level===r.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==At.OK?e:null}}return c}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,n=!e,a=t.alignedSliding&&C(r);if(n||!a&&!r){!function(t,e){t&&(wa(e,t),e.alignedSliding||Pa(e,t),e.alignedSliding||e.skippedSegments||va(t,e,!1))}(s,t);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;s<e&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:t.startTimeOffset;null!==n&&C(n)?(s=e+n,n<0&&(s+=t.edge),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):t.live?(s=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var t;const{media:e}=this;let s=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?s=e.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&yr(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===ee.FRAG_LOADING_WAITING_RETRY)||(this.state=ee.IDLE)}onFragmentOrKeyLoadError(t,e){var s;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=e.details===F.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=e.errorAction;if(!a)return void(this.state=ee.ERROR);const{action:o,flags:l,retryCount:d=0,retryConfig:h}=a,c=!!h,u=c&&o===Et.RetryRequest,f=c&&!a.resolved&&l===Tt.MoveAllAlternatesMatchingHost,g=null==(s=this.hls.latestLevelDetails)?void 0:s.live;if(!u&&f&&yr(i)&&!i.endList&&g&&!bn(e))this.resetFragmentErrors(t),this.treatAsGap(i),a.resolved=!0;else if((u||f)&&d<h.maxNumRetry){var m;const s=Pn(null==(m=e.response)?void 0:m.code),r=kn(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=ee.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${r}ms`)}else if(h){if(this.resetFragmentErrors(t),!(d<h.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);n||o===Et.RemoveAlternatePermanently||(a.resolved=!0)}else o===Et.SendAlternateToPenaltyBox?this.state=ee.WAITING_LEVEL:this.state=ee.ERROR;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,s=e===1/0;(!e||t>=e||s&&!Pn(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ee.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===ee.PARSING||this.state===ee.PARSED){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===U.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ee.STOPPED&&(this.state=ee.IDLE)}afterBufferFlushed(t,e,s){if(!t)return;const i=Ot.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===ee.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ee.STOPPED&&(this.state=ee.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){const r=s.details;if(r){if(!Object.keys(t.elementaryStreams).reduce((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=i?0:ga(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger($.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1)){var n;const e=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===s.fragmentError||e&&(s.fragmentError<2||t.endList))&&this.treatAsGap(t,s),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=ee.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger($.FRAG_PARSED,{frag:t,part:e})}else this.warn("level.details undefined")}playlistLabel(){return this.playlistType===U.MAIN?"level":"track"}fragInfo(t,e=!0,s){var i,r;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${(null!=(i=e&&!s?t.startPTS:(s||t).start)?i:NaN).toFixed(3)}-${(null!=(r=e&&!s?t.endPTS:(s||t).end)?r:NaN).toFixed(3)}]${s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}},ie=class{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let i=0;for(let r=0;r<t.length;r++){const e=t[r];s.set(e,i),i+=e.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}},re={exports:{}},ae=vr((ne||(ne=1,function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||t,a),l=s?s+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,r,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,i),!0;case 4:return h.fn.call(h.context,e,i,r),!0;case 5:return h.fn.call(h.context,e,i,r,n),!0;case 6:return h.fn.call(h.context,e,i,r,n,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(t,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,e);break;case 3:h[d].fn.call(h[d].context,e,i);break;case 4:h[d].fn.call(h[d].context,e,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,i,r){var n=s?s+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==e||r&&!o[l].once||i&&o[l].context!==i)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(re)),re.exports)),oe="1.6.15",le={},de=10,he=10,ce=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({}),ue=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,s){}demux(t,e){this.cachedData&&(t=Fr(this.cachedData,t),this.cachedData=null);let s,i=$a(t,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?to(i):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&C(o))&&(this.basePTS=fe(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ce.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(n,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=l}else Ya(t,r)?(i=$a(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ce.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const e=t.slice(s);this.cachedData?this.cachedData=Fr(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:eo(),id3Track:a,textTrack:eo()}}demuxSampleAes(t,e,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:eo(),id3Track:this._id3Track,textTrack:eo()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},fe=(t,e,s)=>C(t)?90*t:9e4*e+(s?9e4*s.baseTime/s.timescale:0),ge=null,me=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],pe=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ve=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ye=[0,1,1,4],Ee=class extends ue{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const s=$a(t,0);let i=(null==s?void 0:s.length)||0;if(ao(t,i))return!1;for(let r=t.length;i<r;i++)if(Ka(t,i))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Na(t,e)&&Ba(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){Va(t,this.observer,e,s,t.manifestCodec);const i=Wa(t,e,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},Te=(t,e)=>{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],e+=1,i-=o}return s},Se=class extends ue{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=oo(t,e,s,this.basePTS,this.frameIndex);if(-1!==i)return{sample:t.samples[t.samples.length-1],length:i,missing:0}}static probe(t){if(!t)return!1;const e=$a(t,0);if(!e)return!1;const s=e.length;return 11===t[s]&&119===t[s+1]&&void 0!==to(e)&&Te(t,s)<16}},Ae=class extends ue{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=$a(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==to(e)&&Te(t,s)<=16)return!1;for(let i=t.length;s<i;s++)if(ao(t,s))return Y.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return ro(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return so(t,e,s,this.basePTS,this.frameIndex)}},Le=/\/emsg[-/]ID3/i,Ie=class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=eo("video",1),n=this.audioTrack=eo("audio",1),a=this.txtTrack=eo("text",1);if(this.id3Track=eo("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Dr(t);if(o.video){const{id:t,timescale:e,codec:s,supplemental:i}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s,r.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=it.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s<e;){const i=Lr(t,s);if(i>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=i>1?s+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Fr(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=Rr(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(s);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,e);return r.samples=$r(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=$r(t,e),{videoTrack:e,audioTrack:eo(),id3Track:i,textTrack:eo()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=Rr(t.samples,["emsg"]);i&&i.forEach(t=>{const i=function(t){const e=t[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==Sr(t.subarray(d,d+1));)s+=Sr(t.subarray(d,d+1)),d+=1;for(s+=Sr(t.subarray(d,d+1)),d+=1;"\0"!==Sr(t.subarray(d,d+1));)i+=Sr(t.subarray(d,d+1)),d+=1;i+=Sr(t.subarray(d,d+1)),d+=1,r=Lr(t,12),n=Lr(t,16),o=Lr(t,20),l=Lr(t,24),d=28}else if(1===e){d+=4,r=Lr(t,d),d+=4;const e=Lr(t,d);d+=4;const n=Lr(t,d);for(d+=4,a=2**32*e+n,x(a)||(a=Number.MAX_SAFE_INTEGER,Y.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Lr(t,d),d+=4,l=Lr(t,d),d+=4;"\0"!==Sr(t.subarray(d,d+1));)s+=Sr(t.subarray(d,d+1)),d+=1;for(s+=Sr(t.subarray(d,d+1)),d+=1;"\0"!==Sr(t.subarray(d,d+1));)i+=Sr(t.subarray(d,d+1)),d+=1;i+=Sr(t.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(Le.test(i.schemeIdUri)){const t=lo(i,e);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:ce.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=lo(i,e);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:ce.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(t,e,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}},be=class{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Dt(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,It.cbc)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}).catch(s)}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32||(this.decryptAacSample(t,e,s),this.decrypter.isSync())))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let i=0;for(let r=32;r<t.length-16;r+=160,i+=16)s.set(t.subarray(r,r+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let r=32;r<t.length-16;r+=160,i+=16)t.set(s.subarray(i,i+16),r);return t}decryptAvcSample(t,e,s,i,r){const n=Gr(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}).catch(i)}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}},Re=class{constructor(){this.VideoSample=null}createVideoSample(t,e,s){return{key:t,frame:!1,pts:e,dts:s,units:[],length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,s){const i=e.byteLength;let r=t.naluState||0;const n=r,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(e,0),r=0,h=1);h<i;)if(o=e[h++],r)if(1!==r)if(o)if(1===o){if(l=h-r-1,c>=0){const t={data:e.subarray(c,l),type:u};a.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(n&&h<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=Fr(s.data,e.subarray(0,l)),s.state=0))}h<i?(d=this.getNALuType(e,h),c=h,u=d,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const t={data:e.subarray(c,i),type:u,state:r};a.push(t)}if(0===a.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Fr(s.data,e))}return t.naluState=r,a}},ke=class{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&Y.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?s<<e|this.readBits(e):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},De=class extends Re{parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 1:{let e=!1;n=!0;const r=i.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;e&&null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Br(i.data,1,s.pts,e.samples);break;case 7:{var h,c;n=!0,o=!0;const e=i.data,s=this.readSPS(e);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(h=t.pixelRatio)?void 0:h[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:n=!0,t.pps=[i.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}a&&n&&a.units.push(i)}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new ke(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let s,i=8,r=8;for(let n=0;n<t;n++)0!==r&&(s=e.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(t){const e=new ke(t);let s,i,r,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=c();if(3===t&&f(1),m(),m(),f(1),u())for(i=3!==t?8:12,r=0;r<i;r++)u()&&p(r<6?16:64,e)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();m(),f(1);const E=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let A=[1,1];if(u()&&u())switch(d()){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=[d()<<8|d(),d()<<8|d()]}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}},we=class extends Re{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;n=!0,o&&null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Br(i.data,2,s.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=or(t.params,this.readVPS(i.data)),this.initVPS=i.data),t.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],i.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(i.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const s in e.params)t.params[s]=e.params[s]}this.pushParameterSet(t.sps,i.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(i.data);for(const s in e)t.params[s]=e[s]}this.pushParameterSet(t.pps,i.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:n=!1}a&&n&&a.units.push(i)}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let s=0;for(let i=0;i<t.byteLength;i++)i>=2&&3===t[i]&&0===t[i-1]&&0===t[i-2]||(e[s]=t[i],s++);return new Uint8Array(e.buffer,0,s)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ke(t);return e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6),{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new ke(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const s=e.readBits(3);e.readBoolean();const i=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let W=0;W<s;W++)v.push(e.readBoolean()),y.push(e.readBoolean());if(s>0)for(let W=s;W<8;W++)e.readBits(2);for(let W=0;W<s;W++)v[W]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[W]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),A=e.readBoolean();let L=0,I=0,b=0,R=0;A&&(L+=e.readUEG(),I+=e.readUEG(),b+=e.readUEG(),R+=e.readUEG());const k=e.readUEG(),D=e.readUEG(),w=e.readUEG();for(let W=e.readBoolean()?0:s;W<=s;W++)e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.readBoolean()&&e.readBoolean())for(let W=0;W<4;W++)for(let t=0;t<(3===W?2:6);t++)if(e.readBoolean()){const t=Math.min(64,1<<4+(W<<1));W>1&&e.readEG();for(let s=0;s<t;s++)e.readEG()}else e.readUEG();e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let _=0;for(let W=0;W<P;W++){let t=!1;if(0!==W&&(t=e.readBoolean()),t){W===P&&e.readUEG(),e.readBoolean(),e.readUEG();let t=0;for(let s=0;s<=_;s++){const s=e.readBoolean();let i=!1;s||(i=e.readBoolean()),(s||i)&&t++}_=t}else{const t=e.readUEG(),s=e.readUEG();_=t+s;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let i=0;i<s;i++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let s=0;s<t;s++){for(let t=0;t<w+4;t++)e.readBits(1);e.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,$=0;e.readBoolean(),e.readBoolean();let N=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),M=e.readBits(16))}if(e.readBoolean()&&e.readBoolean(),e.readBoolean()&&(e.readBits(3),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())),e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),N=e.readBoolean(),N&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG()),e.readBoolean()&&(F=e.readBits(32),$=e.readBits(32),e.readBoolean()&&e.readUEG(),e.readBoolean())){const t=e.readBoolean(),i=e.readBoolean();let r=!1;(t||i)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=s;n++){O=e.readBoolean();let s=!1;O||e.readBoolean()?e.readEG():s=e.readBoolean();const n=s?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(i)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let U=T,B=S;if(A){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),U=T-t*I-t*L,B=S-e*R-e*b}const G=i?["A","B","C"][i]:"",K=a<<24|o<<16|l<<8|d;let V=0;for(let W=0;W<32;W++)V=(V|(K>>W&1)<<31-W)>>>0;let H=V.toString(16);return 1===n&&"2"===H&&(H="6"),{codecString:`hvc1.${G}${n}.${H}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:$/F}},width:U,height:B,pixelRatio:[x,M]}}readPPS(t){const e=new ke(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2),e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const s=e.readBoolean(),i=e.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}},Pe=188,_e=class t{constructor(t,e,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=t,this.config=e,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,s){const i=t.syncOffset(e);return i>0&&s.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let s=Math.min(940,e-Pe)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<e;o+=Pe){if(71!==t[o]||e-o!==Pe&&71!==t[o+Pe]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-Pe)+1)),r||(r=0===ho(t,o)),r&&a>1&&(0===n&&a>2||o+Pe>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:it[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(e,s,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=t.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=t.createTrack("audio",r),this._id3Track=t.createTrack("id3"),this._txtTrack=t.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=s,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,s,i=!1,r=!1){let n;i||(this.sampleAes=null);const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack;let h=a.pid,c=a.pesData,u=o.pid,f=l.pid,g=o.pesData,m=l.pesData,p=null,v=this.pmtParsed,y=this._pmtId,E=e.length;if(this.remainderData&&(E=(e=Fr(this.remainderData,e)).length,this.remainderData=null),E<Pe&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};const T=Math.max(0,t.syncOffset(e));E-=(E-T)%Pe,E<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let S=0;for(let t=T;t<E;t+=Pe)if(71===e[t]){const s=!!(64&e[t+1]),r=ho(e,t);let E;if((48&e[t+3])>>4>1){if(E=t+5+e[t+4],E===t+Pe)continue}else E=t+4;switch(r){case h:s&&(c&&(n=mo(c,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,d,n,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(E,t+Pe)),c.size+=t+Pe-E);break;case u:if(s){if(g&&(n=mo(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}g={data:[],size:0}}g&&(g.data.push(e.subarray(E,t+Pe)),g.size+=t+Pe-E);break;case f:s&&(m&&(n=mo(m,this.logger))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(e.subarray(E,t+Pe)),m.size+=t+Pe-E);break;case 0:s&&(E+=e[E]+1),y=this._pmtId=co(e,E);break;case y:{s&&(E+=e[E]+1);const r=uo(e,E,this.typeSupported,i,this.observer,this.logger);h=r.videoPid,h>0&&(a.pid=h,a.segmentCodec=r.segmentVideoCodec),u=r.audioPid,u>0&&(o.pid=u,o.segmentCodec=r.segmentAudioCodec),f=r.id3Pid,f>0&&(l.pid=f),null===p||v||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${p}'. Backtracking to sync byte @${T} to parse all TS packets.`),p=null,t=T-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=r}}else S++;S>0&&fo(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=c,o.pesData=g,l.pesData=m;const A={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(A),A}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:s,id3Track:i,textTrack:r}=t,n=s.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=mo(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,a&&(l=mo(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=mo(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,s){const i=this.demux(t,s,!0,!this.config.progressive),r=this.sampleAes=new be(this.observer,this.config,e);return this.decrypt(i,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new De:"hevc"===t&&(this.videoParser=new we))}decrypt(t,e){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{s(t)}):s(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{s(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let s=0;const i=this.aacOverFlow;let r,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,r=i.sample.unit.byteLength;if(-1===e)o=Fr(i.sample.unit,o);else{const n=r-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!Ga(o,r);r++);if(r!==s){let t;const e=r<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",fo(this.observer,new Error(t),e,this.logger),!e)return}if(Va(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Ha(t.samplerate);a=i.sample.pts+e}}let l,d=0;for(;r<n;){if(l=Wa(t,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!Ga(o,r);r++);}}parseMPEGPES(t,e){const s=e.data,i=s.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(no(s,n)){const e=so(t,s,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const s=e.data,i=e.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=oo(t,s,o,i,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=or({},e,{type:this._videoTrack?ce.emsg:ce.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}},Ce=class{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}},xe=Math.pow(2,32)-1,(Me=class t{static init(){let e;for(e in t.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:[]},t.types)t.types.hasOwnProperty(e)&&(t.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);t.HDLR_TYPES={video: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]),audio: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])};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);t.STTS=t.STSC=t.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),t.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),t.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),t.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),t.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),r=new Uint8Array([97,118,99,49]),n=new Uint8Array([0,0,0,1]);t.FTYP=t.box(t.types.ftyp,i,n,i,r),t.DINF=t.box(t.types.dinf,t.box(t.types.dref,s))}static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),i=0,s=8;i<r;i++)n.set(e[i],s),s+=e[i].byteLength;return n}static hdlr(e){return t.box(t.types.hdlr,t.HDLR_TYPES[e])}static mdat(e){return t.box(t.types.mdat,e)}static mdhd(e,s){s*=e;const i=Math.floor(s/(xe+1)),r=Math.floor(s%(xe+1));return t.box(t.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,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return t.box(t.types.mdia,t.mdhd(e.timescale||0,e.duration||0),t.hdlr(e.type),t.minf(e))}static mfhd(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))}static moof(e,s,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,s))}static moov(e){let s=e.length;const i=[];for(;s--;)i[s]=t.trak(e[s]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(t.mvex(e)))}static mvex(e){let s=e.length;const i=[];for(;s--;)i[s]=t.trex(e[s]);return t.box.apply(null,[t.types.mvex,...i])}static mvhd(e,s){s*=e;const i=Math.floor(s/(xe+1)),r=Math.floor(s%(xe+1)),n=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,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,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 t.box(t.types.mvhd,n)}static sdtp(e){const s=e.samples||[],i=new Uint8Array(4+s.length);let r,n;for(r=0;r<s.length;r++)n=s[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return t.box(t.types.sdtp,i)}static stbl(e){return t.box(t.types.stbl,t.stsd(e),t.box(t.types.stts,t.STTS),t.box(t.types.stsc,t.STSC),t.box(t.types.stsz,t.STSZ),t.box(t.types.stco,t.STCO))}static avc1(e){let s,i,r,n=[],a=[];for(s=0;s<e.sps.length;s++)i=e.sps[s],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));for(s=0;s<e.pps.length;s++)i=e.pps[s],r=i.byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));const o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(a))),l=e.width,d=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return t.box(t.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,l>>8&255,255&l,d>>8&255,255&d,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,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const e=t.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,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(e){return t.box(t.types.mp4a,t.audioStsd(e),t.box(t.types.esds,t.esds(e)))}static mp3(e){return t.box(t.types[".mp3"],t.audioStsd(e))}static ac3(e){return t.box(t.types["ac-3"],t.audioStsd(e),t.box(t.types.dac3,e.config))}static stsd(e){const{segmentCodec:s}=e;if("audio"===e.type){if("aac"===s)return t.box(t.types.stsd,t.STSD,t.mp4a(e));if("ac3"===s&&e.config)return t.box(t.types.stsd,t.STSD,t.ac3(e));if("mp3"===s&&"mp3"===e.codec)return t.box(t.types.stsd,t.STSD,t.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===s)return t.box(t.types.stsd,t.STSD,t.avc1(e));if("hevc"===s&&e.vps)return t.box(t.types.stsd,t.STSD,t.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${s}/${e.codec})`)}static tkhd(e){const s=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(i/(xe+1)),o=Math.floor(i%(xe+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,s>>24&255,s>>16&255,s>>8&255,255&s,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,r>>8&255,255&r,0,0,n>>8&255,255&n,0,0]))}static traf(e,s){const i=t.sdtp(e),r=e.id,n=Math.floor(s/(xe+1)),a=Math.floor(s%(xe+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),t.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))}static trex(e){const s=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,s){const i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n);let o,l,d,h,c,u;for(s+=8+n,a.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s],0),o=0;o<r;o++)l=i[o],d=l.duration,h=l.size,c=l.flags,u=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,255&d,h>>>24&255,h>>>16&255,h>>>8&255,255&h,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*o);return t.box(t.types.trun,a)}static initSegment(e){t.types||t.init();const s=t.moov(e);return Fr(t.FTYP,s)}static hvc1(e){const s=e.params,i=[e.vps,e.sps,e.pps],r=new Uint8Array([1,s.general_profile_space<<6|(s.general_tier_flag?32:0)|s.general_profile_idc,s.general_profile_compatibility_flags[0],s.general_profile_compatibility_flags[1],s.general_profile_compatibility_flags[2],s.general_profile_compatibility_flags[3],s.general_constraint_indicator_flags[0],s.general_constraint_indicator_flags[1],s.general_constraint_indicator_flags[2],s.general_constraint_indicator_flags[3],s.general_constraint_indicator_flags[4],s.general_constraint_indicator_flags[5],s.general_level_idc,240|s.min_spatial_segmentation_idc>>8,255&s.min_spatial_segmentation_idc,252|s.parallelismType,252|s.chroma_format_idc,248|s.bit_depth_luma_minus8,248|s.bit_depth_chroma_minus8,0,parseInt(s.frame_rate.fps),3|s.temporal_id_nested<<2|s.num_temporal_layers<<3|(s.frame_rate.fixed?64:0),i.length]);let n=r.length;for(let t=0;t<i.length;t+=1){n+=3;for(let e=0;e<i[t].length;e+=1)n+=2+i[t][e].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=i.length-1;for(let t=0;t<i.length;t+=1){a.set(new Uint8Array([32+t|(t===o?128:0),0,i[t].length]),n),n+=3;for(let e=0;e<i[t].length;e+=1)a.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),n),n+=2,a.set(i[t][e],n),n+=i[t][e].length}const l=t.box(t.types.hvcC,a),d=e.width,h=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return t.box(t.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,d>>8&255,255&d,h>>8&255,255&h,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,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}}).types=void 0,Me.HDLR_TYPES=void 0,Me.STTS=void 0,Me.STSC=void 0,Me.STCO=void 0,Me.STSZ=void 0,Me.VMHD=void 0,Me.SMHD=void 0,Me.STSD=void 0,Me.FTYP=void 0,Me.DINF=void 0,Oe=9e4,Fe=null,$e=null,Ne=class extends K{constructor(t,e,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===Fe){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fe=t?parseInt(t[1]):0}if(null===$e){const t=navigator.userAgent.match(/Safari\/(\d+)/i);$e=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?yo(e):e} > ${t?yo(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t[0].pts,i=t.reduce((t,i)=>{let r=i.pts,n=r-t;return n<-4294967296&&(e=!0,r=To(r,s),n=r-t),n>0?t:r},s);return e&&this.debug("PTS rollover detected"),i}remux(t,e,s,i,r,n,a,o){let l,d,h,c,u,f,g=r,m=r;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,I;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(A=t.pixelRatio)?void 0:A[0])||(null==(L=e.pixelRatio)?void 0:L[1])!==(null==(I=t.pixelRatio)?void 0:I[1]))||!t&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,r,n));const s=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const s=this.getVideoStartPts(e.samples),i=(To(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,r,n)),d=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===U.AUDIO?m:void 0),T){const i=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,s,i)}}else T&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=So(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Ao(i,r,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:c,id3:u}}computeInitPts(t,e,s,i){const r=Math.round(s*e);let n=To(t,r);if(n<r+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${i}`);n<r+e;)n+=8589934592;return n-r}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,c,u=!l||i,f="audio/mp4",g=-1;if(u&&(d=h=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Me.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(g=t.id,c=t.inputTimeScale,l&&c===l.timescale?u=!1:d=h=this.computeInitPts(r[0].pts,c,s,"audio"))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Me.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(g=e.id,c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=To(n[0].dts,t),i=this.computeInitPts(e,c,s,"video"),r=this.computeInitPts(t,c,s,"video");h=Math.min(h,i),d=Math.min(d,r)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/c} (${d}/${c}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:c,trackId:g},this._initDTS={baseTime:h,timescale:c,trackId:g}):d=c=void 0,{tracks:o,initPTS:d,timescale:c,trackId:g}}remuxVideo(t,e,s,i){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let h,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!s||null===u){const t=d+e*r,i=n[0].pts-To(n[0].dts,n[0].pts);Fe&&null!==u&&Math.abs(t-i-(u+d))<15e3?s=!0:u=t-i-d}const y=u+d;for(let M=0;M<o;M++){const t=n[M];t.pts=To(t.pts,y),t.dts=To(t.dts,y),t.dts<n[M>0?M-1:M].dts&&(v=!0)}v&&n.sort(function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i}),h=n[0].dts,c=n[n.length-1].dts;const E=c-h,T=E?Math.round(E/(o-1)):g||t.inputTimeScale/30;if(s){const s=h-y,i=s>T,r=s<-1;if((i||r)&&(i?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${vo(s,!0)} ms (${s}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${vo(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||y>=n[0].pts||Fe)){h=y;const t=n[0].pts-s;if(i)n[0].dts=h,n[0].pts=t;else{let e=!0;for(let i=0;i<n.length&&!(n[i].dts>t&&e);i++){const t=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i<n.length-1){const s=n[i+1].pts;e=s<=n[i].pts==s<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${vo(t,!0)}/${vo(h,!0)}, delta: ${vo(s,!0)} ms`)}}h=Math.max(0,h);let S=0,A=0,L=h;for(let M=0;M<o;M++){const t=n[M],e=t.units,s=e.length;let i=0;for(let r=0;r<s;r++)i+=e[r].data.length;A+=i,S+=s,t.length=i,t.dts<L?(t.dts=L,L+=T/4|0||1):L=t.dts,m=Math.min(t.pts,m),p=Math.max(t.pts,p)}c=n[o-1].dts;const I=A+4*S+8;let b;try{b=new Uint8Array(I)}catch(x){return void this.observer.emit($.ERROR,$.ERROR,{type:O.MUX_ERROR,details:F.REMUX_ALLOC_ERROR,fatal:!1,error:x,bytes:I,reason:`fail allocating video mdat ${I}`})}const R=new DataView(b.buffer);R.setUint32(0,I),b.set(Me.types.mdat,4);let k=!1,D=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY;for(let M=0;M<o;M++){const t=n[M],e=t.units;let s,l=0;for(let i=0,r=e.length;i<r;i++){const t=e[i],s=t.data,r=t.data.byteLength;R.setUint32(f,r),f+=4,b.set(s,f),f+=r,l+=4+r}if(M<o-1)g=n[M+1].dts-t.dts,s=n[M+1].pts-t.pts;else{const e=this.config,a=M>0?t.dts-n[M-1].dts:T;if(s=M>0?t.pts-n[M-1].pts:T,e.stretchShortVideoTrack&&null!==this.nextAudioTs){const s=Math.floor(e.maxBufferHole*r),n=(i?m+i*r:this.nextAudioTs+d)-t.pts;n>s?(g=n-a,g<0?g=a:k=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const h=Math.round(t.pts-t.dts);D=Math.min(D,g),P=Math.max(P,g),w=Math.min(w,s),_=Math.max(_,s),a.push(Eo(t.key,g,l,h))}if(a.length)if(Fe){if(Fe<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if($e&&_-w<P-D&&T/P<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=h;for(let e=0,s=a.length;e<s;e++){const i=t+a[e].duration,r=t+a[e].cts;if(e<s-1){const t=i+a[e+1].cts;a[e].duration=t-r}else a[e].duration=e?a[e-1].duration:T;a[e].cts=0,t=i}}g=k||!g?T:g,this.nextVideoTs=u=c+g-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const C={data1:Me.moof(t.sequenceNumber++,h,or(t,{samples:a})),data2:b,startPTS:(m-d)/r,endPTS:(p+g-d)/r,startDTS:(h-d)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,C}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,s,i,r){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,d=this._initPTS,h="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=t.samples,g=h?0:8,m=this.nextAudioTs||-1;const p=d.baseTime*n/d.timescale,v=p+e*n;if(this.isAudioContiguous=s=s||f.length&&m>0&&(i&&Math.abs(v-(m+p))<9e3||Math.abs(To(f[0].pts,v)-(m+p))<20*l),f.forEach(function(t){t.pts=To(t.pts,v)}),!s||m<0){const t=f.length;if(f=f.filter(t=>t.pts>=0),t!==f.length&&this.warn(`Removed ${f.length-t} of ${t} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===r?0:i&&!u?Math.max(0,v-p):f[0].pts-p}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=m+p;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,d=Math.abs(1e3*o/n);if(o<=-e*l&&u)0===s&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=m=a-p,i=a);else if(o>=e*l&&d<1e4&&u){let e=Math.round(o/l);for(i=a-e*l;i<0&&e&&l;)e--,i+=l;0===s&&(this.nextAudioTs=m=i-p),this.warn(`Injecting ${e} audio frames @ ${((i-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){let e=Ce.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),f.splice(s,0,{unit:e,pts:i}),i+=l,s++}}r.pts=i,i+=l}}let y,E=null,T=null,S=0,A=f.length;for(;A--;)S+=f[A].unit.byteLength;for(let P=0,_=f.length;P<_;P++){const e=f[P],i=e.unit;let r=e.pts;if(null!==T)c[P-1].duration=Math.round((r-T)/a);else{if(s&&"aac"===t.segmentCodec&&(r=m+p),E=r,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(w){return void this.observer.emit($.ERROR,$.ERROR,{type:O.MUX_ERROR,details:F.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:S,reason:`fail allocating audio mdat ${S}`})}h||(new DataView(y.buffer).setUint32(0,S),y.set(Me.types.mdat,4))}y.set(i,g);const n=i.byteLength;g+=n,c.push(Eo(!0,o,n,0)),T=r}const L=c.length;if(!L)return;const I=c[c.length-1];m=T-p,this.nextAudioTs=m+a*I.duration;const b=h?new Uint8Array(0):Me.moof(t.sequenceNumber++,E/a,or({},t,{samples:c}));t.samples=[];const R=(E-p)/n,k=this.nextAudioTs/n,D={data1:b,data2:y,startPTS:R,endPTS:k,startDTS:R,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,D}},Ue=class extends K{constructor(t,e,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(t,i),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:s,videoCodec:i}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=Dr(t);if(e)!function(t,e){if(!t||!e)return;const s=e.keyId;s&&e.isCommonEncryption&&Mr(t,(t,e)=>{const i=t.subarray(8,24);i.some(t=>0!==t)||(Y.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${mr(i)} -> ${mr(s)}`),t.set(s,8))})}(t,e);else{const t=r||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(s=Io(r,Q.AUDIO,this)),n&&(i=Io(n,Q.VIDEO,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:r?a.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,e,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};C(d)||(d=this.lastEndTime=r||0);const c=e.samples;if(!c.length)return h;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e,s){const i={},r=Rr(t,["moof","traf"]);for(let n=0;n<r.length;n++){const t=r[n],a=Rr(t,["tfhd"])[0],o=Lr(a,4),l=e[o];if(!l)continue;i[o]||(i[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=i[o],h=Rr(t,["tfdt"])[0];if(h){const t=h[0];let e=Lr(h,4);1===t&&(e===et?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=et+1,e+=Lr(h,8))),C(e)&&(!C(d.start)||e<d.start)&&(d.start=e)}const c=l.default,u=Lr(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=Lr(a,2&u?12:8));const g=Rr(t,["trun"]);let m=d.start||0,p=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],s=Lr(t,4),i=d.sampleCount;d.sampleCount+=s;const r=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],h=8&t[2];let c=8,u=s;for(r&&(c+=4),n&&s&&(1&t[c+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=i),c+=4,a?(v=Lr(t,c),c+=4):v=f,o&&(c+=4),h&&(c+=4),m+=v,p+=v,u--);u--;)a?(v=Lr(t,c),c+=4):v=f,o&&(c+=4),l&&(1&t[c+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(u+1),d.keyFrameStart=m),c+=4),h&&(c+=4),m+=v,p+=v;!p&&f&&(p+=f*s)}d.duration+=p}if(!Object.keys(i).some(t=>i[t].duration)){let e=1/0,s=0;const r=Rr(t,["sidx"]);for(let t=0;t<r.length;t++){const i=kr(r[t]);if(null!=i&&i.references){e=Math.min(e,i.earliestPresentationTime/i.timescale);const t=i.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+i.earliestPresentationTime/i.timescale)}}s&&C(s)&&Object.keys(i).forEach(t=>{i[t].duration||(i[t].duration=s*i[t].timescale-i[t].start)})}return i}(c,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,v=Lo(p,1/0),y=Lo(m,1/0),E=Lo(p,0,!0),T=Lo(m,0,!0);let S=r,A=0;const L=m&&(!p||!l&&y<v||l&&l.trackId===f.audio.id),I=L?m:p;if(I){const t=I.timescale,e=I.start-r*t,s=L?f.audio.id:f.video.id;S=I.start/t,A=L?T-y:E-v,!n&&l||!function(t,e,s,i){if(null===t)return!0;const r=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>r}(l,S,r,A)&&t===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${e/t} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${S-r} (${e}/${t}) trackId: ${s}`),l=null,u.initPTS=e,u.timescale=t,u.trackId=s)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=S,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const b=S-l.baseTime/l.timescale,R=b+A;A>0?this.lastEndTime=R:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const k=!!f.audio,D=!!f.video;let w="";k&&(w+="audio"),D&&(w+="video");const P={data1:c,startPTS:b,startDTS:b,endPTS:R,endDTS:R,type:w,hasAudio:k,hasVideo:D,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=k&&!D?P:void 0,h.video=D?P:void 0;const _=null==p?void 0:p.sampleCount;if(_){const t=p.keyFrameIndex,e=-1!==t;P.nb=_,P.dropped=0===t||this.isVideoContiguous?0:e?t:_,P.independent=e,P.firstKeyFrame=t,e&&p.keyFrameStart&&(P.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),P.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${_} dropped: ${P.dropped} start: ${P.firstKeyFramePTS||"NA"}`)}return h.initSegment=u,h.id3=So(s,r,l,l),i.samples.length&&(h.text=Ao(i,r,l)),h}};try{Be=self.performance.now.bind(self.performance)}catch(nr){Be=Date.now}(Ge=[{demux:Ie,remux:Ue},{demux:_e,remux:Ne},{demux:Ee,remux:Ne},{demux:Ae,remux:Ne}]).splice(2,0,{demux:Se,remux:Ne}),Ke=class{constructor(t,e,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=t,this.typeSupported=e,this.config=s,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,i){const r=s.transmuxing;r.executeStart=Be();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,E=function(t,e){let s=null;return t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e),s}(n,e);if(E&&Wn(E.method)){const t=this.getDecrypter(),e=Yn(E.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,e).then(t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e}),this.decryptionPromise;{let i=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer,e);if(s.part>-1){const e=t.flush();i=e?e.buffer:e}if(!i)return r.executeEnd=Be(),Ve(s);n=new Uint8Array(i)}}const T=this.needsProbing(d,h);if(T){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit($.ERROR,$.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=Be(),Ve(s)}(d||h||f||T)&&this.resetInitSegment(y,g,m,v,e),(d||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,u,c,s);this.asyncResult=bo(S);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Be(),S}flush(t){const e=t.transmuxing;e.executeStart=Be();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Be();const s=[Ve(t)];return this.asyncResult?Promise.resolve(s):s}const d=o.flush(a);return bo(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===U.MAIN?"level":"track"} ${s.level}`);const d=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=Be()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,i,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer.demuxSampleAes(t,e,s).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i}=this;let r;for(let h=0,c=Ge.length;h<c;h++){var n;if(null!=(n=Ge[h].demux)&&n.probe(t,this.logger)){r=Ge[h];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;o&&o instanceof l||(this.remuxer=new l(s,e,i,this.logger)),a&&a instanceof d||(this.demuxer=new d(s,e,i,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Dt(this.config)),t}},Ve=t=>({remuxResult:{},chunkMeta:t}),He=class{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}},We=class{constructor(t,e,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}},Ye=0,je=class{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ye++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,s=this.hls;if(s&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":s.logger[e.data.logType]&&s.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,s.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===$.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new ae,this.observer.on($.FRAG_DECRYPTED,n),this.observer.on($.ERROR,n);const a=tn(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=le[t];if(e)return e.clientCount++,e;const s=new self.URL(t,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return le[t]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=le[oe];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(e),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return le[oe]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:pt(r)})}catch(nr){s.warn(`Error setting up "${e}" Web Worker, fallback to inline`,nr),this.terminateWorker(),this.error=null,this.transmuxer=new Ke(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new Ke(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Ye++;const e=this.hls.config,s=tn(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:pt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=le[t||oe];if(e&&1===e.clientCount--){const{worker:s,objectURL:i}=e;delete le[t||oe],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!(p&&r.cc===p.cc),y=!(p&&l.level===p.level),E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!y&&(1===E||0===E&&(1===T||S&&T<=0)),L=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!T&&A||(n.stats.parsing.start=L);const I=!(p&&(null==(h=r.initSegment)?void 0:h.url)===(null==(c=p.initSegment)?void 0:c.url)),b=new We(v,A,o,y,g,I);if(!A||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===U.MAIN?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const t=new He(s,i,e,a,d);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,b);bo(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(s){const e=s.flush(t);bo(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}},qe=class extends se{constructor(t,e,s){super(t,e,s,"audio-stream-controller",U.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:t}=this;t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on($.BUFFER_RESET,this.onBufferReset,this),t.on($.BUFFER_CREATED,this.onBufferCreated,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on($.FRAG_LOADING,this.onFragLoading,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off($.BUFFER_RESET,this.onBufferReset,this),t.off($.BUFFER_CREATED,this.onBufferCreated,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off($.FRAG_LOADING,this.onFragLoading,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r,trackId:n}){if(s===U.MAIN){const t=e.cc,s=this.fragCurrent;if(this.initPTS[t]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${t} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=e,this.state===ee.WAITING_INIT_PTS){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==t)&&this.syncWithAnchor(e,null==s?void 0:s.frag)}else!this.hls.hasEnoughToStart&&s&&s.cc!==t?(s.abortRequests(),this.syncWithAnchor(e,s)):this.state===ee.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(e&&(null==i?void 0:i.cc)===e.cc)return;const r=(i||t).cc,n=An(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===ee.IDLE&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=ee.STOPPED);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s,this.state=ee.IDLE):this.state=ee.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case ee.IDLE:this.doTickIdle();break;case ee.WAITING_TRACK:{const{levels:t,trackId:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=ee.WAITING_INIT_PTS}break}case ee.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case ee.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=ee.FRAG_LOADING;const t={frag:e,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=ee.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:s,media:i,trackId:r}=this,n=e.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=ee.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Q.AUDIO,U.AUDIO));const d=this.getFwdBufferInfo(l,U.AUDIO);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return e.trigger($.BUFFER_EOS,{type:"audio"}),void(this.state=ee.ENDED);const h=d.len,c=e.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:d.end;if(this.switchingTrack&&i){const t=g;o.PTSKnown&&t<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(h>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,d,U.MAIN,c)),!p)return void(this.bufferFlushed=!0);let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&yr(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===At.OK&&(this.mainFragLoading=v=null),v&&yr(v))){if(p.start>v.end){const t=this.fragmentTracker.getFragAtPos(m,U.MAIN);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new gt(t))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==ee.STOPPED&&(this.setInterval(100),this.state=ee.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded($.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,e){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=e;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==ee.STOPPED&&(this.state=ee.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=i[n];let h=0;if(r.live||null!=(s=d.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;d.details&&(h=this.alignPlaylists(r,d.details,null==(c=this.levelLastLoaded)?void 0:c.details)),r.alignedSliding||(wa(r,l),r.alignedSliding||Pa(r,l),h=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger($.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==ee.WAITING_TRACK||this.waitForCdnTuneIn(r)||(this.state=ee.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const h=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new je(this.hls,U.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new xt(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n);c.push(r,f,h,"",s,i,d.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new ie,complete:!1};t.push(new Uint8Array(r)),this.state!==ee.STOPPED&&(this.state=ee.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===U.MAIN&&yr(e.frag)&&(this.mainFragLoading=e,this.state===ee.IDLE&&this.tick())}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===U.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(yr(s)){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger($.AUDIO_TRACK_SWITCHED,dr({},t)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==U.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var s;if(e.fatal)this.state=ee.ERROR;else switch(e.details){case F.FRAG_GAP:case F.FRAG_PARSING_ERROR:case F.FRAG_DECRYPT_ERROR:case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.AUDIO,e);break;case F.AUDIO_TRACK_LOAD_ERROR:case F.AUDIO_TRACK_LOAD_TIMEOUT:case F.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ee.WAITING_TRACK||(null==(s=e.context)?void 0:s.type)!==N.AUDIO_TRACK||(this.state=ee.IDLE);break;case F.BUFFER_ADD_CODEC_ERROR:case F.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case F.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case F.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Q.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Q.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ee.ENDED&&(this.state=ee.IDLE);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,U.AUDIO),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:h}=d,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&h){if(this.state=ee.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,t,n),i.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}if(c){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[Q.AUDIO]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(Q.AUDIO,t,e,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=or({id:s,frag:o,details:h},f);i.trigger($.FRAG_PARSING_METADATA,t)}if(u){const t=or({id:s,frag:o,details:h},u);i.trigger($.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s,i){if(this.state!==ee.PARSING)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=U.AUDIO;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger($.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger($.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||i===At.NOT_LOADED||i===At.PARTIAL)if(yr(t))if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=ee.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==e.details.fragmentStart&&Pa(e.details,s)}else super.loadFragment(t,e,s);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;mn({name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},t,pn)||(yn(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger($.AUDIO_TRACK_SWITCHED,dr({},t))}},ze=class extends K{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let n=-1;for(let s=0;s<i.length;s++){const a=i[s];let o;try{o=new self.URL(a.URI,e.url).href}catch(r){this.warn(`Could not construct new URL for Rendition Report: ${r}`),o=a.URI||""}if(o===t){n=s;break}o===t.substring(0,o.length)&&(n=s)}if(-1!==n){const t=i[n],r=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=s&&ln(s);return new ft(r,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return t}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const t=Math.max(o||0,0);i.appliedTimelineOffset=t,i.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(i.live||null!=s&&s.live){const o="levelInfo"in e?e.levelInfo:e.track;if(i.reloaded(s),s&&i.fragments.length>0){ma(s,i,this);const t=i.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=e;return void s.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,c=Ea(i,1e3*(i.edge-h));if(i.requestScheduled+c<n?i.requestScheduled=n:i.requestScheduled+=c,this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let u,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,d=r===a;-1!==l?d?(f=a+1,g=t?0:l):(f=r,g=t?l+1:i.maxPartIndex):f=a+1;const h=i.age,c=h+i.ageHeader;let m=Math.min(c-i.partTarget,1.5*i.targetduration);if(m>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${m} with playlist age: ${i.age}`),m=0;else{const t=Math.floor(m/i.targetduration);f+=t,void 0!==g&&(g+=Math.round(m%i.targetduration/i.partTarget)),this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${m} skip sn ${t} to part ${g}`)}i.tuneInGoal=m}if(u=this.getDeliveryDirectives(i,e.deliveryDirectives,f,g),t||!d)return i.requestScheduled=n,void this.loadingPlaylist(o,u)}else(i.canBlockReload||i.canSkipUntil)&&(u=this.getDeliveryDirectives(i,e.deliveryDirectives,f,g));u&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,i)}else this.clearTimer()}scheduleLoading(t,e,s){const i=s||t.details;if(!i)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,s,i){let r=ln(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=ut.No),new ft(s,i,r)}checkRetry(t){const e=t.details,s=Ln(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Et.RetryRequest||!i.resolved&&r===Et.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=kn(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}},Xe=class extends ze{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVEL_LOADING,this.onLevelLoading,this),t.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off($.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=gn(e,t,pn);if(s>-1)r=t[s];else{const t=gn(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger($.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==N.AUDIO_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&mn(t,i,pn))return i;const r=gn(t,this.tracksInGroup,pn);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=vn(e,i,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==d)return!1;const i=e.audioGroups;return gn(t,s.filter(t=>!i||-1!==i.indexOf(t.groupId)),r)>-1});return h>-1?h:vn(e,i,e=>{const i=e.audioGroups;return gn(t,s.filter(t=>!i||-1!==i.indexOf(t.groupId)),r)>-1})}(t,e.levels,s,i,pn);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=gn(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t],r=i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger($.AUDIO_TRACK_SWITCHING,dr({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if((!this.selectDefaultTrack||i.default)&&(!t||mn(t,i,pn)))return s}if(t){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++)if(mn({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],pn))return t;for(let l=0;l<e.length;l++){const s=e[l];if(ko(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<e.length;l++){const s=e[l];if(ko(t.attrs,s.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&yn(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger($.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}},Qe=class{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const s={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const s={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const s=null==(e=t[0])?void 0:e.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){null!==this.queues&&this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const r=e[0];try{r.execute()}catch(i){var s;if(r.onError(i),null===this.queues||null===this.tracks)return;const e=null==(s=this.tracks[t])?void 0:s.buffer;null!=e&&e.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,s;return null!=(e=this.queues)&&e[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const s=null==(e=this.tracks)?void 0:e[t],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}},Ze=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Je="HlsJsTrackRemovedError",ts=class extends Error{constructor(t){super(t),this.name=Je}},es=class extends K{constructor(t,e){var s;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:s}=this;t&&this.log("Media source opened"),e&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger($.MEDIA_ATTACHED,{media:e,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(s=ur(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.BUFFER_RESET,this.onBufferReset,this),t.on($.BUFFER_APPENDING,this.onBufferAppending,this),t.on($.BUFFER_CODECS,this.onBufferCodecs,this),t.on($.BUFFER_EOS,this.onBufferEos,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.FRAG_PARSED,this.onFragParsed,this),t.on($.FRAG_CHANGED,this.onFragChanged,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.BUFFER_RESET,this.onBufferReset,this),t.off($.BUFFER_APPENDING,this.onBufferAppending,this),t.off($.BUFFER_CODECS,this.onBufferCodecs,this),t.off($.BUFFER_EOS,this.onBufferEos,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.FRAG_PARSED,this.onFragParsed,this),t.off($.FRAG_CHANGED,this.onFragChanged,this),t.off($.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const s={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===e?or(s,i.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(s[e]=or({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var s;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const s=this.media=e.media;this.transferData=this.overrides=void 0;const i=ur(this.appendSource);if(i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const n=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(n),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&n instanceof e,wo(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,t),s.load()}catch(r){s.src=t}else s.src=t}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,s;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const s=this.tracks,i=e.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${pt(s,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${pt(i,(t,e)=>"initSegment"===t?void 0:e)}}`),!fr(i,s)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching($.MEDIA_DETACHING,{}),this.onMediaAttaching($.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach(t=>{const e=t,s=i[e];if(s){const t=s.buffer;if(t){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=Ot.getBuffered(t);i.detectEvictedFragments(e,s,r,null,!0)}const n=Po(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const s=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let s=e.length;s--;)t&&e[s].abort(),r.removeSourceBuffer(e[s]);t&&r.endOfStream()}catch(nr){this.warn(`onMediaDetaching: ${nr.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&&wo(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger($.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(nr){this.warn(`onBufferReset ${t}`,nr)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Po(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Qe(this.tracks)}onBufferCodecs(t,e){var s;const i=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!i[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var s,r;const{id:n,codec:a,levelCodec:o,container:l,metadata:d,supplemental:h}=e[t];let c=i[t];const u=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[t],f=null!=u&&u.buffer?u:c,g=(null==f?void 0:f.pendingCodec)||(null==f?void 0:f.codec),m=null==f?void 0:f.levelCodec;c||(c=i[t]={buffer:void 0,listeners:[],codec:a,supplemental:h,container:l,levelCodec:o,metadata:d,id:n});const p=Qr(g,m),v=null==p?void 0:p.replace(Ze,"$1");let y=Qr(a,o);const E=null==(r=y)?void 0:r.replace(Ze,"$1");y&&p&&v!==E&&("audio"===t.slice(0,5)&&(y=Xr(y,this.appendSource)),this.log(`switching codec ${g} to ${y}`),y!==(c.pendingCodec||c.codec)&&(c.pendingCodec=y),c.container=l,this.appendChangeType(t,l,y))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(s=e.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const s=this.tracks[e];return t[e]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t},{})}appendChangeType(t,e,s){const i=`${e};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const s=t.start,i=s+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,U.MAIN))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>i||null!=e&&e.buffer&&Ot.isBuffered(e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,U.MAIN))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=e,h=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();h.start=f;const g=a.stats.buffering,m=o?o.stats.buffering:null;0===g.start&&(g.start=f),m&&0===m.start&&(m.start=f);const p=s.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==p?void 0:p.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=s.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==c){const t=o||a,e=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const s=t.end;if(e){const t=e.frag.start;(s>t||s<this.lastVideoAppendEnd||Ot.isBuffered(E,t))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const e=t.start+.05*t.duration,s=E.buffered,i=this.currentOp("video");s.length||i?!i&&!Ot.isBuffered(E,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const T=(o||a).start,S={label:`append-${r}`,execute:()=>{var t;h.executeStart=self.performance.now();const e=null==(t=this.tracks[r])?void 0:t.buffer;e&&(v?this.updateTimestampOffset(e,T,.1,r,c,u):void 0!==d&&C(d)&&this.updateTimestampOffset(e,d,1e-6,r,c,u)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();h.executeEnd=h.end=t,0===g.first&&(g.first=t),m&&0===m.first&&(m.first=t);const e={};this.sourceBuffers.forEach(([t,s])=>{t&&(e[t]=Ot.getBuffered(s))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger($.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:e})},onError:t=>{var e;const s={type:O.MEDIA_ERROR,parent:a.type,details:F.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},i=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)s.details=F.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)s.errorAction=_n(!0);else if(t.name===Je&&0===this.sourceBufferCount)s.errorAction=_n(!0);else{const t=++this.appendErrors[r];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${i||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||i)&&(s.fatal=!0)}this.hls.trigger($.ERROR,s)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===U.MAIN?"level":"track"} ${a.level} cc: ${u}`),this.append(S,r,this.isPending(this.tracks[r]))}getFlushOp(t,e,s){return this.log(`queuing "${t}" remove ${e}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger($.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove ${e}-${s} from "${t}" SourceBuffer`,i)}}}onBufferFlushing(t,e){const{type:s,startOffset:i,endOffset:r}=e;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,i,r),t)})}onFragParsed(t,e){const{frag:s,part:i}=e,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[Q.AUDIOVIDEO]?r.push("audiovideo"):(n[Q.AUDIO]&&r.push("audio"),n[Q.VIDEO]&&r.push("video")),0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.hls.trigger($.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type})},r).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var s;this.sourceBuffers.forEach(([t])=>{if(t){const s=this.tracks[t];e.type&&e.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger($.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger($.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===F.BUFFER_APPEND_ERROR&&e.frag){var s;const t=null==(s=e.errorAction)?void 0:s.nextAutoLevel;C(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||null===e)return;if(!this.sourceBufferCount)return;const i=t.config,r=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(C(a)&&a>=0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}const o=i.frontBufferFlushThreshold;if(C(o)&&o>0){const t=Math.max(i.maxBufferLength,o),e=Math.max(t,n),s=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(t,e,s){this.sourceBuffers.forEach(([t,e])=>{if(e){const r=Ot.getBuffered(e);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger($.BACK_BUFFER_REACHED,{bufferEnd:s});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger($.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}})}flushFrontBuffer(t,e,s){this.sourceBuffers.forEach(([e,i])=>{if(i){const r=Ot.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||t>=a&&t<=o)return;this.hls.trigger($.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:s}=this;if(!e||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,i)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return C(r)?{duration:r}:null;const n=this.media.duration;return i>(C(s.duration)?s.duration:0)&&i>n||!C(n)?{duration:i}:null}updateMediaSource({duration:t,start:e,end:s}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==t&&(C(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),i.duration=t),void 0!==e&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${e}-${s}.`),i.setLiveSeekableRange(e,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${pt(s)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,s])=>{if(e){const i=this.tracks[e];t[e]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger($.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in t){const a=n,o=t[a];if(this.isPending(o)){const t=this.getTrackCodec(o,a),n=`${o.container};codecs=${t}`;o.codec=t,this.log(`creating sourceBuffer(${n})${this.currentOp(a)?" Queued":""} ${pt(o)}`);try{const t=s.addSourceBuffer(n);e[Po(a)]=[a,t],o.buffer=t}catch(r){var i;return this.error(`error while trying to add sourceBuffer: ${r.message}`),this.shiftAndExecuteNext(a),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[a],void this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:r,sourceBufferName:a,mimeType:n,parent:o.id})}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(t,e){const s=t.supplemental;let i=t.codec;s&&("video"===e||"audiovideo"===e)&&Wr(s,"video")&&(i=function(t,e){const s=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)Hr(e[t],"video")||s.push(e[t])}return e&&s.push(e),s.join(",")}(i,s));const r=Qr(i,t.levelCodec);return r?"audio"===e.slice(0,5)?Xr(r,this.appendSource):r:""}trackSourceBuffer(t,e){const s=e.buffer;if(!s)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:s,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger($.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const s=this.currentOp(t);s&&(s.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const r=this.currentOp(t);r&&r.onError(i)}updateTimestampOffset(t,e,s,i,r,n){const a=e-t.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,s){const{media:i,mediaSource:r}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!i||!r||!a)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=C(i.duration)?i.duration:1/0,l=C(r.duration)?r.duration:1/0,d=Math.max(0,e),h=Math.min(s,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${t} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.tracks[e],i=null==s?void 0:s.buffer;if(!i)throw new ts(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:s}=this,i=e.map(t=>this.appendBlocker(t));return e.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(e=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;s&&!s.updating&&this.shiftAndExecuteNext(t)})}append(t,e,s){this.operationQueue&&this.operationQueue.append(t,e,s)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,s){const i=this.tracks[t];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,t);i.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const s=e.buffer;s&&(e.listeners.forEach(t=>{s.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}},ss=class t{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.BUFFER_CODECS,this.onBufferCodecs,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.BUFFER_CODECS,this.onBufferCodecs,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&C(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(e){const s=this.hls.levels;if(!s.length)return-1;const i=s.filter((t,s)=>this.isLevelAllowed(t)&&s<=e);return this.clientRect=null,t.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(e){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,s){if(null==t||!t.length)return-1;const i=(t,e)=>!e||t.width!==e.width||t.height!==e.height;let r=t.length-1;const n=Math.max(e,s);for(let a=0;a<t.length;a+=1){const e=t[a];if((e.width>=n||e.height>=n)&&i(e,t[a+1])){r=a;break}}return r}},is={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},rs={HLS:"h"},ns=class t{constructor(e,s){Array.isArray(e)&&(e=e.map(e=>e instanceof t?e:new t(e))),this.value=e,this.params=s}},as="Dict",os=class{constructor(t){this.description=t}},ls="Bare Item",ds="Boolean",hs="Byte Sequence",cs="Integer",us="Decimal",fs="String",gs=/[\x00-\x1f\x7f]+/,ms="Token",ps="Key",Ss={br:vs="CMCD-Object",ab:vs,d:vs,ot:vs,tb:vs,tpb:vs,lb:vs,tab:vs,lab:vs,url:vs,pb:ys="CMCD-Request",bl:ys,tbl:ys,dl:ys,ltc:ys,mtp:ys,nor:ys,nrr:ys,rc:ys,sn:ys,sta:ys,su:ys,ttfb:ys,ttfbb:ys,ttlb:ys,cmsdd:ys,cmsds:ys,smrt:ys,df:ys,cs:ys,ts:ys,cid:Es="CMCD-Session",pr:Es,sf:Es,sid:Es,st:Es,v:Es,msd:Es,bs:Ts="CMCD-Status",bsd:Ts,cdn:Ts,rtp:Ts,bg:Ts,pt:Ts,ec:Ts,e:Ts},As={REQUEST:ys},Ls="event",bs=(t,e)=>Array.isArray(t)?t.map(t=>bs(t,e)):t instanceof ns&&"string"==typeof t.value?new ns(bs(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const s=new URL(t),i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),Rs=t=>100*Is(t/100),ks={br:Is=t=>Math.round(t),d:Is,bl:Rs,dl:Rs,mtp:Rs,nor:(t,e)=>{let s=t;return e.version>=2&&(t instanceof ns&&"string"==typeof t.value?s=new ns([t]):"string"==typeof t&&(s=[t])),bs(s,e)},rtp:Rs,tb:Is},Ds="request",ws="response",Ps=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],_s=["e"],Cs=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/,xs=["d","dl","nor","ot","rtp","su"],Ms=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Os=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Fs={[ws]:qo,[Ls]:Yo,[Ds]:jo},$s="CMCD",Ns=/CMCD=[^&#]+/,Us=class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:is.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=t=>{try{const{frag:e,part:s}=t,i=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*(s||e).duration,ot:r};r!==is.VIDEO&&r!==is.AUDIO&&r!=is.MUXED||(n.br=i.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=s?this.getNextPart(s):this.getNextFrag(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||t.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHED,this.onMediaDetached,this),t.on($.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHED,this.onMediaDetached,this),t.off($.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,i;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer}createData(){var t;return{v:1,sf:rs.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){or(e,this.createData());const s=e.ot===is.INIT||e.ot===is.VIDEO||e.ot===is.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce((t,s)=>(i.includes(s)&&(t[s]=e[s]),t),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),Qo(t.headers,e,r)):t.url=Jo(t.url,e,r)}getNextFrag(t){var e;const s=null==(e=this.hls.levels[t.level])?void 0:e.details;if(s){const e=t.sn-s.startSN;return s.fragments[e+1]}}getNextPart(t){var e;const{index:s,fragment:i}=t,r=null==(e=this.hls.levels[i.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=i;for(let e=r.length-1;e>=0;e--){const i=r[e];if(i.index===s&&i.fragment.sn===t)return r[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?is.TIMED_TEXT:"initSegment"===t.sn?is.INIT:"audio"===e?is.AUDIO:"main"===e?this.hls.audioTracks.length?is.VIDEO:is.MUXED:void 0}getTopBandwidth(t){let e,s=0;const i=this.hls;if(t===is.AUDIO)e=i.audioTracks;else{const t=i.maxAutoLevel,s=t>-1?t+1:i.levels.length;e=i.levels.slice(0,s)}return e.forEach(t=>{t.bitrate>s&&(s=t.bitrate)}),s>0?s:NaN}getBufferLength(t){const e=this.media,s=t===is.AUDIO?this.audioBuffer:this.videoBuffer;return s&&e?1e3*Ot.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}},Bs=class extends K{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Et.SendAlternateToPenaltyBox&&s.flags===Tt.MoveAllAlternatesMatchingHost){const t=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),e.details!==F.BUFFER_APPEND_ERROR||e.fatal?s.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${pt(i)} penalized: ${pt(this.penalizedPathways)}`):s.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(t=>{i-s[t]>3e5&&delete s[t]});for(let r=0;r<t.length;r++){const i=t[r];if(i in s)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(i),e.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,La(e),this.hls.trigger($.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(e===N.AUDIO_TRACK&&i[r].hasAudioGroup(t)||e===N.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(t))return i[r].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new Ut(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=el(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new gt({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let s=1;s<t.audioGroups.length;s++)d.addGroupId("audio",`${t.audioGroups[s]}_clone_${r}`);if(t.subtitleGroups)for(let s=1;s<t.subtitleGroups.length;s++)d.addGroupId("text",`${t.subtitleGroups[s]}_clone_${r}`);return d});e.push(...o),tl(this.audioTracks,s,a,r),tl(this.subtitleTracks,i,a,r)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(e);try{i=new self.URL(t)}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:i.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger($.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},Gs=class t extends K{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.debug(i),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Jn(this.config));const e=t.map(Zn).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{const n=Qn(r);if("sinf"!==e||n!==Vt.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);let a;try{const t=Sr(new Uint8Array(s)),e=Or(jn(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24))}catch(c){return void this.warn(`${i} Failed to parse sinf: ${c}`)}const o=mr(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let h=l[o];for(let t=0;t<d.length;t++){const i=d[t],r=i.decryptdata;if(!r.keyId)continue;const n=mr(r.keyId);if(Vn(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(h=l[n],!h)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(s),r.keyId=a,h=l[o]=h.then(()=>this.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match")),h.catch(t=>this.handleError(t));break}}h||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on($.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off($.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=null==e?void 0:e[t];return i?i.licenseUrl:t===Vt.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=null==e?void 0:e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map(t=>t.audioCodec).filter(s),r=e.map(t=>t.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):s(e instanceof Ks?e:new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};n(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===Wt&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){var i;const r=function(t,e,s,i){let r;switch(t){case Vt.FAIRPLAY:r=["cenc","sinf"];break;case Vt.WIDEVINE:case Vt.PLAYREADY:r=["cenc"];break;case Vt.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${pt(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,i.then(e=>e?this.setMediaKeysServerCertificate(s,t,e):s)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${mr(t.keyId||[])} keyUri: ${t.uri}`);const i={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:s.createSession(),keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=sl(e),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${mr(t.decryptdata.keyId||[])}\n } (data length: ${e.byteLength})`),s.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Zn(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return new Promise((e,s)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const i=Zn(t);i?e(i):s(new Error(`Unable to find format for key-system "${t}"`))}).catch(s)})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=Jn(this.config),s=t.map(Qn).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(s)}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let s=0;s<e.length;s++){const i=il(t,e[s]);if(i)return i}}loadKey(t){const e=t.keyInfo.decryptdata,s=sl(e),i=this.bannedKeyIds[s];if(i||"internal-error"===this.getKeyStatus(e)){const s=rl(i||"internal-error",e);return this.handleError(s,t.frag),Promise.reject(s)}const r=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const i=this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:e}))))).then(t=>{const s=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",s,"playlist-key")});return i.catch(e=>this.handleError(e,t.frag)),this.keyIdToKeySessionPromise[s]=i,i}return n.catch(s=>{if(s instanceof Ks){const i=dr({},s.data);"internal-error"===this.getKeyStatus(e)&&(i.decryptdata=e);const r=new Ks(i,s.message);this.handleError(r,t.frag)}}),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof Ks){e&&(t.data.frag=e);const s=t.data.decryptdata;this.error(`${t.message}${s?` (${mr(s.keyId||[])})`:""}`),this.hls.trigger($.ERROR,t.data)}else this.error(t.message),this.hls.trigger($.ERROR,{type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=sl(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=Qn(t.keyFormat),s=e?[e]:Jn(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=Jn(this.config)),0===t.length)throw new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${pt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(s)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===s.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,s,i){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[t.keySystem])?void 0:r.generateRequest;if(n)try{const i=n.call(this.hls,e,s,t);if(!i)throw new Error("Invalid response from configured generateRequest filter");e=i.initDataType,s=i.initData?i.initData:null,t.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const a=sl(t.decryptdata),o=t.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${a} URI: ${o} (init data type: ${e} length: ${s.byteLength})`);const l=new ae,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void l.emit("error",new Error("invalid state"));const{messageType:i,message:r}=e;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(t,r).catch(t=>{l.eventNames().length?l.emit("error",t):this.handleError(t)}):"license-release"===i?t.keySystem===Vt.FAIRPLAY&&this.updateKeySession(t,qn("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${i}"`)},h=(t,e)=>{let s;e.keyStatus=t,t.startsWith("usable")?l.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?s=rl(t,e.decryptdata):"expired"===t?s=new Error(`key expired (keyId: ${a})`):"released"===t?s=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${a})`),s&&(l.eventNames().length?l.emit("error",s):this.handleError(s))},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const s=this.getKeyStatuses(t);if(!Object.keys(s).some(t=>"status-pending"!==s[t]))return;if("expired"===s[a])return this.log(`Expired key ${pt(s)} in key-session "${t.mediaKeysSession.sessionId}"`),void this.renewKeySession(t);let i=s[a];if(i)h(i,t);else{var r;const e=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(r=t.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const s=this.getKeyStatus(t.decryptdata);if(s&&"status-pending"!==s)return this.log(`No status for keyId ${a} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${s} from other session.`),h(s,t);this.log(`key status for ${a} in key-session "${t.mediaKeysSession.sessionId}" timed out after ${e}ms`),i="internal-error",h(i,t)},e)),this.log(`No status for keyId ${a} (${pt(s)}).`)}};_a(t.mediaKeysSession,"message",d),_a(t.mediaKeysSession,"keystatuseschange",c);const u=new Promise((t,e)=>{l.on("error",e),l.on("resolved",t)});return t.mediaKeysSession.generateRequest(e,s).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(e=>{throw new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>u).catch(e=>(l.removeAllListeners(),this.removeSession(t).then(()=>{throw e}))).then(()=>(l.removeAllListeners(),t))}getKeyStatuses(t){const e={};return t.mediaKeysSession.keyStatuses.forEach((s,i)=>{if("string"==typeof i&&"object"==typeof s){const t=i;i=s,s=t}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(t.keySystem===Vt.PLAYREADY&&16===r.length){const t=mr(r);e[t]=s,zn(r)}const n=mr(r);"internal-error"===s&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${t.mediaKeysSession.sessionId}"`),e[n]=s}),e}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};s.load(a,l,{onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:dr({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise((i,r)=>{t.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${e}"`),i(t)}).catch(t=>{r(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(e=>{throw new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s<i;s++){var n,a;e=r[s];const i=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;i&&o&&t.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return qn(atob(l))}setupLicenseXHR(t,e,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,s,i)}).then(s=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:s||i})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(o){this.error(o)}i(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(i,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then(({xhr:e,licenseChallenge:s})=>{t.keySystem==Vt.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,_a(s,"encrypted",this.onMediaEncrypted),_a(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const t=this.media;t&&(Ca(t,"encrypted",this.onMediaEncrypted),Ca(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const s=this.mediaResolved;if(s&&s(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,jt.clearKeyUriToKeyIdMap();const n=r.length;t.CDMCleanupPromise=Promise.all(r.map(t=>this.removeSession(t)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s,decryptdata:i}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}" keyId: ${mr((null==i?void 0:i.keyId)||[])}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=t;n&&Object.keys(n).forEach(t=>self.clearTimeout(n[t]));const{drmSystemOptions:a}=this.config;return(function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(a)?new Promise((t,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(s)}):Promise.resolve()).catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}},Gs.CDMCleanupPromise=void 0,Ks=class extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}},Vs=class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off($.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger($.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger($.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},Hs=class extends ze{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=dl(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVEL_LOADING,this.onLevelLoading,this),t.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off($.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const s=this.media;if(!s)return;const i=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i||dl(s.textTracks).forEach(t=>{ol(t)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=gn(e,t);if(s>-1)r=t[s];else{const t=gn(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger($.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const r=e[i];if((!s||r.default)&&(s||t)&&(!t||mn(r,t)))return i}if(t){for(let s=0;s<e.length;s++){const i=e[s];if(ko(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(ko(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++)if(Do(e[s],t))return s}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==N.SUBTITLE_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&mn(t,s))return s;const i=gn(t,this.tracksInGroup);if(i>-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i),t}if(s)return null;{const s=gn(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger($.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=dl(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter(t=>Do(s,t))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==i&&(t.mode="disabled")}),i){const t=this.subtitleDisplay?"showing":"hidden";i.mode!==t&&(i.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!C(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=i;this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const h=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(h)}},Ws=.025,Ys=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({}),js=class{constructor(t,e){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=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const s=this.playoutLimit;return!(t<=0||isNaN(s))&&(0===s||((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>s)}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return ul(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-ul(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=C(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return ul(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Ws))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ys.Range:Ys.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}},qs=class{constructor(t,e,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&&this.hls.trigger($.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once($.LEVEL_LOADED,n),r.once($.AUDIO_TRACK_LOADED,n),r.once($.SUBTITLE_TRACK_LOADED,n),r.on($.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e,this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on($.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger($.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let s=this.assetItem.uri;try{s=fl(s,t.config.primarySessionId||"").href}catch(e){}t.loadSource(s)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=Ot.bufferInfo(t,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=Ot.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const s=e-this.startOffset;if(s>0&&s<t)return s}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const s=t-e;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,t-e),s)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,s){var i;null==(i=this.hls)||i.on(t,e)}once(t,e,s){var i;null==(i=this.hls)||i.once(t,e)}off(t,e,s){var i;null==(i=this.hls)||i.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${ml(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}},zs=class extends K{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((s,i)=>t<=i.startOffset&&e>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===e&&(e=t.start),s=this.findItemIndexAtTime(e));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(t,e){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(e&&"primary"!==e&&(r=r[e]),t===r.start||t>r.start&&t<r.end)return i}return-1}findJumpRestrictedIndex(t,e){const s=this.items;if(s)for(let i=t;i<=e&&s[i];i++){const t=s[i].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return i}return-1}findEventIndex(t){const e=this.items;if(e)for(let i=e.length;i--;){var s;if((null==(s=e[i].event)?void 0:s.identifier)===t)return i}return-1}findAssetIndex(t,e){const s=t.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const t=s[r];if(!t.error){const s=t.timelineStart;if(e===s||e>s&&(e<s+(t.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,s=t[t.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(t,e){const s=t.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},e),a=Object.keys(i),o=r?r.filter(t=>!a.includes(t.identifier)):[];n.length&&n.sort((t,e)=>{const s=t.cue.pre,i=t.cue.post,r=e.cue.pre,n=e.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=t.startTime,i=e.startTime;if(s!==i)return s-i}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=n,o.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,o)}updateSchedule(t,e=[],s=!1){const i=this.events||[];if(i.length||e.length||this.length<2){const r=this.items,n=this.parseSchedule(i,t);(s||e.length||(null==r?void 0:r.length)!==n.length||n.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,s){const i=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new js(o,e),this.eventMap[a]=t,!1===s&&(t.appendInPlace=s)),i.push(t)}}return i}parseSchedule(t,e){const s=[],i=e.main.details,r=i.live?1/0:i.edge;let n=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let i=0,o=0;if(t.forEach((e,a)=>{const l=e.cue.pre,d=e.cue.post,h=t[a-1]||null,c=e.appendInPlace,u=d?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===Ys.Range?f:0,m=e.resumptionOffset,p=(null==h?void 0:h.startTime)===u,v=u+e.cumulativeDuration;let y=c?v+f:u+m;if(l||!d&&u<=0){const t=o;o+=g,e.timelineStart=v;const i=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:i,end:n},integrated:{start:t,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-i;if(r>.033){const l=i,d=o;o+=r;const h=n;n+=r;const c={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+r,playout:{start:h,end:n},integrated:{start:d,end:o}};s.push(c)}else r>0&&h&&(h.cumulativeDuration+=r,s[s.length-1].end=u)}d&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=e.resumeTime;i=d||E>r?r:E}),i<r){var a;const t=i,e=o,l=r-i;o+=l;const d=n;n+=l,s.push({previousEvent:(null==(a=s[s.length-1])?void 0:a.event)||null,nextEvent:null,start:i,end:t+l,playout:{start:d,end:n},integrated:{start:e,end:o}})}this.setDurations(r,n,o)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return s}setDurations(t,e,s){this.durations={primary:t,playout:e,integrated:s}}resolveOffsets(t,e){const s=e.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;t.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,h=l?0:d?i:a.startTime;this.updateAssetDurations(a),n===h?a.cumulativeDuration=r:(r=0,n=h),!d&&a.snapOptions.in&&(a.resumeAnchor=En(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)),!a.appendInPlace&&o+1<t.length&&t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const c=C(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(t,e){const s=t.resumeTime,i=t.startTime+t.resumptionOffset;return Math.abs(s-i)>Ws?(this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(e).some(i=>{const r=e[i].details,n=r.edge;if(s>=n)return this.log(`"${t.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=En(null,r.fragments,s);if(!a)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<Ws+o||Math.abs(a.end-s)<Ws+o||(this.log(`"${t.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),0))})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error),s+=a.error?0:a.duration||0}t.duration=i&&!r?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}},Xs=class{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const s=t.assetListUrl;let i;try{i=fl(s,this.hls.sessionId,t.baseUrl)}catch(d){const e=this.assignAssetListError(t,F.ASSET_LIST_LOAD_ERROR,d,s);return void this.hls.trigger($.ERROR,e)}e&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return n.load(a,l,{onSuccess:(e,s,i,r)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const e=this.assignAssetListError(t,F.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger($.ERROR,e)}t.assetListResponse=n,this.hls.trigger($.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:r})},onError:(e,s,i,r)=>{const n=this.assignAssetListError(t,F.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${s.url})`),s.url,r,i);this.hls.trigger($.ERROR,n)},onTimeout:(e,s,i)=>{const r=this.assignAssetListError(t,F.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,e,i);this.hls.trigger($.ERROR,r)}}),this.hls.trigger($.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,s,i,r,n){return t.error=s,{type:O.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:i,error:s,networkDetails:n,stats:r}}},Qs=class extends K{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const s=e<=-.01;this.timelinePos=t,this.bufferedPos=t;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0),this.checkBuffer(),s&&t<i.start||t>=i.end){var r;const e=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const e=i.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&t<a||t>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const s=this.playingAsset;s&&t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,e)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=t.map(t=>t.identifier),l=!(!r.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>pl(t))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,h=null;i&&(d=this.updateItem(i,this.timelinePos),this.itemsMatch(i,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const c=this.bufferingItem;if(c&&(h=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,h)?this.bufferingItem=h:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const s=t.assetItem.timelineStart,i=t.timelineOffset-s;if(i)try{t.timelineOffset=s}catch(e){Math.abs(i)>Ws&&this.warn(`${e} ("${t.assetId}" ${t.timelineOffset}->${s})`)}}}),l||e){if(this.hls.trigger($.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.includes(i.event.identifier))return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(d,i),c&&h!==d&&this.trimInPlace(h,c),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Xs(t),this.schedule=new zs(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on($.BUFFER_APPENDED,this.onBufferAppended,this),t.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on($.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on($.MEDIA_ENDED,this.onMediaEnded,this),t.on($.ERROR,this.onError,this),t.on($.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off($.BUFFER_CODECS,this.onBufferCodecs,this),t.off($.BUFFER_APPENDED,this.onBufferAppended,this),t.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off($.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off($.MEDIA_ENDED,this.onMediaEnded,this),t.off($.ERROR,this.onError,this),t.off($.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Ca(t,"play",this.onPlay),Ca(t,"pause",this.onPause),Ca(t,"seeking",this.onSeeking),Ca(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const s=this.media=e.media;_a(s,"seeking",this.onSeeking),_a(s,"timeupdate",this.onTimeupdate),_a(s,"play",this.onPlay),_a(s,"pause",this.onPause)}onMediaAttached(t,e){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,s=e=>e?t.getAssetPlayer(e.identifier):e,i=(e,i,n,a,o)=>{if(e){let l=e[i].start;const d=e.event;if(d){if("playout"===i||d.timelineOccupancy!==Ys.Point){const t=s(n);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else l+=("bufferedPos"===a?r():t[a])-e.start;return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var s,i;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:(null==(i=t.schedule)?void 0:i.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,r),h=null==(a=t.schedule.items)?void 0:a[d],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,h);if(l&&(f||g)){const n=s(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-s,d=(f?s:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(h){let s=e;if("primary"!==r){const t=e-h[r].start;s=h.start+t}const i=!t.isInterstitial(h);if(t.isInterstitial(l)&&!l.event.appendInPlace||!i&&!h.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(d>n){const e=t.schedule.findJumpRestrictedIndex(n+1,d);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(i)t.timelinePos=s,t.checkBuffer();else{const t=h.event.assetList,s=e-(h[r]||h).start;for(let e=t.length;e--;){const i=t[e];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=e;break}}}t.setSchedulePosition(d,a)}}else{const e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=s)}}},o=()=>{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const i=e();return t.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=e(),r=t.bufferingItem;var n;return r&&r===s&&(i(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),s=t.effectivePlayingItem;return s&&s===e?i(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(e){const s=o(),i=t.effectivePlayingItem;i&&i===s&&a(e+i.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const s=null==(e=o())?void 0:e.event.assetList;return s?s.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const s=null==(e=o())?void 0:e.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const s=e();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){var e;return((e,s)=>{var i;if(0!==e&&"primary"!==s&&null!=(i=t.schedule)&&i.length){var r;const i=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[i];if(n)return e+(n[s].start-n.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,s=null==e?void 0:e.event;if(s&&!s.restrictions.skip){const i=t.findItemIndex(e);s.appendInPlace?a(e.playout.start+e.event.duration+.001,"playout"):t.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&s)&&this.findItemIndex(e)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(i=this.primaryMedia);const r=null==(e=i)?void 0:e.currentTime;return void 0!==r&&C(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,e)}transferMediaFromPlayer(t,e){const s=t.interstitial.appendInPlace,i=t.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&i)return void(this.detachedData={media:i});const s=t.transferMedia();this.log(`transfer MediaSource from ${t} ${pt(s)}`),this.detachedData=s}else e&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(t,e){var s,i;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const t=this.getBufferingPlayer();t?(r=t.transferMedia(),d=`${t}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${pt(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const h=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState),c=h&&r?r:e;this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`);const u=this.schedule;if(c===r&&u){const e=a&&t.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(-1===s){const s=this.hls.startPosition;if(this.log(yl("checkStart",s)),this.timelinePos=s,e.length&&e[0].cue.pre){const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const e=this.timelinePos=s>0?s:0,i=t.findItemIndexAtTime(e);this.setSchedulePosition(i)}}else if(i&&!this.playingItem){const e=t.findItemIndex(i);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const s=t.event,i=gl(s,s.findAssetIndex(e));if(s.isAssetPastPlayoutLimit(i)){if(this.schedule){var r;const e=null==(r=this.schedule.items)?void 0:r[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,i)}advanceAfterAssetEnded(t,e,s){const i=gl(t,s);if(t.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=e+1;if(i>=s.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(yl("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(i)}}}else{if(t.appendInPlace){const e=t.assetList[i];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,i)}}setScheduleToAssetAtTime(t,e){const s=this.schedule;if(!s)return;const i=e.parentIdentifier,r=s.getEvent(i);if(r){const e=s.findEventIndex(i),n=s.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=t>=0?i[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?pl(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,d=this.playingAsset,h=null==d?void 0:d.identifier,c=h?this.getAssetPlayer(h):null;if(c&&h&&(!this.eventItemsMatch(n,r)||void 0!==e&&h!==s.assetList[e].identifier)){var o;const e=s.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${s.assetList.length} ${ml(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger($.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:e,event:s,schedule:i.slice(0),scheduleIndex:t,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(h,r),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${pl(n)}`),s.hasPlayed=!0,this.hls.trigger($.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:t}),s.cue.once)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(r&&t){const s=this.findItemIndex(r);this.advanceSchedule(s,t,e,n,a)}return}}this.advanceSchedule(t,i,e,n,a)}advanceSchedule(t,e,s,i,r){const n=this.schedule;if(!n)return;const a=e[t]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(e=>{const s=e.interstitial,i=n.findEventIndex(s.identifier);(i<t||i>t+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const e=gl(r,(s=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,t,s);s=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${pl(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger($.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const h=r.assetList[s];if(!h)return void this.advanceAfterAssetEnded(r,t,s||0);if(d||(d=this.getAssetPlayer(h.identifier)),null===d||d.destroyed){const t=r.assetList.length;this.warn(`asset ${s+1}/${t} player destroyed ${r}`),d=this.createAssetPlayer(r,h,s),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(d,s,e,t,o),this.shouldPlay&&vl(d.media)}else a?(this.resumePrimary(a,t,i),this.shouldPlay&&vl(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,s){var i,r;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${pl(t)}`),null==(i=this.detachedData)||!i.mediaSource){let s=this.timelinePos;(s<t.start||s>=t.end)&&(s=this.getPrimaryResumption(t,e),this.log(yl("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,t)}if(!s)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${pl(t)}`),this.hls.trigger($.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const s=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(s<t.fragmentStart||s>t.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);return null!=e&&e.hls?e.hls.bufferedToEnd:Ot.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,s){e?this.setBufferingItem(e):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(t,s)),s||(this.log(yl("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,e){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(s=i.mainForwardBufferInfo)?void 0:s.start)||i.media.currentTime)-t)>.5?i.startLoad(t,e):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.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($.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on($.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const s=this.hls.levels[e.level];if(!s.details)return;const i=dr(dr({},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(t,e){const s=this.hls.audioTracks[e.id],i=this.mediaSelection;i?this.mediaSelection=dr(dr({},i),{},{audio:s}):this.altSelection=dr(dr({},this.altSelection),{},{audio:s})}onSubtitleTrackUpdated(t,e){const s=this.hls.subtitleTracks[e.id],i=this.mediaSelection;i?this.mediaSelection=dr(dr({},i),{},{subtitles:s}):this.altSelection=dr(dr({},this.altSelection),{},{subtitles:s})}onAudioTrackSwitching(t,e){const s=fn(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(s)))}onSubtitleTrackSwitch(t,e){const s=fn(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(s)))}onBufferCodecs(t,e){const s=e.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const s=this.playingItem;!s||this.itemsMatch(s,this.bufferingItem)||this.isInterstitial(s)||(this.bufferedPos=this.timelinePos,this.checkBuffer())}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const i=e[t];if(i.cue.post){var s;const t=this.schedule.findEventIndex(i.identifier),e=null==(s=this.schedule.items)?void 0:s[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;return t&&i&&i[this.findItemIndex(t,e)]||null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,s)=>{t.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(e.identifier,null)});const s=t.end+.25,i=Ot.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${pl(t)} (was ${pl(e)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var s;return!!e&&(t===e||t.event.identifier===(null==(s=e.event)?void 0:s.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const s=this.mediaSelection;s&&(null==(e=this.schedule)||e.updateSchedule(s,[],t))}checkBuffer(t){var e;const s=null==(e=this.schedule)?void 0:e.items;if(!s)return;const i=Ot.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=i.len<1),this.updateBufferedPos(i.end,s,t)}updateBufferedPos(t,e,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!i)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const s=this.findItemIndex(r),i=Math.min(s+1,e.length-1),n=e[i];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=i),this.isInterstitial(r)){const t=r.event;if(i-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>s&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(t,e)&&s){const{items:i,events:r}=s;if(!i||!r)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${pl(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=s.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,s)=>{const i=this.getAssetPlayer(t.identifier);i&&(s===e&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger($.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==s){this.bufferingAsset=null;const e=this.detachedData;e&&e.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),s=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(s)}bufferedToEvent(t,e){const s=t.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const t=this.preloadAssets(s,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const s=t.assetUrl,i=t.assetList.length,r=0===i&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${s?1:i} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&i){for(let r=e;r<i;r++){const e=t.assetList[r],s=this.getAssetPlayerQueueIndex(e.identifier);-1!==s&&!this.playerQueue[s].destroyed||e.error||this.createAssetPlayer(t,e,r)}const s=t.assetList[e];if(s){const t=this.getAssetPlayer(s.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;e&&(this.log(`Removing front buffer starting at ${t}`),Object.keys(e).forEach(e=>{this.hls.trigger($.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})}))}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let s=0;s<e.length;s++)if(t===e[s].assetId)return s;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let s=0;s<t.length;s++)if(t[s].media===e)return t[s];return null}createAsset(t,e,s,i,r,n){const a={parentIdentifier:t.identifier,identifier:cl(t,n,e),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const a=i.loadLevelObj||i.levels[i.currentLevel];(n||a)&&(n=or({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let d=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const s=e.duration;s&&t<s&&(d=t)}}const h=e.identifier,c=dr(dr({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(c.timelineOffset=e.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=or({},u,{contentId:hl(e.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${t} and asset ${h}`);const f=new qs(this.HlsPlayerClass,c,t,e);this.playerQueue.push(f),t.assetList[s]=e;let g=!0;const m=i=>{if(i.live){var r;const e=new Error(`Interstitials MUST be VOD assets ${t}`),i={fatal:!0,type:O.OTHER_ERROR,details:F.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=(null==(r=this.schedule)?void 0:r.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(i,t,n,s,e.message)}const n=i.edge-i.fragmentStart,a=e.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${h}" duration change ${a} > ${n}`),e.duration=n,this.updateSchedule())};f.on($.LEVEL_UPDATED,(t,{details:e})=>m(e)),f.on($.LEVEL_PTS_UPDATED,(t,{details:e})=>m(e)),f.on($.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(t,e)=>{const s=this.getAssetPlayer(h);if(s&&e.tracks){s.off($.BUFFER_CODECS,p),s.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};f.on($.BUFFER_CODECS,p),f.on($.BUFFERED_TO_END,()=>{var s;const i=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${i}`),!i||!this.schedule)return;const r=this.schedule.findEventIndex(t.identifier),n=null==(s=this.schedule.items)?void 0:s[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,e)});const v=e=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,e)};return f.once($.MEDIA_ENDED,v(s)),f.once($.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on($.ERROR,(e,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(h);if(i.details===F.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,`Asset player error ${i.error} ${t}`)}),f.on($.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${h}`),i={fatal:!0,type:O.OTHER_ERROR,details:F.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ml(e)}`),this.hls.trigger($.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:s,event:t,player:f}),f}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const s=this.playerQueue[e];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(t,e){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){const t=this.playerQueue[s];this.log(`clear ${t} toSegment: ${e?pl(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(s,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=t,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,s[i]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${ml(a)}`),this.hls.trigger($.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:s.slice(0),scheduleIndex:i,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=t,a=this.schedule.findEventIndex(r.identifier),o=null==(s=this.schedule.items)?void 0:s[a];if(!o)return;t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===t)return;const d=r.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const h=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(h&&!fr(h,t.tracks)){const e=new Error(`Asset ${ml(n)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),s={fatal:!0,type:O.OTHER_ERROR,details:F.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},i=r.findAssetIndex(n);return void this.handleAssetItemError(s,r,a,i,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,s=this.primaryMedia;if(!e||!s)return;const i=s.currentTime,r=e.findAssetIndex(t,i),n=t.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s))&&a.hls){const s=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,r)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,s,i,r){if(t.details===F.BUFFER_STALLED_ERROR)return;const n=e.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?ml(n):n} ${t.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,h=or({},t,{fatal:!1,errorAction:_n(!0),asset:n,assetListIndex:i,event:e,schedule:d,scheduleIndex:s,player:l});if(this.hls.trigger($.INTERSTITIAL_ASSET_ERROR,h),!t.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),e.assetList.some(t=>!t.error))for(let g=i;g<e.assetList.length;g++)this.resetAssetPlayer(e.assetList[g].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):c&&c.identifier===a?this.advanceAfterAssetEnded(e,s,i):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(t){const e=t.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${i} playing: ${pl(s)} error: ${t.error}`),-1===i&&(i=this.hls.startPosition);const r=this.updateItem(s,i);this.itemsMatch(s,r)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===i)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(t,e){var s,i;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((t,e)=>{const s=parseFloat(t.DURATION);this.createAsset(r,e,d,o+d,s,t.URI),d+=s}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const h=this.waitingItem,c=(null==h?void 0:h.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(c){var f;const t=this.schedule.findEventIndex(n),e=null==(f=this.schedule.items)?void 0:f[t];if(e){if(!this.playingItem&&this.timelinePos>e.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r);this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case F.ASSET_LIST_PARSING_ERROR:case F.ASSET_LIST_LOAD_ERROR:case F.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case F.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Zs=class extends se{constructor(t,e,s){super(t,e,s,"subtitle-stream-controller",U.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=ee.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:i}=e;if(this.fragContextChanged(s)||(yr(s)&&(this.fragPrevious=s),this.state=ee.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let l=0;l<r.length;l++)if(a>=r[l].start&&a<=r[l].end){n=r[l];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}}),this.fragmentTracker.removeFragmentsInRange(s,t,U.SUBTITLE)}}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===U.SUBTITLE&&(e.details===F.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ee.STOPPED&&(this.state=ee.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Ro(this.levels,e)?this.levels=e.map(t=>new gt(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new gt(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,U.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==ee.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var d;o.details?(l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&e&&(l=e.start,ya(n,l))):n.hasProgramDateTime&&t.hasProgramDateTime?(Pa(n,t),l=n.fragmentStart):e&&(l=e.start,ya(n,l)),t&&!this.startFragRequested&&this.setStartPosition(t,l)}o.details=n,this.levelLastLoaded=o,a===i&&(this.hls.trigger($.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===ee.IDLE&&(En(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&Wn(i.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,Yn(i.method)).catch(t=>{throw r.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(s=>{const i=performance.now();r.trigger($.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:i}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=ee.IDLE})}}doTick(){if(this.media){if(this.state===ee.IDLE){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;if(this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),{end:n,len:a}=Ot.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),o=s.details;if(a>this.hls.maxBufferLength+o.levelTargetDuration)return;const l=o.fragments,d=l.length,h=o.edge;let c=null;const u=this.fragPrevious;if(n<h){const t=i.maxFragLookUpTolerance,e=n>h-t?0:t;c=En(u,l,Math.max(l[0].start,n),e),!c&&u&&u.start<l[0].start&&(c=l[0])}else c=l[d-1];if(c=this.filterReplacedPrimary(c,s.details),!c)return;const f=l[c.sn-o.startSN-1];if(f&&f.cc===c.cc&&this.fragmentTracker.getState(f)===At.NOT_LOADED&&(c=f),this.fragmentTracker.getState(c)===At.NOT_LOADED){const t=this.mapToInitFragWhenRequired(c);t&&this.loadFragment(t,s,n)}}}else this.state=ee.IDLE}loadFragment(t,e,s){yr(t)?super.loadFragment(t,e,s):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Js(this.tracksBuffered[this.currentTrackId]||[])}},Js=class{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}},ti={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},ei=t=>String.fromCharCode(ti[t]||t),si=15,ii=100,ri={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ni={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ai={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},oi={25:2,26:4,29:6,30:8,31:10,27:13,28:15},li=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],di=class{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;Y.log(`${this.time} [${t}] ${s}`)}}},hi=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e},ci=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let s=0;s<e.length;s++){const i=e[s];t.hasOwnProperty(i)&&(this[i]=t[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},ui=class{constructor(){this.uchar=" ",this.penState=new ci}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}},fi=class{constructor(t){this.chars=[],this.pos=0,this.currPenState=new ci,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<ii;e++)this.chars.push(new ui);this.logger=t}equals(t){for(let e=0;e<ii;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<ii;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<ii;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>ii&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ii)}moveCursor(t){const e=this.pos+t;if(t>1)for(let s=this.pos+1;s<e+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=ei(t);this.pos>=ii?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<ii;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let s=0;s<ii;s++){const i=this.chars[s].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}},gi=class{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<si;e++)this.rows.push(new fi(t));this.logger=t}reset(){for(let t=0;t<si;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<si;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<si;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<si;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+pt(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let e=0;e<si;e++)this.rows[e].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[t].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let n=0;n<this.nrRollUpRows;n++)this.rows[e-this.nrRollUpRows+n+1].copy(s.rows[t+n])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,i=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+pt(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",i=-1;for(let r=0;r<si;r++){const s=this.rows[r].getTextString();s&&(i=r+1,t?e.push("Row "+i+": '"+s+"'"):e.push(s.trim()))}return e.length>0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}},mi=class{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new gi(s),this.nonDisplayedMemory=new gi(s),this.lastOutputScreen=new gi(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let s=0;s<t.length;s++)this.writeScreen.insertChar(t[s]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};e.underline=t%2==1,e.italics=t>=46,e.italics?e.foreground="white":e.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(t/2)-16],this.logger.log(2,"MIDROW: "+pt(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}},pi=class{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new di;this.channels=[null,new mi(t,e,i),new mi(t+1,s,i)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let s=0;s<e.length;s+=2){const t=127&e[s],i=127&e[s+1];let r=!1,n=null;if(0===t&&0===i)continue;this.logger.log(3,()=>"["+hi([e[s],e[s+1]])+"] -> ("+hi([t,i])+")");const a=this.cmdHistory;if(t>=16&&t<=31){if(Tl(t,i,a)){El(null,null,a),this.logger.log(3,()=>"Repeated command ("+hi([t,i])+") is dropped");continue}El(t,i,this.cmdHistory),r=this.parseCmd(t,i),r||(r=this.parseMidrow(t,i)),r||(r=this.parsePAC(t,i)),r||(r=this.parseBackgroundAttributes(t,i))}else El(null,null,a);if(!r&&(n=this.parseChars(t,i),n)){const t=this.currentChannel;t&&t>0?this.channels[t].insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+hi([t,i])+" orig: "+hi([e[s],e[s+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=s,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+hi([t,e])+")"),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127||(16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?ri[t]:ai[t]:1===i?ni[t]:oi[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+ei(t)+"' in channel "+s),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,()=>"Char codes = "+hi(i).join(",")),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;let s;const i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=li[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}El(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}},vi=function(){if(null!=Kt&&Kt.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function i(t){return s(e,t)}function r(t,...e){let s=1;for(;s<arguments.length;s++){const e=arguments[s];for(const s in e)t[s]=e[s]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=e,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const i=function(e){return s(t,e)}(e);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return A},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");A=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),yi=class{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}},Ei=class{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i<s.length;++i)if(e===s[i]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}},Ti=new vi(0,0,""),Si="middle"===Ti.align?"middle":"center",Ai=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new yi,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=Il(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const i=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),i}function i(t){Al(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=s();const i=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let n=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(n?n=!1:t=s(),e.state){case"HEADER":/:/.test(t)?i(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new vi(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{Ll(t,e.cue,e.regionList)}catch(r){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(n=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(r){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}},Li=/\r\n|\n\r|\n|\r/g,Ii=function(t,e,s=0){return t.slice(s,s+e.length)===e},bi=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(C(e)&&C(s)&&C(i)&&C(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e},Ri=function(t,e,s){let i=t[e],r=t[i.prevCC];if(!r||!r.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=i.start-r.start,i.new=!1,i=r,r=t[i.prevCC]}t.presentationOffset=s},ki="stpp.ttml.im1t",Di=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wi=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Pi={left:"start",center:"center",right:"end",start:"start",end:"end"},_i=class{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Ci=class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on($.FRAG_LOADING,this.onFragLoading,this),t.on($.FRAG_LOADED,this.onFragLoaded,this),t.on($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on($.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off($.FRAG_LOADING,this.onFragLoading,this),t.off($.FRAG_LOADED,this.onFragLoaded,this),t.off($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off($.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new _i(this,"textTrack1"),e=new _i(this,"textTrack2"),s=new _i(this,"textTrack3"),i=new _i(this,"textTrack4");this.cea608Parser1=new pi(1,t,e),this.cea608Parser2=new pi(3,s,i)}addCues(t,e,s,i,r){let n=!1;for(let a=r.length;a--;){const t=r[a],i=Fl(t[0],t[1],e,s);if(i>=0&&(t[0]=Math.min(t[0],e),t[1]=Math.max(t[1],s),n=!0,i/(s-e)>.5))return}if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,s,i)}else{const r=this.Cues.newCue(null,e,s,i);this.hls.trigger($.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;s===U.MAIN&&(this.initPTS[e.cc]={baseTime:i,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded($.FRAG_LOADED,t):this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Ol(r,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=e[t],a=this.getExistingTrack(r,n);if(a)s[t]=a,ol(s[t]),nl(s[t],i);else{const e=this.createTextTrack("captions",r,n);e&&(e[t]=!0,s[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger($.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,s){const i=this.media;if(i)return i.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const s=!!e.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(t=>{ol(i[t]),delete i[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let s=0;s<e.length;s++)ol(e[s])}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],i=s.some(t=>t.textCodec===ki);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Ro(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?dl(t.textTracks):null;if(this.tracks.forEach((t,s)=>{let i;if(e){let s=null;for(let i=0;i<e.length;i++)if(e[i]&&Ol(e[i],t)){s=e[i],e[i]=null;break}s&&(i=s)}if(i)ol(i);else{const e=Ml(t);i=this.createTextTrack(e,t.name,t.lang),i&&(i.mode="disabled")}i&&this.textTracks.push(i)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger($.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s=`textTrack${e[1]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===U.MAIN){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.type===U.SUBTITLE)if(i.byteLength){const t=s.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===ki?this._parseIMSC1(s,i):this._parseVTTs(e)}}else this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;kl(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{s.logger.log(`Failed to parse IMSC1: ${e}`),s.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(t);const o=this.hls;Rl(null!=(e=s.initSegment)&&e.data?Fr(s.initSegment.data,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,t=>{this._appendCues(t,s.level),o.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(s,i),o.logger.log(`Failed to parse VTT cue: ${e}`),r&&a>s.cc||o.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})})}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||kl(e,this.initPTS[t.cc],()=>{s.textCodec=ki,this._parseIMSC1(t,e)},()=>{s.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach(t=>al(s,t))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger($.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===U.SUBTITLE&&this.onFragLoaded($.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=e;if(s.type!==U.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let r=0;r<i.length;r++){const t=i[r].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const e=this.extractCea608Data(t);this.cea608Parser1.addData(i[r].pts,e[0]),this.cea608Parser2.addData(i[r].pts,e[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach(i=>ll(t[i],e,s))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==i){const{textTracks:t}=this;Object.keys(t).forEach(s=>ll(t[s],e,i))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r<s;r++){const s=t[i++],r=127&t[i++],n=127&t[i++];if((0!==r||0!==n)&&4&s){const t=3&s;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},xi=/\s/,Mi={newCue(t,e,s,i){const r=[];let n,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,d="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)xi.test(n.chars[t].uchar)&&o?l++:(d+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const i=Il(d.trim()),f=bl(e,s,i);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new h(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>al(t,e))),r}},Oi=/(\d+)-(\d+)\/(\d+)/,Fi=class{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Nl,this.controller=new self.AbortController,this.stats=new X}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(or({},t.headers))};return t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),s}(t,this.controller.signal),n="arraybuffer"===t.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&C(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))},e.timeout),(bo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(s=>{var r;this.response=this.loader=s;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))},l-(a-i.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new $i(e||"fetch, bad network response",t,s)}i.loading.first=a,i.total=$l(s.headers)||i.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&C(e.highWaterMark)?this.loadProgressively(s,i,t,e.highWaterMark,o):n?s.arrayBuffer():"json"===t.responseType?s.json():s.text()}).then(s=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=s[a];l&&(i.loaded=i.total=l);const d={url:o.url,data:s,code:o.status},h=null==(r=this.callbacks)?void 0:r.onProgress;h&&!C(e.highWaterMark)&&h(i,t,s,o),null==(n=this.callbacks)||n.onSuccess(d,i,t,o)}).catch(e=>{var s;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=e&&e.code||0,n=e?e.message:null;null==(s=this.callbacks)||s.onError({code:r,text:n},t,e?e.details:null,i)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,i=0,r){const n=new ie,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,s,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(e,s,n.flush().buffer,t)):r(e,s,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}},$i=class extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}},Ni=/^age:\s*[\d.]+\s*$/im,Ui=class{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new X,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r(s,e.url)}).catch(t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r(s,e.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:t.message},e,s,i)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const a in i)t.setRequestHeader(a,i[a]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&C(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const r=null!=l?l:e.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first),s.loaded=s.total="arraybuffer"===e.responseType?r.byteLength:r.length,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const o=null==(n=this.callbacks)?void 0:n.onProgress;o&&o(s,t,r,e);const l={url:e.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(l,s,t,e))}}const d=r.loadPolicy.errorRetry;var o;wn(d,s.retry,!1,{url:t.url,data:void 0,code:i})?this.retry(d):(Y.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,s))}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(wn(t,this.stats.retry,!0))this.retry(t);else{var e;Y.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=kn(t,s.retry),s.retry++,Y.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Ni.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}},Bi=dr(dr({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Ui,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:vt,bufferController:es,capLevelController:ss,errorController:St,fpsController:Vs,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:Wt,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Mi,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:Zs,subtitleTrackController:Hs,timelineController:Ci,audioStreamController:qe,audioTrackController:Xe,emeController:Gs,cmcdController:Us,contentSteeringController:Bs,interstitialsController:Qs}),Gi=class extends Ct{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const s=this.media=e.media;_a(s,"playing",this.onMediaPlaying),_a(s,"waiting",this.onMediaWaiting),_a(s,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:s}=this;s&&(Ca(s,"playing",this.onMediaPlaying),Ca(s,"waiting",this.onMediaWaiting),Ca(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(d)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1})));if(!Ot.getBuffered(n).length)return void(this.nudgeRetry=0);const h=Ot.bufferInfo(n,t,0),c=h.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const e=Gl(this.hls.inFlightFragments,t),s=h.len>2,i=!c||e||c-t>2&&!u.getPartialFragment(t);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(h.len>0||c))return;const e=Math.max(c,h.start||0)-t,s=null!=f&&f.live?2*f.targetduration:2,i=Vl(t,u);if(e>0&&(e<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let v=this.stalled;if(null===v){if(!(p>0&&m-p<g))return void(this.stalled=m);v=this.stalled=p}const y=m-v;if(!a&&(y>=g||p)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger($.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const T=Ot.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(T,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger($.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&t>i.end(0)){const s=Ot.bufferedInfo(Ot.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&e>=s.start){const s=Ot.timeRangesToArray(i),r=Ot.bufferedInfo(s,e,0).bufferedIndex;if(r>-1&&r<s.length-1){const e=Ot.bufferedInfo(s,t,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===e||e>r)&&n-i<1&&t-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=Vl(t,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=Ot.bufferInfo(this.media,t,0);this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=Vl(s,n);if((d||null!=l&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const h=t.buffered,c=this.adjacentTraversal(t,s);(h&&h.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-s<o.maxBufferHole||c))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const s=this.fragmentTracker,i=t.nextStart;if(s&&i){const t=s.getFragAtPos(e,U.MAIN),r=s.getFragAtPos(i,U.MAIN);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${pt(t)})`);this.warn(i.message),e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:s,media:i}=this,r=null==(e=this.hls)?void 0:e.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=Ot.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const e=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&i.readyState<3,h=o-n;if(h>0&&(e||d)){if(h>r.maxBufferHole){let e=!1;if(0===n){const t=s.getAppendedFrag(0,U.MAIN);t&&o<t.end&&(e=!0)}if(!e&&t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Gl(this.hls.inFlightFragments,o))return 0;let e=!1,i=t.end;for(;i<o;){const t=Vl(i,s);if(!t){e=!0;break}i+=t.duration}if(e)return 0}}const e=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${e}`),this.moved=!0,i.currentTime=e,null==t||!t.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`),i={type:O.MEDIA_ERROR,details:F.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?i.part=t:i.frag=t),this.hls.trigger($.ERROR,i)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:s,nudgeRetry:i}=this,r=null==e?void 0:e.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:t.len,bufferInfo:t})}}},Ki=(()=>{const t=Hl();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Vi=class{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger($.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var s;this.media=e.media,!1===(null==(s=e.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null,e.transferMedia||(this.id3Track&&(this.removeCues&&ol(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const s=t[e];if("metadata"===s.kind&&"id3"===s.label)return nl(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Hl();if(n)for(let a=0;a<r.length;a++){const t=r[a].type;if(t===ce.emsg&&!s||!i)continue;const e=Qa(r[a].data),o=r[a].pts;let l=o+r[a].duration;l>Ki&&(l=Ki),l-o<=0&&(l=o+.25);for(let s=0;s<e.length;s++){const i=e[s];if(!Za(i)){this.updateId3CueEnds(o,t);const e=Wl(n,o,l,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(t,e){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let r=i.length;r--;){const s=i[r];s.type===e&&s.startTime<t&&s.endTime===Ki&&(s.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===i?t=>t.type===ce.audioId3&&o:"video"===i?t=>t.type===ce.emsg&&a:t=>t.type===ce.audioId3&&o||t.type===ce.emsg&&a,ll(r,e,s,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Hl();if(s&&i&&!n){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):a&&(r=this.assetCue=Wl(a,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,d=Object.keys(l);let h=this.dateRangeCuesAppended;var c;if(o&&e)if(null!=(c=o.cues)&&c.length){const t=Object.keys(h).filter(t=>!d.includes(t));for(let e=t.length;e--;){var u;const s=t[e],i=null==(u=h[s])?void 0:u.cues;delete h[s],i&&Object.keys(i).forEach(t=>{const e=i[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(e)}catch(s){}}})}}else h=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==d.length&&C(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],s=l[e],i=s.startTime,r=h[e],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=Ki;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,c=!0;else if(s.endOnNext&&!c){const t=d.reduce((t,e)=>{if(e!==s.id){const i=l[e];if(i.class===s.class&&i.startDate>s.startDate&&(!t||s.startDate<t.startDate))return i}return t},null);t&&(u=t.startTime,c=!0)}const m=Object.keys(s.attr);for(let t=0;t<m.length;t++){const l=m[t];if(!Gn(l))continue;const d=o[l];if(d)!c||null!=r&&r.durationKnown?Math.abs(d.startTime-i)>.01&&(d.startTime=i,d.endTime=u):d.endTime=u;else if(a){let t=s.attr[l];Kn(l)&&(t=pr(t));const r=Wl(a,i,u,{key:l,data:t},ce.dateRange);r&&(r.id=e,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}h[e]={cues:o,dateRange:s,durationKnown:c}}}}},Hi=class{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(e,Math.max(1,s));this.changeMediaPlaybackRate(t,i)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:s,targetduration:i}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const d=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var s;e.details===F.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var s,i;t.playbackRate!==e&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}},Wi=class extends ze{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this),t.on($.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this),t.off($.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:d,videoCodec:h}=t;d&&(t.audioCodec=d=Xr(d,s)||void 0),h&&(h=t.videoCodec=function(t){const e=t.split(",");for(let s=0;s<e.length;s++){const t=e[s].split(".");t.length>2&&"avc1"===t[0]&&(e[s]=`avc1.${parseInt(t[1]).toString(16)}${("000"+parseInt(t[2]).toString(16)).slice(-4)}`)}return e.join(",")}(h));const{width:c,height:u,unknownCodecs:f}=t,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!h),l||(l=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=e,S=`${y||"."}-${t.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(r[S])if(r[S].uri===t.url||t.attrs["PATHWAY-ID"])r[S].addGroupId("audio",e.AUDIO),r[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=this.createLevel(t);r[S]=s,i.push(s)}else{const e=this.createLevel(t);r[S]=e,n[S]=1,i.push(e)}}),this.filterAndSortMediaOptions(i,e,a,o,l)}createLevel(t){const e=new gt(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),e.supportedResult=sn(t,[])}return e}isAudioSupported(t){return Wr(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Wr(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,s,i,r){var n;let a=[],o=[],l=t;const d=(null==(n=e.stats)?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&!!(r=e)&&ct.indexOf(r)>-1;var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;e.levels.length&&(s=`one or more CODECS in variant not supported: ${pt(e.levels.map(t=>t.attrs.CODECS).filter((t,e,s)=>s.indexOf(t)===e))}`,this.warn(s),t+=` (${s})`);const i=new Error(t);this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:s})}}),void(d.end=performance.now());e.audioTracks&&(a=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),Yl(a)),e.subtitles&&(o=e.subtitles,Yl(o));const h=l.slice(0);l.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return ct.indexOf(t.videoRange)-ct.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=qr(t.videoCodec),i=qr(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=zr(t.codecSet),i=zr(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length))for(let v=0;v<h.length;v++)if(h[v].pathwayId===l[0].pathwayId){c=h[v];break}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===c){var u;this._firstLevel=v;const t=c.bitrate,e=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const s=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);s>e&&e===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=s)}break}const f=r&&!i,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:m&&!f&&a.some(t=>!!t.url)};d.end=performance.now(),this.hls.trigger($.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const s=new Error("invalid level idx"),i=t<0;if(this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger($.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),s=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=s}}onError(t,e){!e.fatal&&e.context&&e.context.type===N.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===U.MAIN){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger($.LEVEL_LOADING,{url:s,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const s=this._levels.filter((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));La(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.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($.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger($.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}},Yi=class extends se{constructor(t,e,s){super(t,e,s,"stream-controller",U.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 t=this.media,e=t?t.currentTime:null;if(null===e||!C(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const s=this.getFwdBufferInfoAtPos(t,e,U.MAIN,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on($.BUFFER_CREATED,this.onBufferCreated,this),t.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off($.BUFFER_CREATED,this.onBufferCreated,this),t.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}s>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=ee.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=ee.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ee.WAITING_LEVEL:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=ee.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=ee.IDLE;break}break}case ee.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===ee.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger($.BUFFER_EOS,t),void(this.state=ee.ENDED)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===ee.WAITING_LEVEL||this.waitForLive(n))return this.level=r,this.state=ee.WAITING_LEVEL,void(this.startFragRequested=!1);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&yr(u)&&this.fragmentTracker.getState(u)!==At.OK){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?Q.AUDIO:Q.VIDEO,e=(t===Q.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,U.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,U.MAIN,h)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i===At.NOT_LOADED||i===At.PARTIAL?yr(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,s):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,U.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let s;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case ee.KEY_LOADING:case ee.FRAG_LOADING:case ee.FRAG_LOADING_WAITING_RETRY:case ee.PARSING:case ee.PARSED:this.state=ee.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;_a(s,"playing",this.onMediaPlaying),_a(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:s}=this;s&&(Ca(s,"playing",this.onMediaPlaying),Ca(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e),e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger($.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let s=!1,i=!1;for(let r=0;r<e.levels.length;r++){const t=e.levels[r].audioCodec;t&&(s=s||-1!==t.indexOf("mp4a.40.2"),i=i||-1!==t.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var t;const e=jl();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==ee.IDLE)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=ee.WAITING_LEVEL)}onLevelLoaded(t,e){var s;const{levels:i,startFragRequested:r}=this,n=e.level,a=e.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,d=this.fragCurrent;!d||this.state!==ee.FRAG_LOADING&&this.state!==ee.FRAG_LOADING_WAITING_RETRY||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,h),this.hls.trigger($.LEVEL_UPDATED,{details:a,level:n}),this.state===ee.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=ee.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const t=Ot.bufferInfo(s,i,0);if(null==(l=t.buffered)||!l.length)return void(s.currentTime=i);if(t.start<=r)return void(s.currentTime=i);const{nextStart:e}=Ot.bufferedInfo(t.buffered,r,0);e&&(s.currentTime=e)}else s.currentTime=i}}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new je(this.hls,U.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new xt(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,h,c,l,s,i,o.totalduration,d,m,p)}onAudioTrackSwitching(t,e){const s=this.hls,i=0!==this.altAudio;if(yn(e.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once($.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger($.AUDIO_TRACK_SWITCHED,e)}),void s.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger($.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=yn(e.url,this.hls);if(s){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=s?2:0,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const a in s){const t=s[a];if("main"===t.id){if(r=a,i=t,"video"===a){const t=s[a];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e,r=s.type===U.MAIN;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===ee.PARSED&&(this.state=ee.IDLE));const t=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),yr(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&Ot.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var s;if(e.fatal)this.state=ee.ERROR;else switch(e.details){case F.FRAG_GAP:case F.FRAG_PARSING_ERROR:case F.FRAG_DECRYPT_ERROR:case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.MAIN,e);break;case F.LEVEL_LOAD_ERROR:case F.LEVEL_LOAD_TIMEOUT:case F.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ee.WAITING_LEVEL||(null==(s=e.context)?void 0:s.type)!==N.LEVEL||(this.state=ee.IDLE);break;case F.BUFFER_ADD_CODEC_ERROR:case F.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case F.BUFFER_FULL_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case F.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=ee.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Q.AUDIO||!this.altAudio){const t=(e===Q.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,U.MAIN),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${e}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=Ot.getBuffered(t),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),e<s&&(this.log(`seek to target start position ${s} from current time ${e} buffer start ${a}`),t.currentTime=s)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:s}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=ee.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger($.FRAG_LOADED,t),i.bitrateTest=!1}).catch(e=>{this.state!==ee.STOPPED&&this.state!==ee.ERROR&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=t,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:h,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=ee.PARSING,u){const t=u.tracks;if(t){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,t,i,r),s.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:e,tracks:t})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(C(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const t=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:t},s.trigger($.INIT_PTS_FOUND,{frag:a,id:e,initPTS:i,timescale:n,trackId:t})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,s=!t||a.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:i,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,i,a.start,l,!0)}else e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,t,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,e||s)}else{if(!e&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[Q.AUDIO]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(Q.AUDIO,t,e,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const t={id:e,frag:a,details:f,samples:c.samples};s.trigger($.FRAG_PARSING_METADATA,t)}if(f&&h){const t={id:e,frag:a,details:f,samples:h.samples};s.trigger($.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${yr(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,s,i){if(this.state!==ee.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=e;if(r){const s=t.audioCodec;let i=Qr(r.codec,s);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=U.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=U.MAIN;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){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"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger($.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger($.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,U.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,s=null==t?void 0:t[e];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=ee.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(Ot.isBuffered(t,s)?e=this.getAppendedFrag(s):Ot.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger($.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger($.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return C(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(C(e)){const t=this.getLevelDetails(),s=this.currentFrag||(t?En(null,t.fragments,e):null);if(s){const t=s.programDateTime;if(null!==t){const i=t+1e3*(e-s.start);return new Date(i)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}},ji=class extends K{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=F.KEY_LOAD_ERROR,s,i,r){return new _t({type:O.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i})}loadClear(t,e,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let i=0,r=e.length;i<r;i++){const n=e[i];if(t.cc<=n.cc&&(!yr(t)||!yr(n)||t.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(t=>{if(!this.emeController)return;n.setKeyFormat(t);const e=Qn(t);return e?this.emeController.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=Jn(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var s,i;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const s=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,F.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,F.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=zl(r);let o=this.keyIdToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:t,keyInfo:o});if(this.emeController&&null!=(i=o)&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(e=>{const{keyInfo:s}=e;return r.key=s.decryptdata.key,{frag:t,keyInfo:s}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+mr(r.keyId):""} URI: ${r.uri} from ${t.type} ${t.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,F.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var i;if(!t.decryptdata.keyId&&null!=(i=e.initSegment)&&i.data){const s=function(t){const e=[];return Mr(t,t=>e.push(t.subarray(8,24))),e}(e.initSegment.data);if(s.length){let e=s[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${mr(e)}`),jt.setKeyIdForUri(t.decryptdata.uri,e)):(e=jt.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${mr(e)}`)),t.decryptdata.keyId=e}}return t.decryptdata.keyId||yr(e)?(t.keyLoadPromise=this.emeController.loadKey(s).then(e=>(t.mediaKeySessionContext=e,s))).catch(s=>{throw t.keyLoadPromise=null,"data"in s&&(s.data.frag=e),s}):Promise.resolve(s)}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,i=new(0,s.loader)(s);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(a,l,{onSuccess:(t,e,s,i)=>{const{frag:a,keyInfo:o}=s,l=zl(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,F.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,F.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,dr({url:a.url,data:void 0},t)))},onTimeout:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,F.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,F.INTERNAL_ABORTED,new Error("key loading aborted"),i))}})})}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=null,s.loader=null);const n=zl(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}},qi=class{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_LOADING,this.onLevelLoading,this),t.off($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:N.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:N.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:N.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:N.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const s=this.loaders[N.LEVEL];if(s){const t=s.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(s.abort(),delete this.loaders[N.LEVEL])}}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,s=r.context;if(s&&s.levelOrTrack===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void(s.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===N.MANIFEST?s.manifestLoadPolicy.default:or({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),C(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===N.LEVEL&&null!==t.level?e=this.hls.levels[t.level].details:t.type===N.AUDIO_TRACK&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===N.SUBTITLE_TRACK&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);i=or({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};r.load(t,a,{onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;e.parsing.start=performance.now(),Jt.isMediaPlaylist(n)||s.type!==N.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}})}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Ql(t,s),o=Jt.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];Wr(a,"audio",s)?(t.audioCodec=i=i?`${i},${a}`:a,nt.audio[i.substring(0,4)]=2,e.splice(n,1)):Wr(a,"video",s)&&(t.videoCodec=r=r?`${r},${a}`:a,nt.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Jt.parseMasterPlaylistMedia(n,a,o);g.length&&(g.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ut({}),bitrate:0,url:""}))),r.trigger($.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,d=Ql(t,s),h=C(o)?o:C(a)?a:0,c=Xl(s),u=Jt.parseLevelPlaylist(t.data,d,h,c,0,this.variableList);if(l===N.MANIFEST){const t={attrs:new Ut({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=e.loading.start+Ea(u,0),n.trigger($.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.MANIFEST_PARSING_ERROR,fatal:e.type===N.MANIFEST,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===N.LEVEL?n+=`: ${t.level} id: ${t.id}`:t.type!==N.AUDIO_TRACK&&t.type!==N.SUBTITLE_TRACK||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=F.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case N.MANIFEST:o=s?F.MANIFEST_LOAD_TIMEOUT:F.MANIFEST_LOAD_ERROR,l=!0;break;case N.LEVEL:o=s?F.LEVEL_LOAD_TIMEOUT:F.LEVEL_LOAD_ERROR,l=!1;break;case N.AUDIO_TRACK:o=s?F.AUDIO_TRACK_LOAD_TIMEOUT:F.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case N.SUBTITLE_TRACK:o=s?F.SUBTITLE_TRACK_LOAD_TIMEOUT:F.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const h={type:O.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:r};i&&(h.response=dr({url:(null==e?void 0:e.url)||t.url,data:void 0},i)),this.hls.trigger($.ERROR,h)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:h,groupId:c,deliveryDirectives:u}=i,f=Ql(e,i),g=Xl(i);let m="number"==typeof i.level&&g===U.MAIN?l:void 0;const p=t.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:e,context:i,level:m,parent:g,networkDetails:r,stats:s});t.playlistParsingError=null}if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:e,context:i,level:m,parent:g,networkDetails:r,stats:s})}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case N.MANIFEST:case N.LEVEL:if(m)if(d){if(d!==a.levels[m]){const t=a.levels.indexOf(d);t>-1&&(m=t)}}else m=0;a.trigger($.LEVEL_LOADED,{details:t,levelInfo:d||a.levels[0],level:m||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===N.MANIFEST});break;case N.AUDIO_TRACK:a.trigger($.AUDIO_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case N.SUBTITLE_TRACK:a.trigger($.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u})}}},t("t",zi=class t{static get version(){return oe}static isMSESupported(){return ql()}static isSupported(){return function(){if(!ql())return!1;const t=ur();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(jr(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(jr(e,"audio"))))}()}static getMediaSource(){return ur()}static get Events(){return $}static get MetadataSchema(){return ce}static get ErrorTypes(){return O}static get ErrorDetails(){return F}static get DefaultConfig(){return t.defaultConfig?t.defaultConfig:Bi}static set DefaultConfig(e){t.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 ae,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 s=this.logger=function(t,e,s){const i=hr();if("object"==typeof console&&!0===t||"object"==typeof t){const n=["debug","log","info","warn","error"];n.forEach(e=>{i[e]=cr(e,t,s)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch(r){return hr()}n.forEach(e=>{W[e]=cr(e,t)})}else or(W,i);return i}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(t,e,s){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Ul(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach(s=>{const r=`${t}Loading${s}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=i[n].default;switch(e[n]={default:t},s){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${pt(e[n])}`)}),dr(dr({},i),e)}(t.DefaultConfig,e,s);this.userConfig=e,i.progressive&&Bl(i,s);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=i,d=new o(this),h=this.abrController=new r(this),c=new Lt(this),u=i.interstitialsController,f=u?this.interstitialsController=new u(this,t):null,g=this.bufferController=new n(this,c),m=this.capLevelController=new a(this),p=new l(this),v=new qi(this),y=i.contentSteeringController,E=y?new y(this):null,T=this.levelController=new Wi(this,E),S=new Vi(this),A=new ji(this.config,this.logger),L=this.streamController=new Yi(this,c,A),I=this.gapController=new Gi(this,c);m.setStreamController(L),p.setStreamController(L);const b=[v,T,L];f&&b.splice(1,0,f),E&&b.splice(1,0,E),this.networkControllers=b;const R=[h,g,I,m,p,S,c];this.audioTrackController=this.createController(i.audioTrackController,b);const k=i.audioStreamController;k&&b.push(this.audioStreamController=new k(this,c,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,b);const D=i.subtitleStreamController;D&&b.push(this.subtititleStreamController=new D(this,c,A)),this.createController(i.timelineController,R),A.emeController=this.emeController=this.createController(i.emeController,R),this.cmcdController=this.createController(i.cmcdController,R),this.latencyController=this.createController(Hi,R),this.coreComponents=R,b.push(d);const w=d.onErrorOut;"function"==typeof w&&this.on($.ERROR,w,d),this.on($.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(s){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const e=t===$.ERROR;this.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,fatal:e,event:t,error:s}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger($.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,s=e?t.media:t,i=e?t:{media:s};this._media=s,this.trigger($.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger($.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger($.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,s=this._url,i=this._url=z.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),e&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger($.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,e),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[U.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[U.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[U.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return ht.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let i=0;i<s;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let r=i;r--;){const e=t[r].attrs["HDCP-LEVEL"];if(e&&e<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return nn(t,un(e),navigator.mediaCapabilities)}}),zi.defaultConfig=void 0}}});
1
+ System.register(["./chunk-legacy-D5ZT36tR.js","./store-legacy-CI1UFD5I.js"],function(t,e){var s,i,r,n,a,o,l,d,h,c,u,f,g,m,p,v,y,E,T,S,A,L,I,b,R,k,D,w,P,_,C,x,M,O,F,$,N,U,B,G,K,V,H,W,Y,j,q,z,X,Q,Z,J,tt,et,st,it,rt,nt,at,ot,lt,dt,ht,ct,ut,ft,gt,mt,pt,vt,yt,Et,Tt,St,At,Lt,It,bt,Rt,kt,Dt,wt,Pt,_t,Ct,xt,Mt,Ot,Ft,$t,Nt,Ut,Bt,Gt,Kt,Vt,Ht,Wt,Yt,jt,qt,zt,Xt,Qt,Zt,Jt,te,ee,se,ie,re,ne,ae,oe,le,de,he,ce,ue,fe,ge,me,pe,ve,ye,Ee,Te,Se,Ae,Le,Ie,be,Re,ke,De,we,Pe,_e,Ce,xe,Me,Oe,Fe,$e,Ne,Ue,Be,Ge,Ke,Ve,He,We,Ye,je,qe,ze,Xe,Qe,Ze,Je,ts,es,ss,is,rs,ns,as,os,ls,ds,hs,cs,us,fs,gs,ms,ps,vs,ys,Es,Ts,Ss,As,Ls,Is,bs,Rs,ks,Ds,ws,Ps,_s,Cs,xs,Ms,Os,Fs,$s,Ns,Us,Bs,Gs,Ks,Vs,Hs,Ws,Ys,js,qs,zs,Xs,Qs,Zs,Js,ti,ei,si,ii,ri,ni,ai,oi,li,di,hi,ci,ui,fi,gi,mi,pi,vi,yi,Ei,Ti,Si,Ai,Li,Ii,bi,Ri,ki,Di,wi,Pi,_i,Ci,xi,Mi,Oi,Fi,$i,Ni,Ui,Bi,Gi,Ki,Vi,Hi,Wi,Yi,ji,qi,zi;function Xi(t){switch(t){case 1:case 2:case 3:default:return 0;case 4:return 2;case 5:return 1}}function Qi(t){if("string"!=typeof t)return[];const e=t.matchAll(/<d[^>]*?p="(?<p>[^"]+)"[^>]*>(?<text>.*?)<\/d>/gs);return Array.from(e).map(t=>{const e=t.groups.p.split(",");return e.length>=8?{text:t.groups.text.trim().replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&"),time:Number(e[0]),mode:Xi(Number(e[1])),fontSize:Number(e[2]),color:`#${Number(e[3]).toString(16)}`,timestamp:Number(e[4]),pool:Number(e[5]),userID:e[6],rowID:Number(e[7])}:null}).filter(Boolean)}function Zi({data:t}){const{xml:e,id:s}=t;if(!s||!e)return;const i=Qi(e);globalThis.postMessage({danmus:i,id:s})}function Ji(){const t=`\n ${Xi.toString()}\n ${Qi.toString()}\n onmessage = ${Zi.toString()}\n `,e=new Blob([t],{type:"application/javascript"});return new Worker(URL.createObjectURL(e))}function tr(t){let e;try{if(e=o&&(self.URL||self.webkitURL).createObjectURL(o),!e)throw"";const s=new Worker(e,{type:"module",name:t?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),s}catch(s){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(a),{type:"module",name:t?.name})}}function er(t,e,s){const{query:i}=t.constructor.utils;t.controls.add({name:"heatmap",position:"top",html:"",style:{position:"absolute",top:"-100px",left:"0px",right:"0px",height:"100px",width:"100%",pointerEvents:"none"},mounted(r){let n=null,a=null;function o(o=[]){if(n=null,a=null,r.innerHTML="",!t.duration||t.option.isLive)return;const l={w:r.offsetWidth,h:r.offsetHeight},h={xMin:0,xMax:l.w,yMin:0,yMax:128,scale:.25,opacity:.2,minHeight:Math.floor(.05*l.h),sampling:Math.floor(l.w/100),smoothing:.2,flattening:.2};"object"==typeof s&&Object.assign(h,s);let c=[];if(Array.isArray(o)&&o.length)c=[...o];else{const s=t.duration/l.w;for(let t=0;t<=l.w;t+=h.sampling){const i=e.queue.filter(({time:e})=>e>t*s&&e<=(t+h.sampling)*s).length;c.push([t,i])}}if(0===c.length)return;const u=c[c.length-1],f=u[0],g=u[1];f!==l.w&&c.push([l.w,g]);const m=c.map(t=>t[1]),p=(Math.min(...m)+Math.max(...m))/2;for(let t=0;t<c.length;t++){const e=c[t],s=e[1];e[1]=s*(s>p?1+h.scale:1-h.scale)+h.minHeight}const v=(t,e,s,i)=>{const r=function(t,e){const s=e[0]-t[0],i=e[1]-t[1];return{length:Math.sqrt(s**2+i**2),angle:Math.atan2(i,s)}}(e||t,s||t),n=d.map(Math.cos(r.angle)*h.flattening,0,1,1,0),a=r.angle*n+(i?Math.PI:0),o=r.length*h.smoothing;return[t[0]+Math.cos(a)*o,t[1]+Math.sin(a)*o]},y=c.map(t=>[d.map(t[0],h.xMin,h.xMax,0,l.w),d.map(t[1],h.yMin,h.yMax,l.h,0)]).reduce((t,e,s,i)=>0===s?`M ${i[i.length-1][0]},${l.h} L ${e[0]},${l.h} L ${e[0]},${e[1]}`:`${t} ${((t,e,s)=>{const i=v(s[e-1],s[e-2],t),r=v(t,s[e-1],s[e+1],!0),n=e===s.length-1?" z":"";return`C ${i[0]},${i[1]} ${r[0]},${r[1]} ${t[0]},${t[1]}${n}`})(e,s,i)}`,"");r.innerHTML=`\n <svg viewBox="0 0 ${l.w} ${l.h}">\n <defs>\n <linearGradient id="heatmap-solids" x1="0%" y1="0%" x2="100%" y2="0%">\n <stop offset="0%" style="stop-color:var(--art-theme);stop-opacity:${h.opacity}" />\n <stop offset="0%" style="stop-color:var(--art-theme);stop-opacity:${h.opacity}" id="heatmap-start" />\n <stop offset="0%" style="stop-color:var(--art-progress-color);stop-opacity:1" id="heatmap-stop" />\n <stop offset="100%" style="stop-color:var(--art-progress-color);stop-opacity:1" />\n </linearGradient>\n </defs>\n <path fill="url(#heatmap-solids)" d="${y}"></path>\n </svg>\n `,n=i("#heatmap-start",r),a=i("#heatmap-stop",r),n.setAttribute("offset",100*t.played+"%"),a.setAttribute("offset",100*t.played+"%")}t.on("video:timeupdate",()=>{n&&a&&(n.setAttribute("offset",100*t.played+"%"),a.setAttribute("offset",100*t.played+"%"))}),t.on("setBar",(t,e)=>{n&&a&&"played"===t&&(n.setAttribute("offset",100*e+"%"),a.setAttribute("offset",100*e+"%"))}),t.on("ready",()=>o()),t.on("resize",()=>o()),t.on("artplayerPluginDanmuku:loaded",()=>o()),t.on("artplayerPluginDanmuku:points",t=>o(t))}})}function sr(t){return e=>{const s=new l(e,t),i=new A(e,s);return s.option.heatmap&&er(e,s,s.option.heatmap),{name:"artplayerPluginDanmuku",emit:s.emit.bind(s),load:s.load.bind(s),config:s.config.bind(s),hide:s.hide.bind(s),show:s.show.bind(s),reset:s.reset.bind(s),mount:i.mount.bind(i),get option(){return s.option},get isHide(){return s.isHide},get isStop(){return s.isStop}}}}function ir(t){return function(t){return/^https?:\/\//.test(t)}(t)?t:new URL(t,document.baseURI).toString()}function rr({workerUrl:t,wasmUrl:e}){return new Promise(s=>{fetch(t).then(t=>t.text()).then(i=>{let r=i;r=r.replace(/wasmBinaryFile\s*=\s*"(subtitles-octopus-worker\.wasm)"/g,(s,i)=>`wasmBinaryFile = "${e=e?ir(e):new URL(i,ir(t)).toString()}"`);const n=new Blob([r],{type:"text/javascript"});s(URL.createObjectURL(n))})})}function nr(t){_.canvasParent&&(_.canvasParent.style.display=t?"block":"none")}function ar(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function or(){return or=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var i in s)({}).hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},or.apply(null,arguments)}function lr(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),s.push.apply(s,i)}return s}function dr(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?lr(Object(s),!0).forEach(function(e){ar(t,e,s[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):lr(Object(s)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))})}return t}function hr(){return or({},H)}function cr(t,e,s){return e[t]?e[t].bind(e):function(t,e){const s=self.console[t];return s?s.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):V}(t,s)}function ur(t=!0){if("undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function fr(t,e){const s=Object.keys(t),i=Object.keys(e),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(t=>-1===i.indexOf(t))}function gr(t,e=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(t);if(e){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"")}const s=t.length;let i,r,n,a="",o=0;for(;o<s;){if(i=t[o++],0===i&&e)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=t[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=t[o++],n=t[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&n)}}return a}function mr(t){let e="";for(let s=0;s<t.length;s++){let i=t[s].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function pr(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function vr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function yr(t){return"initSegment"!==t.sn}function Er(t,e){const s=Object.getPrototypeOf(t);if(s){const t=Object.getOwnPropertyDescriptor(s,e);return t||Er(s,e)}}function Tr(t,e){const s=Er(t,e);s&&(s.enumerable=!0,Object.defineProperty(t,e,s))}function Sr(t){return String.fromCharCode.apply(null,t)}function Ar(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function Lr(t,e){const s=br(t,e);return s<0?4294967296+s:s}function Ir(t,e){let s=Lr(t,e);return s*=Math.pow(2,32),s+=Lr(t,e+4),s}function br(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Rr(t,e){const s=[];if(!e.length)return s;const i=t.byteLength;for(let r=0;r<i;){const n=Lr(t,r),a=n>1?r+n:i;if(Sr(t.subarray(r+4,r+8))===e[0])if(1===e.length)s.push(t.subarray(r+8,a));else{const i=Rr(t.subarray(r+8,a),e.slice(1));i.length&&st.apply(s,i)}r=a}return s}function kr(t){const e=[],s=t[0];let i=8;const r=Lr(t,i);i+=4;let n=0,a=0;0===s?(n=Lr(t,i),a=Lr(t,i+4),i+=8):(n=Ir(t,i),a=Ir(t,i+8),i+=16),i+=2;let o=t.length+a;const l=Ar(t,i);i+=2;for(let d=0;d<l;d++){let s=i;const n=Lr(t,s);s+=4;const a=2147483647&n;if((2147483648&n)>>>31==1)return Y.warn("SIDX has hierarchical references (not supported)"),null;const l=Lr(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function Dr(t){const e=[],s=Rr(t,["moov","trak"]);for(let i=0;i<s.length;i++){const t=s[i],r=Rr(t,["tkhd"])[0];if(r){let s=r[0];const i=Lr(r,0===s?12:20),n=Rr(t,["mdia","mdhd"])[0];if(n){s=n[0];const r=Lr(n,0===s?12:20),a=Rr(t,["mdia","hdlr"])[0];if(a){const s=Sr(a.subarray(8,12)),n={soun:Q.AUDIO,vide:Q.VIDEO}[s],o=wr(Rr(t,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:r,type:n,stsd:o},e[n]=dr({timescale:r,id:i},o)):e[i]={timescale:r,type:s,stsd:o}}}}}return Rr(t,["moov","mvex","trex"]).forEach(t=>{const s=e[Lr(t,4)];s&&(s.default={duration:Lr(t,12),flags:Lr(t,20)})}),e}function wr(t){const e=t.subarray(8),s=e.subarray(86),i=Sr(e.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;a&&Rr(Rr(e,[i])[0].subarray("enca"===i?28:78),["sinf"]).forEach(t=>{const e=Rr(t,["schm"])[0];if(e){const s=Sr(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=Rr(t,["frma"])[0];e&&(n=Sr(e))}}});const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Rr(s,["avcC"])[0];t&&t.length>3&&(n+="."+Cr(t[1])+Cr(t[2])+Cr(t[3]),r=Pr("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const t=Rr(e,[i])[0],s=Rr(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=_r(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=_r(s,t);const i=s[t++];if(64!==i)break;if(n+="."+Cr(i),t+=12,5!==s[t++])break;t=_r(s,t);const r=s[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=Rr(s,["hvcC"])[0];if(t&&t.length>12){const e=t[1],s=["","A","B","C"][e>>6],i=31&e,r=Lr(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+s+i,n+="."+function(t){let e=0;for(let s=0;s<32;s++)e|=(t>>s&1)<<31-s;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];(e||d)&&(d="."+e.toString(16).toUpperCase()+d)}n+=d}r=Pr("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Pr(n,s)||n;break;case"vp09":{const t=Rr(s,["vpcC"])[0];if(t&&t.length>6){const e=t[4],s=t[5],i=t[6]>>4&15;n+="."+xr(e)+"."+xr(s)+"."+xr(i)}break}case"av01":{const t=Rr(s,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2];n+="."+e+"."+xr(i)+a+"."+xr(d)+"."+h+"."+c+u+f+"."+xr(1)+"."+xr(1)+"."+xr(1)+".0",r=Pr("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function Pr(t,e){const s=Rr(e,["dvvC"]),i=s.length?s[0]:Rr(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return t+"."+xr(e)+"."+xr(s)}}function _r(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function Cr(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function xr(t){return(t<10?"0":"")+t}function Mr(t,e){Rr(t,["moov","trak"]).forEach(t=>{const s=Rr(t,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=Rr(i,["enca"]);const n=r.length>0;n||(r=Rr(i,["encv"])),r.forEach(t=>{Rr(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const s=Or(t);s&&e(s,n)})})})}function Or(t){const e=Rr(t,["schm"])[0];if(e){const s=Sr(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=Rr(t,["schi","tenc"])[0];if(e)return e}}}function Fr(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function $r(t,e){const s=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return Rr(i,["moof"]).map(o=>{const l=o.byteOffset-8;Rr(o,["traf"]).map(o=>{const d=Rr(o,["tfdt"]).map(t=>{const e=t[0];let s=Lr(t,4);return 1===e&&(s*=Math.pow(2,32),s+=Lr(t,8)),s/r})[0];return void 0!==d&&(t=d),Rr(o,["tfhd"]).map(d=>{const h=Lr(d,4),c=16777215&Lr(d,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;h===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=Lr(d,p),p+=4),f&&(g=Lr(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=Nr(e.codec)),Rr(o,["trun"]).map(n=>{const o=n[0],d=16777215&Lr(n,0),h=!!(1&d);let c=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const A=Lr(n,4);let L=8;h&&(c=Lr(n,L),L+=4),f&&(L+=4);let I=c+l;for(let l=0;l<A;l++){if(m?(p=Lr(n,L),L+=4):p=u,v?(y=Lr(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?Lr(n,L):br(n,L),L+=4),e.type===Q.VIDEO){let e=0;for(;e<y;){const n=Lr(i,I);I+=4,Ur(a,i[I])&&Br(i.subarray(I,I+n),a?2:1,t+S/r,s),I+=n,e+=n+4}}t+=p/r}}))})})}),s}function Nr(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Ur(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6==(31&e)}function Br(t,e,s,i){const r=Gr(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){Y.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Ar(r,e);if(e+=2,49===t){const t=Lr(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=r[e++]}i.push({type:t,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let s=0;s<n;s++)l[s]=r[e++];i.push({payloadType:a,pts:s,uuid:t.join(""),userData:gr(l),userDataBytes:l})}}}function Gr(t){const e=t.byteLength,s=[];let i=1;for(;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return t;const r=e-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=t[a];return n}function Kr(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,s)}function Vr(t){const e=t.getUint32(0),s=t.byteOffset,i=t.byteLength;if(i<e)return{offset:s,size:i};if(1886614376!==t.getUint32(4))return{offset:s,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=mr(new Uint8Array(n,s+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=t.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,s+32+16*t,16));d=32+16*r}if(!d)return{offset:s,size:e};const h=t.getUint32(d);return e-32<h?{offset:s,size:e}:(l=new Uint8Array(n,s+d+4,h),{version:r,systemId:a,kids:o,data:l,offset:s,size:e})}function Hr(t,e){const s=nt[e];return!!s&&!!s[t.slice(0,4)]}function Wr(t,e,s=!0){return!t.split(",").some(t=>!Yr(t,e,s))}function Yr(t,e,s=!0){var i;const r=ur(s);return null!=(i=null==r?void 0:r.isTypeSupported(jr(t,e)))&&i}function jr(t,e){return`${e}/mp4;codecs=${t}`}function qr(t){if(t){const e=t.substring(0,4);return nt.video[e]}return 2}function zr(t){const e=rt();return t.split(",").reduce((t,s)=>{const i=e&&Nr(s)?9:nt.video[s];return i?(2*i+t)/(t?3:2):(nt.audio[s]+t)/(t?2:1)},0)}function Xr(t,e=!0){return t.replace(ot,t=>function(t,e=!0){if(at[t])return at[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<s.length;r++){var i;if(Yr(s[r],"audio",e))return at[t]=s[r],s[r];if("mp3"===s[r]&&null!=(i=ur(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function Qr(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Zr(t,"audio")||Zr(t,"video")))return t;if(e){const s=e.split(",");if(s.length>1){if(t)for(let e=s.length;e--;)if(s[e].substring(0,4)===t.substring(0,4))return s[e];return s[0]}}return e||t}function Zr(t,e){return Hr(t,e)&&Yr(t,e)}function Jr(t){if(t.startsWith("av01.")){const e=t.split("."),s=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=s[t-4];return e.join(".")}return t}function tn(t){const e=ur(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function en(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function sn(t,e){return{supported:!1,configurations:e,decodingInfoResults:[lt],error:t}}function rn(t,e,s,i,r,n){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,h=d?parseInt(d):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(e=>{t[e]=(t[e]||0)+i.channels[e]})}return t},{2:0})}catch(u){return!0}return void 0!==a&&(a.split(",").some(t=>Nr(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!c&&C(h)&&Object.keys(c).some(t=>parseInt(t)>h)}function nn(t,e,s,i={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!s)return Promise.resolve(dt);const n=[],a=function(t){var e;const s=null==(e=t.videoCodec)?void 0:e.split(","),i=on(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return s?s.map(t=>{const e={contentType:jr(Jr(t),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,s){var i;const r=null==(i=t.audioCodec)?void 0:i.split(","),n=on(t);return r&&t.audioGroups?t.audioGroups.reduce((t,i)=>{var a;const o=i?null==(a=e.groups[i])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===i){const i=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:jr(e,"audio"),bitrate:s?an(e,n):n};i&&(r.channels=""+i),t.push(r)})}return t},t):t},[]):[]}(t,e,o>0),d=l.length;for(let h=o||1*d||1;h--;){const t={type:"media-source"};if(o&&(t.video=a[h%o]),d){t.audio=l[h%d];const e=t.audio.bitrate;t.video&&e&&(t.video.bitrate-=e)}n.push(t)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>Nr(t))&&rt())return Promise.resolve(sn(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:s,video:i}=t;return i&&(e+=`${en(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`),s&&(e+=`${i?"_":""}${en(s.contentType)}_c${s.channels}`),e}(t);return i[e]||(i[e]=s.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function an(t,e){if(e<=1)return 1;let s=128e3;return"ec-3"===t?s=768e3:"ac-3"===t&&(s=64e4),Math.min(e/2,s)}function on(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function ln(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i<e/2?s?ut.v2:ut.Yes:ut.No}function dn(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function hn(t,e){let s=!1,i=[];if(t&&(s="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||ct.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;s=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}function cn(t,e){Y.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function un(t){return t.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function fn(t){if(!t)return t;const{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}=t;return{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function gn(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i<e.length;i++)if(mn(t,e[i],s))return i;return-1}function mn(t,e,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===i||e.groupId===i)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){return t.length===e.length?t===e:t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const s=t.split(","),i=e.split(",");return s.length===i.length&&!s.some(t=>-1===i.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===s||s(t,e))}function pn(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function vn(t,e,s){for(let i=e;i>-1;i--)if(s(t[i]))return i;for(let i=e+1;i<t.length;i++)if(s(t[i]))return i;return-1}function yn(t,e){var s;return!!t&&t!==(null==(s=e.loadLevelObj)?void 0:s.uri)}function En(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Tn(s,i,n)||function(t,e,s){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=yt.search(e,Tn.bind(null,s,i));return!a||a===t&&n?n:a}function Tn(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function Sn(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}function An(t,e,s){if(t&&t.startCC<=e&&t.endCC>=e){let i=t.fragments;const{fragmentHint:r}=t;let n;return r&&(i=i.concat(r)),yt.search(i,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=s?1:t.start>s?-1:0)),n||null}return null}function Ln(t){switch(t.details){case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_TIMEOUT:case F.LEVEL_LOAD_TIMEOUT:case F.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function In(t){return t.details.startsWith("key")}function bn(t){return In(t)&&!!t.frag&&!t.frag.decryptdata}function Rn(t,e){const s=Ln(e);return t.default[(s?"timeout":"error")+"Retry"]}function kn(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function Dn(t){return dr(dr({},t),{errorRetry:null,timeoutRetry:null})}function wn(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return Pn(t)||!!t&&(t<400||t>499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}function Pn(t){return 0===t&&!1===navigator.onLine}function _n(t){const e={action:Et.DoNothing,flags:Tt.None};return t&&(e.resolved=!0),e}function Cn(t){var e,s,i;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(s=t.range.audio)&&s.partial||null!=(i=t.range.audiovideo)&&i.partial)}function xn(t){return`${t.type}_${t.level}_${t.sn}`}function Mn(t,e){return t.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}function On(t,e=null){const s=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(C(r)&&C(n)){var a;let e=r,s=n;if("initSegment"===t.sn&&("AES-128"===(o=null==(a=t.decryptdata)?void 0:a.method)||"AES-256"===o)){const t=n-r;t%16&&(s=n+(16-t%16)),0!==r&&(i.resetIV=!0,e=r-16)}i.rangeStart=e,i.rangeEnd=s}var o;return i}function Fn(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:O.MEDIA_ERROR,details:F.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new _t(i)}function $n(t){return Ft.test(t)}function Nn(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(Ft,e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r})}return e}function Un(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(a){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Bn(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function Gn(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function Kn(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}function Vn(t,e){return t.length===e.length&&!t.some((t,s)=>t!==e[s])}function Hn(t,e){return!t&&!e||!(!t||!e)&&Vn(t,e)}function Wn(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Yn(t){switch(t){case"AES-128":case"AES-256":return It.cbc;case"AES-256-CTR":return It.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function jn(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function qn(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function zn(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function Xn(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=jn(r)):s=function(t){const e=qn(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}function Qn(t){switch(t){case Ht.FAIRPLAY:return Vt.FAIRPLAY;case Ht.PLAYREADY:return Vt.PLAYREADY;case Ht.WIDEVINE:return Vt.WIDEVINE;case Ht.CLEARKEY:return Vt.CLEARKEY}}function Zn(t){switch(t){case Vt.FAIRPLAY:return Ht.FAIRPLAY;case Vt.PLAYREADY:return Ht.PLAYREADY;case Vt.WIDEVINE:return Ht.WIDEVINE;case Vt.CLEARKEY:return Ht.CLEARKEY}}function Jn(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[Vt.FAIRPLAY,Vt.WIDEVINE,Vt.PLAYREADY,Vt.CLEARKEY].filter(t=>!!e[t]):[];return!i[Vt.WIDEVINE]&&s&&i.push(Vt.WIDEVINE),i}function ta(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),s=String.fromCharCode.apply(null,Array.from(e)),i=s.substring(s.indexOf("<"),s.length),r=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=jn(t).subarray(0,16);return zn(e),e}}return null}function ea(t){const e=null==t?void 0:t[Ht.PLAYREADY];if(e){const t=Xn(e.uri);if(t)return ta(t)}return null}function sa(t,e){let s=t.length;if(!s){if(!e.hasProgramDateTime)return;{const i=e.fragments[e.fragments.length-1];t.push(i),s++}}const i=t[s-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=t[i])?void 0:a.sn)<e.startSN)break;const s=ia(e,d,t,i,r);if(-1!==s){l.tagAnchor=e.fragments[s].ref;break}}}}function ia(t,e,s,i,r){const n=s[i];if(n){const o=n.programDateTime;var a;if((e>=o||0===i)&&e<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-t.startSN;if(r<0)return-1;const n=t.fragments;if(n.length>s.length)for(let a=(s[i+1]||n[n.length-1]).sn-t.startSN;a>r;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}return r}}return-1}function ra(t,e,s){var i,r;const n=new Ut(t,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(r=n.KEYFORMAT)?r:"identity";return o&&n.IV&&!l&&Y.error(`Invalid IV: ${n.IV}`),new jt(a,o?Jt.resolve(o,e):"",h,(d||"1").split("/").map(Number).filter(Number.isFinite),l,n.KEYID)}function na(t){const e=new Ut(t).decimalFloatingPoint("TIME-OFFSET");return C(e)?e:null}function aa(t,e){let s=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const i=s.filter(e=>Hr(e,t));i.length&&(e[`${t}Codec`]=i.map(t=>t.split("/")[0]).join(","),s=s.filter(t=>-1===i.indexOf(t)))}),e.unknownCodecs=s}function oa(t,e,s){const i=e[s];i&&(t[s]=i)}function la(t,e,s){t.rawProgramDateTime?s.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function da(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function ha(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||i.push(t)}function ca(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${s[0]})`)}function ua(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${s[0]})`)}function fa(t,e){const s=e.startPTS;if(C(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&i.setDuration(r)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration):e.setStart(Math.max(t.start-e.duration,0))}function ga(t,e,s,i,r,n,a){i-s<=0&&(a.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let o=s,l=i;const d=e.startPTS,h=e.endPTS;if(C(d)){const c=Math.abs(d-s);t&&c>t.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${e.level} ${t.url}`):C(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,o=Math.max(s,d),s=Math.min(s,d),r=void 0!==e.startDTS?Math.min(r,e.startDTS):r,l=Math.min(i,h),i=Math.max(i,h),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}const c=s-e.start;0!==e.start&&e.setStart(s),e.setDuration(i-e.start),e.startPTS=s,e.maxStartPTS=o,e.startDTS=r,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let f;const g=u-t.startSN,m=t.fragments;for(m[g]=e,f=g;f>0;f--)fa(m[f],m[f-1]);for(f=g;f<m.length-1;f++)fa(m[f],m[f+1]);return t.fragmentHint&&fa(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function ma(t,e,s){if(t===e)return;let i=null;const r=t.fragments;for(let h=r.length-1;h>=0;h--){const t=r[h].initSegment;if(t){i=t;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,s){const i=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let d=r;d<=n;d++){const r=l[a+d];let n=o[d];if(i&&!n&&r&&(n=e.fragments[d]=r),r&&n){s(r,n,d,o);const i=r.relurl,a=n.relurl;if(i&&Ia(i,a))return void(e.playlistParsingError=pa(`media sequence mismatch ${n.sn}:`,t,e,0,n));if(r.cc!==n.cc)return void(e.playlistParsingError=pa(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,t,e,0,n))}}}(t,e,(t,s,r,a)=>{if((!e.startCC||e.skippedSegments)&&s.cc!==t.cc){const i=t.cc-s.cc;for(let t=r;t<a.length;t++)a[t].cc+=i;e.endCC=a[a.length-1].cc}C(t.startPTS)&&C(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(n=s),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,i=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const{dateRanges:i,recentlyRemovedDateranges:r}=e,n=or({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;return a?(Object.keys(i).forEach(t=>{const e=n[t],r=new Bt(i[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${pt(i[t].attr)}"`)}),n):i}(t.dateRanges,e,s));const i=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&la(o[t],o[t-1],i);sa(i,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const s=Ta(t,e.startSN-1);e.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}!function(t,e,s){if(t&&e){let i=0;for(let r=0,n=t.length;r<=n;r++){const n=t[r],a=e[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),n?ga(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):va(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const t=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=t),e.driftEndTime=d,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function pa(t,e,s,i,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function va(t,e,s=!0){const i=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&s)a=t.fragmentStart+i*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}ya(e,a)}function ya(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i<s.length;i++)s[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function Ea(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments;if(i.length&&4*s>e){const t=1e3*i[i.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}function Ta(t,e,s){if(!t)return null;let i=t.fragments[e-t.startSN];return i||(i=t.fragmentHint,i&&i.sn===e?i:e<t.startSN&&s&&s.sn===e?s:null)}function Sa(t,e,s){return t?Aa(t.partList,e,s):null}function Aa(t,e,s){if(t)for(let i=t.length;i--;){const r=t[i];if(r.index===s&&r.fragment.sn===e)return r}return null}function La(t){t.forEach((t,e)=>{var s;null==(s=t.details)||s.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function Ia(t,e){return!(t===e||!e)&&ba(t)!==ba(e)}function ba(t){return t.replace(/\?[^?]*$/,"")}function Ra(t,e){for(let i=0,r=t.length;i<r;i++){var s;if((null==(s=t[i])?void 0:s.cc)===e)return t[i]}return null}function ka(t,e){const s=t.start+e;t.startPTS=s,t.setStart(s),t.endPTS=s+t.duration}function Da(t,e){const s=e.fragments;for(let i=0,r=s.length;i<r;i++)ka(s[i],t);e.fragmentHint&&ka(e.fragmentHint,t),e.alignedSliding=!0}function wa(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const s=Math.min(e.endCC,t.endCC),i=Ra(e.fragments,s),r=Ra(t.fragments,s);i&&r&&(Y.log(`Aligning playlist at start of dicontinuity sequence ${s}`),Da(i.start-r.start,t))}function Pa(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=Ra(i,a),n=Ra(s,a)),r&&n||(r=i[Math.floor(i.length/2)],n=Ra(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;o&&l&&Da((l-o)/1e3-(n.start-r.start),t)}function _a(t,e,s){Ca(t,e,s),t.addEventListener(e,s)}function Ca(t,e,s){t.removeEventListener(e,s)}function xa(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}function Ma(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Oa(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Fa(t,e){let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s}function $a(t,e){const s=e;let i=0;for(;Oa(t,e);)i+=10,i+=Fa(t,e+6),Ma(t,e+10)&&(i+=10),e+=i;if(i>0)return t.subarray(s,s+i)}function Na(t,e){return 255===t[e]&&240==(246&t[e+1])}function Ua(t,e){return 1&t[e+1]?7:9}function Ba(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Ga(t,e){return e+1<t.length&&Na(t,e)}function Ka(t,e){if(Ga(t,e)){const s=Ua(t,e);if(e+s>=t.length)return!1;const i=Ba(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||Ga(t,r)}return!1}function Va(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){const r=e[s+2],n=r>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit($.ERROR,$.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[s+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h=n;5!==a&&29!==a||(h-=3);const c=[a<<3|(14&h)>>1,(1&h)<<7|o<<3];return Y.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(e,s,i,r);if(!n)return;or(t,n)}}function Ha(t){return 9216e4/t}function Wa(t,e,s,i,r){const n=i+r*Ha(t.samplerate),a=function(t,e){const s=Ua(t,e);if(e+s<=t.length){const i=Ba(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,d=Math.max(0,s+l-e.length);d?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,s+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-s;return o=new Uint8Array(l),o.set(e.subarray(s,e.length),0),{sample:{unit:o,pts:n},length:l,missing:-1}}function Ya(t,e){return Oa(t,e)&&Fa(t,e+6)+10<=t.length-e}function ja(t,e=0,s=1/0){return function(t,e,s,i){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=(h=t)&&h.buffer instanceof ArrayBuffer&&void 0!==h.byteLength&&void 0!==h.byteOffset?t.byteOffset:0,o=(a+t.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o)));var h;return new i(r,d,Math.floor(Math.min(d+Math.max(s,0),o))-d)}(t,e,s,Uint8Array)}function qa(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=t.data.subarray(1).indexOf(0);if(-1===s)return;const i=gr(ja(t.data,1,s)),r=t.data[2+s],n=t.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=gr(ja(t.data,3+s,n));let o;return o="--\x3e"===i?gr(ja(t.data,4+s+n)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=a,e.data=o,e}function za(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=gr(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=gr(t.data.subarray(e),!0);e+=s.length+1;const i=gr(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=gr(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?qa(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=gr(t.data.subarray(e),!0);e+=s.length+1;const i=gr(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=gr(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function Xa(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=Fa(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}}function Qa(t){let e=0;const s=[];for(;Oa(t,e);){const i=Fa(t,e+6);t[e+5]>>6&1&&(e+=de),e+=de;const r=e+i;for(;e+he<r;){const i=Xa(t.subarray(e)),r=za(i);r&&s.push(r),e+=i.size+de}Ma(t,e)&&(e+=de)}return s}function Za(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Ja(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function to(t){const e=Qa(t);for(let s=0;s<e.length;s++){const t=e[s];if(Za(t))return Ja(t)}}function eo(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}function so(t,e,s,i,r){if(s+24>e.length)return;const n=io(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function io(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*me[14*(3===s?3-i:3===i?3:4)+r-1],d=pe[3*(3===s?0:2===s?1:2)+n],h=3===o?1:2,c=ve[s][i],u=ye[i],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===ge){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ge=t?parseInt(t[1]):0}return ge&&ge<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function ro(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function no(t,e){return e+1<t.length&&ro(t,e)}function ao(t,e){if(e+1<t.length&&ro(t,e)){const s=4,i=io(t,e);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===t.length||no(t,n)}return!1}function oo(t,e,s,i,r){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const d=e[s+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(e[s+6]<<8|e[s+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}function lo(t,e){return C(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}function ho(t,e){return((31&t[e+1])<<8)+t[e+2]}function co(t,e){return(31&t[e+10])<<8|t[e+11]}function uo(t,e,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=ho(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){go("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!i){go("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){go("AC-3",n);break}case 129:s.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let i=e+5,r=l;for(;r>2;){106===t[i]&&(!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3"));const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return fo(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=l+5}return a}function fo(t,e,s,i){i.warn(`parsing error: ${e.message}`),t.emit($.ERROR,$.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:e,reason:e.message})}function go(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function mo(t,e){let s,i,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Fr(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>t.size-6)return null;const d=s[7];192&d&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&d?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let h=r+9;if(t.size<=h)return null;t.size-=h;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){s=l[t];let e=s.byteLength;if(h){if(h>e){h-=e;continue}s=s.subarray(h),e-=h,h=0}c.set(s,o),o+=e}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}function po(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function vo(t,e=!1){return po(t,1e3,1/Oe,e)}function yo(t){const{baseTime:e,timescale:s,trackId:i}=t;return`${e/s} (${e}/${s}) trackId: ${i}`}function Eo(t,e,s,i){return{duration:e,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function To(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function So(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let o=0;o<r;o++){const r=t.samples[o];r.pts=To(r.pts-s.baseTime*n/s.timescale,e*n)/n,r.dts=To(r.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Ao(t,e,s){const i=t.samples.length;if(!i)return;const r=t.inputTimeScale;for(let a=0;a<i;a++){const i=t.samples[a];i.pts=To(i.pts-s.baseTime*r/s.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function Lo(t,e,s=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(s?t.duration:0))/t.timescale:e}function Io(t,e,s){const i=t.codec;return i&&i.length>4?i:e===Q.AUDIO?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?Xr(i,!1):(s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}function bo(t){return"then"in t&&t.then instanceof Function}function Ro(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!ko(t[s].attrs,e[s].attrs))return!1;return!0}function ko(t,e,s){const i=t["STABLE-RENDITION-ID"];return i&&!s?i===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>t[s]!==e[s])}function Do(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}function wo(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function Po(t){return"audio"===t?1:0}function _o(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}function Co(t,e,s){return _o("serialize",t,e,s)}function xo(t){if(!1===ArrayBuffer.isView(t))throw Co(t,hs);return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Mo(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw Co(t,cs);return t.toString()}function Oo(t,e){if(t<0)return-Oo(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)<Number.EPSILON){const e=Math.floor(t*s);return(e%2==0?e:e+1)/s}return Math.round(t*s)/s}function Fo(t){const e=Oo(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Co(t,us);const s=e.toString();return s.includes(".")?s:`${s}.0`}function $o(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Co(e,ms);return e}function No(t){switch(typeof t){case"number":if(!C(t))throw Co(t,ls);return Number.isInteger(t)?Mo(t):Fo(t);case"string":return function(t){if(gs.test(t))throw Co(t,fs);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return $o(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Co(t,ds);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Mo(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return xo(t);if(t instanceof os)return $o(t);default:throw Co(t,ls)}}function Uo(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Co(t,ps);return t}function Bo(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${Uo(t)}`:`;${Uo(t)}=${No(e)}`).join("")}function Go(t){return t instanceof ns?`${No(t.value)}${Bo(t.params)}`:No(t)}function Ko(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw Co(t,as);const s=t instanceof Map?t.entries():Object.entries(t),i=(null==e?void 0:e.whitespace)?" ":"";return Array.from(s).map(([t,e])=>{e instanceof ns==0&&(e=new ns(e));let s=Uo(t);var i;return!0===e.value?s+=Bo(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(Go).join(" ")})${Bo(i.params)}`:s+=Go(e)),s}).join(`,${i}`)}function Vo(t,e){return Ko(t,e)}function Ho(t,e){const s={};if(!t)return s;const i=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var s;return null===(s=n[e])||void 0===s||s.forEach(s=>t[s]=e),t},{})):{};var n;return i.reduce((e,s)=>{var i;const n=Ss[s]||r[s]||As.REQUEST;return(null!==(i=e[n])&&void 0!==i?i:e[n]={})[s]=t[s],e},s)}function Wo(t){return Cs.test(t)}function Yo(t){return Ps.includes(t)||_s.includes(t)||Wo(t)}function jo(t){return Ps.includes(t)||xs.includes(t)||Wo(t)}function qo(t){return Ps.includes(t)||xs.includes(t)||Ms.includes(t)||Wo(t)}function zo(t){return Os.includes(t)||Wo(t)}function Xo(t,e={}){const s={};if(null==t||"object"!=typeof t)return s;const i=e.version||t.v||1,r=e.reportingMode||Ds,n=1===i?zo:Fs[r];let a=Object.keys(t).filter(n);const o=e.filter;"function"==typeof o&&(a=a.filter(o));const l=r===ws||r===Ls;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const d=or({},ks,e.formatters),h={version:i,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(e=>{let r=t[e];const n=d[e];if("function"==typeof n&&(r=n(r,h)),"v"===e){if(1===i)return;r=i}"pr"==e&&1===r||(l&&"ts"===e&&!C(r)&&(r=Date.now()),function(t){return"number"==typeof t?C(t):null!=t&&""!==t&&!1!==t}(r)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(e)&&"string"==typeof r&&(r=new os(r)),s[e]=r))}),s}function Qo(t,e,s){return or(t,function(t,e={}){const s={};if(!t)return s;const i=Ho(Xo(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(i).reduce((t,[e,s])=>{const i=Vo(s,{whitespace:!1});return i&&(t[e]=i),t},s)}(e,s))}function Zo(t,e={}){if(!t)return"";const s=function(t,e={}){return t?Vo(Xo(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(s)}function Jo(t,e,s){const i=function(t,e={}){return t?`${$s}=${Zo(t,e)}`:""}(e,s);return i?Ns.test(t)?t.replace(Ns,i):`${t}${t.includes("?")?"&":"?"}${i}`:t}function tl(t,e,s,i){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=or({},t);return n.details=void 0,n.attrs=new Ut(n.attrs),n.url=n.attrs.URI=el(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n});t.push(...n)})}function el(t,e,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}function sl(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return mr(t.keyId)}function il(t,e){return t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId)?e.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(e.decryptdata)?e.keyStatus:void 0}function rl(t,e){const s="output-restricted"===t,i=s?F.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:F.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ks({type:O.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},s?"HDCP level output restricted":`key status changed to "${t}"`)}function nl(t,e){let s;try{s=new Event("addtrack")}catch(i){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function al(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Y.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(r){Y.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}"disabled"===s&&(t.mode=s)}function ol(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===s&&(t.mode=s)}function ll(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(e<=t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&r<s))return i;r=i+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e<r.length;e++)i&&!i(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function dl(t){const e=[];for(let s=0;s<t.length;s++){const i=t[s];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||e.push(t[s])}return e}function hl(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()}function cl(t,e,s){return`${t.identifier}-${s+1}-${hl(e)}`}function ul(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Ws)?e.start:e.start+e.duration}function fl(t,e,s){const i=new self.URL(t,s);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",e),i}function gl(t,e){for(;null!=(s=t.assetList[++e])&&s.error;)var s;return e}function ml(t){const e=t.timelineStart,s=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+s).toFixed(2)}]`}function pl(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}function vl(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function yl(t,e){return`[${t}] Advancing timeline position to ${e}`}function El(t,e,s){s.a=t,s.b=e}function Tl(t,e,s){return s.a===t&&s.b===e}function Sl(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}function Al(t,e,s,i){const r=i?t.split(i):[t];for(const n in r){if("string"!=typeof r[n])continue;const t=r[n].split(s);2===t.length&&e(t[0],t[1])}}function Ll(t,e,s){const i=t;function r(){const e=Sl(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new Ei;Al(t,function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",Si,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",Si,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Si,"end","left","right"])}},/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===Ti.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Si);let n=i.get("position","auto");"auto"===n&&50===Ti.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Il(t){return t.replace(/<br(?: \/)?>/gi,"\n")}function bl(t,e,s){return hl(t.toString())+hl(e.toString())+hl(s)}function Rl(t,e,s,i,r,n,a){const o=new Ai,l=gr(new Uint8Array(t)).trim().replace(Li,"\n").split("\n"),d=[],h=e?function(t,e=1){return po(t,Oe,1/e)}(e.baseTime,e.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(f-h)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:Ri(s,i,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,u=To(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=bl(t.startTime,t.endTime,m)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(d)},l.forEach(t=>{if(m){if(Ii(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach(t=>{Ii(t,"LOCAL:")?u=t.slice(6):Ii(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=bi(u)/1e3}catch(e){c=e}return}""===t&&(m=!1)}o.parse(t+"\n")}),o.flush()}function kl(t,e,s,i){const r=Rr(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>gr(t)),a=function(t,e,s=1,i=!1){return po(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach(t=>s(function(t,e){const s=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(i).reduce((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||i[e],t),{}),n="preserve"!==s.getAttribute("xml:space"),a=wl(Dl(s,"styling","style")),o=wl(Dl(s,"layout","region")),l=Dl(s,"body","[begin]");return[].map.call(l,t=>{const s=Pl(t,n);if(!s||!t.hasAttribute("begin"))return null;const i=xl(t.getAttribute("begin"),r),l=xl(t.getAttribute("dur"),r);let d=xl(t.getAttribute("end"),r);if(null===i)throw Cl(t);if(null===d){if(null===l)throw Cl(t);d=i+l}const h=new vi(i-e,d-e,s);h.id=bl(h.startTime,h.endTime,h.text);const c=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&s.hasOwnProperty(a)&&(r=s[a]),n.reduce((s,n)=>{const a=_l(e,i,n)||_l(t,i,n)||_l(r,i,n);return a&&(s[n]=a),s},{})}(o[t.getAttribute("region")],a[t.getAttribute("style")],a),{textAlign:u}=c;if(u){const t=Pi[u];t&&(h.lineAlign=t),h.align=u}return or(h,c),h}).filter(t=>null!==t)}(t,a)))}catch(o){i(o)}}function Dl(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function wl(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function Pl(t,e){return[].slice.call(t.childNodes).reduce((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?Pl(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function _l(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function Cl(t){return new Error(`Could not parse ttml timestamp ${t}`)}function xl(t,e){if(!t)return null;let s=Sl(t);return null===s&&(Di.test(t)?s=function(t,e){const s=Di.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):wi.test(t)&&(s=function(t,e){const s=wi.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}function Ml(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Ol(t,e){return!!t&&t.kind===Ml(e)&&Do(e,t)}function Fl(t,e,s,i){return Math.min(e,i)-Math.max(t,s)}function $l(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Oi.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(C(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}function Nl(t,e){return new self.Request(t.url,e)}function Ul(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Ul):Object.keys(t).reduce((e,s)=>(e[s]=Ul(t[s]),e),{}):t}function Bl(t,e){const s=t.loader;s!==Fi&&s!==Ui?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=Fi,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}function Gl(t,e){const s=Kl(t.main);if(s&&s.start<=e)return s;const i=Kl(t.audio);return i&&i.start<=e?i:null}function Kl(t){if(!t)return null;switch(t.state){case ee.IDLE:case ee.STOPPED:case ee.ENDED:case ee.ERROR:return null}return t.frag}function Vl(t,e){return e.getAppendedFrag(t,U.MAIN)||e.getPartialFragment(t)}function Hl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Wl(t,e,s,i,r){let n=new t(e,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new t(e,s,pt(r?dr({type:r},i):i))}return n}function Yl(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function jl(){return self.SourceBuffer||self.WebKitSourceBuffer}function ql(){if(!ur())return!1;const t=jl();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}function zl(t){if(t.keyFormat!==Ht.FAIRPLAY){const e=t.keyId;if(e)return mr(e)}return t.uri}function Xl(t){const{type:e}=t;switch(e){case N.AUDIO_TRACK:return U.AUDIO;case N.SUBTITLE_TRACK:return U.SUBTITLE;default:return U.MAIN}}function Ql(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}return t({n:function(t){return async e=>((_=new I.default({availableFonts:{"times new roman":ir(w)},workerUrl:await rr({workerUrl:k,wasmUrl:D}),fallbackFont:ir(P),video:e.template.$video,...t})).canvasParent.className="artplayer-plugin-ass",_.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=>{_.freeTrack(),_.setTrackByUrl(t),nr(!0)}),e.on("subtitle",t=>nr(t)),e.on("artplayer-plugin-ass:visible",t=>nr(t)),e.on("subtitleOffset",t=>_.timeOffset=t),e.on("destroy",()=>_.dispose()),{name:"artplayerPluginAss",instance:_})},r:sr}),{setters:[function(t){s=t.i,i=t.t},function(t){r=t.B}],execute:function(){if((n=document.createElement("style")).textContent="@media (max-width:440px){.art-control.art-control-previous-button,.art-control.art-control-next-button{display:none}}@media (max-width:360px){.art-control.art-control-time{display:none}}\n/*$vite$:1*/",document.head.appendChild(n),a='/*!\n * artplayer-plugin-danmuku.js v5.3.0\n * Github: https://github.com/zhw2590582/ArtPlayer\n * (c) 2017-2026 Harvey Zhao\n * Released under the MIT License.\n */\nfunction getDanmuTop({ target, visibles, clientWidth, clientHeight, marginBottom, marginTop, antiOverlap }) {\n const maxTop = clientHeight - marginBottom;\n const danmus = visibles.filter((item) => item.mode === target.mode && item.top <= maxTop).sort((prev, next) => prev.top - next.top);\n if (danmus.length === 0) {\n if (target.mode === 2) {\n return maxTop - target.height;\n } else {\n return marginTop;\n }\n }\n danmus.unshift({\n type: "top",\n top: 0,\n left: 0,\n right: 0,\n height: marginTop,\n width: clientWidth,\n speed: 0,\n distance: clientWidth\n });\n danmus.push({\n type: "bottom",\n top: maxTop,\n left: 0,\n right: 0,\n height: marginBottom,\n width: clientWidth,\n speed: 0,\n distance: clientWidth\n });\n if (target.mode === 2) {\n for (let index = danmus.length - 2; index >= 0; index -= 1) {\n const item = danmus[index];\n const prev = danmus[index + 1];\n const itemBottom = item.top + item.height;\n const diff = prev.top - itemBottom;\n if (diff >= target.height) {\n return prev.top - target.height;\n }\n }\n } else {\n for (let index = 1; index < danmus.length; index += 1) {\n const item = danmus[index];\n const prev = danmus[index - 1];\n const prevBottom = prev.top + prev.height;\n const diff = item.top - prevBottom;\n if (diff >= target.height) {\n return prevBottom;\n }\n }\n }\n const topMap = [];\n for (let index = 1; index < danmus.length - 1; index += 1) {\n const item = danmus[index];\n if (topMap.length) {\n const last = topMap[topMap.length - 1];\n if (last[0].top === item.top) {\n last.push(item);\n } else {\n topMap.push([item]);\n }\n } else {\n topMap.push([item]);\n }\n }\n if (antiOverlap) {\n switch (target.mode) {\n case 0: {\n const result = topMap.find((list) => {\n return list.every((danmu) => {\n if (clientWidth < danmu.distance)\n return false;\n if (target.speed < danmu.speed)\n return true;\n const overlapTime = danmu.right / (target.speed - danmu.speed);\n if (overlapTime > danmu.time)\n return true;\n return false;\n });\n });\n return result && result[0] ? result[0].top : void 0;\n }\n // 静止弹幕没有重叠问题\n case 1:\n case 2:\n return void 0;\n }\n } else {\n switch (target.mode) {\n case 0:\n topMap.sort((prev, next) => {\n const nextMinRight = Math.min(...next.map((item) => item.right));\n const prevMinRight = Math.min(...prev.map((item) => item.right));\n return nextMinRight * next.length - prevMinRight * prev.length;\n });\n break;\n case 1:\n case 2:\n topMap.sort((prev, next) => {\n const nextMaxWidth = Math.max(...next.map((item) => item.width));\n const prevMaxWidth = Math.max(...prev.map((item) => item.width));\n return prevMaxWidth * prev.length - nextMaxWidth * next.length;\n });\n break;\n }\n return topMap[0][0].top;\n }\n}\nonmessage = (event) => {\n const { data } = event;\n if (!data.id || !data.type)\n return;\n const fns = { getDanmuTop };\n const fn = fns[data.type];\n const result = fn(data);\n globalThis.postMessage({\n result,\n id: data.id\n });\n};\n',o="undefined"!=typeof self&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",a],{type:"text/javascript;charset=utf-8"}),l=class t{constructor(e,s){const{constructor:i,template:r}=e;this.utils=i.utils,this.validator=i.validator,this.$danmuku=r.$danmuku,this.$player=r.$player,this.art=e,this.queue=[],this.$refs=[],this.isStop=!1,this.isHide=!1,this.timer=null,this.index=0,this.option=t.option,this.states={wait:[],ready:[],emit:[],stop:[]},this.config(s,!0),this.worker=new tr,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),e.on("video:play",this.start),e.on("video:playing",this.start),e.on("video:pause",this.stop),e.on("video:waiting",this.stop),e.on("destroy",this.destroy),e.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'\n user-select: none;\n position: absolute;\n white-space: pre;\n pointer-events: none;\n perspective: 500px;\n display: inline-block;\n will-change: transform;\n font-weight: normal;\n line-height: 1.125;\n visibility: hidden;\n font-family: SimHei, "Microsoft JhengHei", Arial, Helvetica, sans-serif;\n 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;\n '}get isRotate(){return this.art.plugins?.autoOrientation?.state}get marginTop(){const{clamp:e}=this.utils,s=this.option.margin[0],{clientHeight:i}=this.$player;return"number"==typeof s?e(s,0,i):"string"==typeof s&&s.endsWith("%")?e(i*(Number.parseFloat(s)/100),0,i):t.option.margin[0]}get marginBottom(){const{clamp:e}=this.utils,s=this.option.margin[1],{clientHeight:i}=this.$player;return"number"==typeof s?e(s,0,i):"string"==typeof s&&s.endsWith("%")?e(i*(Number.parseFloat(s)/100),0,i):t.option.margin[1]}get fontSize(){const{clamp:e}=this.utils,{clientHeight:s}=this.$player,i=this.option.fontSize;if("number"==typeof i)return Math.round(e(i,12,s));if("string"==typeof i&&i.endsWith("%")){const t=Number.parseFloat(i)/100;return Math.round(e(s*t,12,s))}return t.option.fontSize}get $ref(){const e=this.$refs.pop()||document.createElement("div");return e.style.cssText=t.cssText,e.dataset.mode="",e.dataset.id="",e.className="",e}get readys(){const{currentTime:t}=this.art,e=[];return this.filter("ready",t=>e.push(t)),this.filter("wait",s=>{t+.1>=s.time&&s.time>=t-.1&&e.push(s)}),e}get visibles(){const t=[],{clientWidth:e}=this.$player,s=this.getLeft(this.$player);return this.filter("emit",i=>{const r=i.$ref.offsetTop,n=this.getLeft(i.$ref)-s,a=i.$ref.clientHeight,o=i.$ref.clientWidth,l=n+o,d=e-l,h=l/i.$restTime,c={};c.top=r,c.left=n,c.height=a,c.width=o,c.right=d,c.speed=h,c.distance=l,c.time=i.$restTime,c.mode=i.mode,t.push(c)}),t}get speed(){return this.option.synchronousPlayback&&this.art.playbackRate?this.option.speed/Number(this.art.playbackRate):this.option.speed}async load(t){const{errorHandle:e}=this.utils;let s=[];const i=t||this.option.danmuku;try{"function"==typeof i?s=await i():i instanceof Promise?s=await i:"string"==typeof i?s=await(r=i,new Promise(async t=>{const e=await(await fetch(r)).text();try{const s=Ji();s.onmessage=e=>{const{danmus:i,id:r}=e.data;r&&i&&(t(i),s.terminate())},s.postMessage({xml:e,id:Date.now()})}catch(s){console.error("Error parsing Bilibili Danmu:",s),t(Qi(e))}})):Array.isArray(i)&&(s=i),e(Array.isArray(s),"Danmuku need return an array as result"),void 0===t&&(this.reset(),this.queue=[],this.states={wait:[],ready:[],emit:[],stop:[]},this.$refs=[],this.$danmuku.textContent="");for(let t=0;t<s.length;t++){const e=s[t];await this.emit(e)}this.art.emit("artplayerPluginDanmuku:loaded",this.queue)}catch(n){throw this.art.emit("artplayerPluginDanmuku:error",n),n}var r;return this}async emit(t){const{clamp:e}=this.utils;if(this.validator(t,{id:"?string",text:"string",mode:"?number",color:"?string",time:"?number",border:"?boolean",style:"?object"}),!t.text.trim())return this;if(t.time?t.time=e(t.time,0,1/0):t.time=this.art.currentTime+.5,void 0===t.mode&&(t.mode=this.option.mode),void 0===t.style&&(t.style={}),void 0===t.color&&(t.color=this.option.color),![0,1,2].includes(t.mode))return this;if(!this.option.filter(t))return this;const s={...t,$state:"wait",$index:this.index++,$ref:null,$restTime:0,$lastStartTime:0};return this.setState(s,"wait"),this.queue.push(s),this}config(e,s=!1){const{clamp:i}=this.utils,{$controlsCenter:r}=this.art.template;return Object.keys(e).some(t=>JSON.stringify(this.option[t])!==JSON.stringify(e[t]))||s?(this.option=Object.assign({},t.option,this.option,e),this.validator(this.option,t.scheme),this.option.mode=i(this.option.mode,0,2),this.option.speed=i(this.option.speed,1,10),this.option.opacity=i(this.option.opacity,0,1),this.option.lockTime=i(this.option.lockTime,1,60),this.option.maxLength=i(this.option.maxLength,1,1e3),this.option.mount=this.option.mount||r,e.fontSize&&this.reset(),this.option.visible?this.show():this.hide(),this.art.emit("artplayerPluginDanmuku:config",this.option),this):this}getLeft(t){const e=t.getBoundingClientRect();return this.isRotate?e.top:e.left}postMessage(t={}){return new Promise(e=>{t.id=Date.now(),this.worker.postMessage(t),this.worker.onmessage=s=>{const{data:i}=s;i.id===t.id&&e(i)}})}filter(t,e){const s=this.states[t]||[];for(let i=0;i<s.length;i++)e(s[i]);return s}setState(t,e){this.states[t.$state]=this.states[t.$state].filter(e=>e!==t),t.$state=e,t.$ref&&(t.$ref.dataset.state=e),this.states[e].push(t)}makeWait(e){this.setState(e,"wait"),e.$ref&&(e.$ref.style.cssText=t.cssText,e.$ref.style.visibility="hidden",e.$ref.style.marginLeft="0px",e.$ref.style.transform="translateX(0px)",e.$ref.style.transition="transform 0s linear 0s",this.$refs.push(e.$ref),e.$ref=null)}update(){const{setStyles:t}=this.utils;return this.timer=window.requestAnimationFrame(async()=>{if(this.art.playing&&!this.isHide){this.filter("emit",t=>{const e=(Date.now()-t.$lastStartTime)/1e3;t.$restTime-=e,t.$lastStartTime=Date.now(),t.$restTime<=0&&this.makeWait(t)});const e=this.readys;for(let s=0;s<e.length;s++){const i=e[s];if(await this.option.beforeVisible(i)){const{clientWidth:e,clientHeight:s}=this.$player;i.$ref=this.$ref,i.$ref.textContent=i.text,this.$danmuku.appendChild(i.$ref),i.$ref.style.opacity=this.option.opacity,i.$ref.style.fontSize=`${this.fontSize}px`,i.$ref.style.color=i.color,i.$ref.style.border=i.border?`1px solid ${i.color}`:null,i.$ref.style.backgroundColor=i.border?"rgb(0 0 0 / 50%)":null,t(i.$ref,i.style),i.$lastStartTime=Date.now(),i.$restTime=this.speed;const r=e+i.$ref.clientWidth,{result:n}=await this.postMessage({type:"getDanmuTop",target:{mode:i.mode,height:i.$ref.clientHeight,speed:r/i.$restTime},visibles:this.visibles,antiOverlap:this.option.antiOverlap,clientWidth:e,clientHeight:s,marginBottom:this.marginBottom,marginTop:this.marginTop});if(i.$ref)if(this.isStop||void 0===n)this.setState(i,"ready"),this.$refs.push(i.$ref),i.$ref=null;else{switch(this.setState(i,"emit"),i.$ref.style.top=`${n}px`,i.$ref.style.visibility="visible",i.$ref.dataset.mode=i.mode,i.$ref.dataset.id=i.id||"",i.mode){case 0:i.$ref.style.left=`${e}px`,i.$ref.style.marginLeft="0px",i.$ref.style.transform=`translateX(${-r}px)`,i.$ref.style.transition=`transform ${i.$restTime}s linear 0s`;break;case 1:case 2:i.$ref.style.left="50%",i.$ref.style.marginLeft=`-${i.$ref.clientWidth/2}px`}this.art.emit("artplayerPluginDanmuku:visible",i)}}}}this.isStop||this.update()}),this}resize(){const{clientWidth:t}=this.$player;this.filter("stop",e=>{0===e.mode&&(e.$ref.style.left=`${t}px`)}),this.filter("emit",e=>{switch(e.$lastStartTime=Date.now(),e.mode){case 0:{const s=t+e.$ref.clientWidth;e.$ref.style.left=`${t}px`,e.$ref.style.transform=`translateX(${-s}px)`,e.$ref.style.transition=`transform ${e.$restTime}s linear 0s`;break}}})}continue(){const{clientWidth:t}=this.$player;return this.filter("stop",e=>{switch(this.setState(e,"emit"),e.$lastStartTime=Date.now(),e.mode){case 0:{const s=t+e.$ref.clientWidth;e.$ref.style.transform=`translateX(${-s}px)`,e.$ref.style.transition=`transform ${e.$restTime}s linear 0s`;break}}}),this}suspend(){const{clientWidth:t}=this.$player;return this.filter("emit",e=>{switch(this.setState(e,"stop"),e.mode){case 0:{const s=t-(this.getLeft(e.$ref)-this.getLeft(this.$player));e.$ref.style.transform=`translateX(${-s}px)`,e.$ref.style.transition="transform 0s linear 0s";break}}}),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(t=>this.makeWait(t)),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")}},d={map:(t,e,s,i,r)=>(t-e)*(r-i)/(s-e)+i,range(t,e,s){const i=Math.round(t/s)*s;return Array.from({length:Math.floor((e-t)/s)},(t,e)=>e*s+i)}},h='<svg class="apd-icon apd-check-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',c='<svg class="apd-icon apd-check-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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"></path></svg>',u='<svg class="apd-icon apd-config-icon" xmlns:xlink="http://www.w3.org/1999/xlink" 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.363c1.903.094 3.317.141 5.513.141a.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.09-.002.056-.004.112-.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-.305c-.228-.501-.5-.959-.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"></path></svg>',f='<svg class="apd-icon apd-mode-0-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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"></path></svg>',g='<svg class="apd-icon apd-mode-0-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',m='<svg class="apd-icon apd-mode-1-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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"></path></svg>',p='<svg class="apd-icon apd-mode-1-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',v='<svg class="apd-icon apd-mode-2-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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"></path></svg>',y='<svg class="apd-icon apd-mode-2-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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="#FFFFFF"></path></svg>',E='<svg class="apd-icon apd-toggle-off" xmlns:xlink="http://www.w3.org/1999/xlink" 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.813-2.444-.087-4.466-.13-6.064-.131-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.975c-2.196 0-3.61-.047-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"></path></svg>',T='<svg class="apd-icon apd-toggle-on" xmlns:xlink="http://www.w3.org/1999/xlink" 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><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.005c.407.315 1 .27 1.354-.124l5.81-6.505.08-.102.005-.008a1 1 0 0 0-.166-1.295Z" clip-rule="evenodd"></path></svg>',S='<svg class="apd-icon apd-style-icon" xmlns:xlink="http://www.w3.org/1999/xlink" 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"></path></svg>',A=class{constructor(t,e){this.art=t,this.danmuku=e,this.utils=t.constructor.utils;const{setStyle:s}=this.utils,{$controlsCenter:i}=t.template;s(i,"display","flex"),this.template={$controlsCenter:i,$mount:i,$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),t.on("resize",()=>this.resize()),t.on("fullscreen",t=>this.onFullscreen(t)),t.on("fullscreenWeb",t=>this.onFullscreen(t)),t.proxy(this.template.$config,"mouseenter",()=>{this.onMouseEnter({$control:this.template.$config,$panel:this.template.$configPanel})}),t.proxy(this.template.$style,"mouseenter",()=>{this.onMouseEnter({$control:this.template.$style,$panel:this.template.$stylePanel})})}static get icons(){return{$on:T,$off:E,$config:u,$style:S,$mode_0_off:f,$mode_0_on:g,$mode_1_off:m,$mode_1_on:p,$mode_2_off:v,$mode_2_on:y,$check_on:c,$check_off:h}}get option(){return this.danmuku.option}get outside(){return this.template.$mount!==this.template.$controlsCenter}get TEMPLATE(){const{option:t}=this;return`\n <div class="apd-toggle">\n ${T}${E}\n </div>\n <div class="apd-config">\n ${u}\n <div class="apd-config-panel">\n <div class="apd-config-panel-inner">\n <div class="apd-config-mode">\n 按类型屏蔽\n <div class="apd-modes">\n <div data-mode="0" class="apd-mode">\n ${f}${g}\n <div>滚动</div>\n </div>\n <div data-mode="1" class="apd-mode">\n ${m}${p}\n <div>顶部</div>\n </div>\n <div data-mode="2" class="apd-mode">\n ${v}${y}\n <div>底部</div>\n </div>\n </div>\n </div>\n <div class="apd-config-other">\n <div class="apd-other apd-anti-overlap">\n ${c}${h}\n 防止弹幕重叠\n </div>\n <div class="apd-other apd-sync-video">\n ${c}${h}\n 同步视频速度\n </div>\n </div>\n <div class="apd-config-slider apd-config-opacity">\n 不透明度\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n <div class="apd-config-slider apd-config-margin">\n 显示区域\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n <div class="apd-config-slider apd-config-fontSize">\n 弹幕字号\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n <div class="apd-config-slider apd-config-speed">\n 弹幕速度\n <div class="apd-slider"></div>\n <div class="apd-value">未知</div>\n </div>\n </div>\n </div>\n </div>\n <div class="apd-emitter">\n <div class="apd-style">\n ${S}\n <div class="apd-style-panel">\n <div class="apd-style-panel-inner">\n <div class="apd-style-mode">\n 模式\n <div class="apd-modes">\n <div data-mode="0" class="apd-mode">\n ${g}\n <div>滚动</div>\n </div>\n <div data-mode="1" class="apd-mode">\n ${p}\n <div>顶部</div>\n </div>\n <div data-mode="2" class="apd-mode">\n ${y}\n <div>底部</div>\n </div>\n </div>\n </div>\n <div class="apd-style-color">\n 颜色\n <div class="apd-colors">\n ${this.COLOR.map(t=>`<div data-color="${t}" class="apd-color" style="background-color: ${t}"></div>`).join("")}\n </div>\n </div>\n </div>\n </div>\n </div>\n <input class="apd-input" placeholder="发个友善的弹幕见证当下" autocomplete="off" maxLength="${t.maxLength}" />\n <div class="apd-send">发送</div>\n </div>\n `}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(t){const{query:e}=this.utils,{$danmuku:s}=this.template;return e(t,s)}append(t,e){const{append:s}=this.utils;[...t.children].includes(e)||s(t,e)}setData(t,e){const{$player:s}=this.art.template,{$mount:i}=this.template;s.dataset[t]=e,this.outside&&(i.dataset[t]=e)}createTemplate(){const{createElement:t,tooltip:e}=this.utils,s=t("div");s.className="artplayer-plugin-danmuku",s.innerHTML=this.TEMPLATE,this.template.$danmuku=s,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");const{$toggle:i}=this.template;this.art.on("artplayerPluginDanmuku:show",()=>{e(i,"关闭弹幕")}),this.art.on("artplayerPluginDanmuku:hide",()=>{e(i,"打开弹幕")})}createEvents(){const{$toggle:t,$configModes:e,$styleModes:s,$colors:i,$antiOverlap:r,$syncVideo:n,$send:a,$input:o}=this.template;this.art.proxy(t,"click",()=>{this.danmuku.config({visible:!this.option.visible}),this.reset()}),this.art.proxy(e,"click",t=>{const e=t.target.closest(".apd-mode");if(!e)return;const s=Number(e.dataset.mode);this.option.modes.includes(s)?this.danmuku.config({modes:this.option.modes.filter(t=>t!==s)}):this.danmuku.config({modes:[...this.option.modes,s]}),this.reset()}),this.art.proxy(r,"click",()=>{this.danmuku.config({antiOverlap:!this.option.antiOverlap}),this.reset()}),this.art.proxy(n,"click",()=>{this.danmuku.config({synchronousPlayback:!this.option.synchronousPlayback}),this.reset()}),this.art.proxy(s,"click",t=>{const e=t.target.closest(".apd-mode");if(!e)return;const s=Number(e.dataset.mode);this.danmuku.config({mode:s}),this.reset()}),this.art.proxy(i,"click",t=>{const e=t.target.closest(".apd-color");e&&(this.danmuku.config({color:e.dataset.color}),this.reset())}),this.art.proxy(a,"click",()=>this.emit()),this.art.proxy(o,"keypress",t=>{"Enter"===t.key&&(t.preventDefault(),this.emit())})}createSliders(){this.slider.opacity=this.createSlider({...this.OPACITY,container:this.template.$opacitySlider,findIndex:()=>Math.round(100*this.option.opacity),onChange:t=>{const{$opacityValue:e}=this.template;e.textContent=`${t}%`,this.danmuku.config({opacity:t/100})}}),this.slider.margin=this.createSlider({...this.MARGIN,container:this.template.$marginSlider,findIndex:()=>this.MARGIN.steps.findIndex(t=>t.value[0]===this.option.margin[0]&&t.value[1]===this.option.margin[1]),onChange:t=>{const e=this.MARGIN.steps[t];if(!e)return;const{$marginValue:s}=this.template;s.textContent=e.name,this.danmuku.config({margin:e.value})}}),this.slider.fontSize=this.createSlider({...this.FONT_SIZE,container:this.template.$fontSizeSlider,findIndex:()=>this.danmuku.fontSize,onChange:t=>{const{$fontSizeValue:e}=this.template;e.textContent=`${t}px`,t!==this.danmuku.fontSize&&this.danmuku.config({fontSize:t})}}),this.slider.speed=this.createSlider({...this.SPEED,container:this.template.$speedSlider,findIndex:()=>this.SPEED.steps.findIndex(t=>t.value===this.option.speed),onChange:t=>{const e=this.SPEED.steps[t];if(!e)return;const{$speedValue:s}=this.template;s.textContent=e.name,this.danmuku.config({speed:e.value})}})}createSlider({min:t,max:e,container:s,findIndex:i,onChange:r,steps:n=[]}){const{query:a,clamp:o,setStyle:l}=this.utils;l(s,"touch-action","none"),s.innerHTML=`\n <div class="apd-slider-line">\n <div class="apd-slider-points">\n ${n.map(()=>'<div class="apd-slider-point"></div>').join("")}\n </div>\n <div class="apd-slider-progress"></div>\n </div>\n <div class="apd-slider-dot"></div>\n <div class="apd-slider-steps">\n ${n.map(t=>t.hide?"":`<div class="apd-slider-step">${t.name}</div>`).join("")}\n </div>\n `;const d=a(".apd-slider-dot",s),h=a(".apd-slider-progress",s);let c=!1;function u(s=i()){if(s<t||s>e)return;const a=(s-t)/(e-t);d.style.left=100*a+"%",0===n.length&&(h.style.width=d.style.left),r(s)}function f(i){const{top:r,height:n,left:a,width:l}=s.getBoundingClientRect();if(this.art.isRotate){const s=o(i.clientY-r,0,n);u(Math.round(s/n*(e-t)+t))}else{const s=o(i.clientX-a,0,l);u(Math.round(s/l*(e-t)+t))}}return this.art.proxy(s,"click",t=>{f.call(this,t)}),this.art.proxy(s,"pointerdown",t=>{c=0===t.button}),this.art.on("document:pointermove",t=>{c&&f.call(this,t)}),this.art.on("document:pointerup",t=>{c&&(c=!1,f.call(this,t))}),{reset:u}}onFullscreen(t){const{$danmuku:e,$controlsCenter:s,$mount:i}=this.template;this.outside?t?this.append(s,e):this.append(i,e):this.append(s,e)}onMouseEnter({$control:t,$panel:e}){const{$player:s}=this.art.template,i=t.getBoundingClientRect(),r=e.getBoundingClientRect(),n=s.getBoundingClientRect(),a=r.width/2-i.width/2,o=n.left-(i.left-a),l=i.right+a-n.right;e.style.left=o>0?`${-a+o}px`:l>0?-a-l+"px":-a+"px"}async emit(){const{$input:t}=this.template,e=t.value.trim();if(!e.length)return;if(this.isLock)return;if(this.emitting)return;const s={text:e,mode:this.option.mode,color:this.option.color,time:this.art.currentTime};try{this.emitting=!0;const e=await this.option.beforeEmit(s);if(this.emitting=!1,!0!==e)return;s.border=!0,delete s.time,this.danmuku.emit(s),t.value="",this.lock()}catch(i){console.error("Error emitting danmuku:",i),this.emitting=!1}}lock(){const{addClass:t}=this.utils,{$send:e}=this.template;this.isLock=!0;let s=this.option.lockTime;e.textContent=s,t(e,"apd-lock");const i=()=>{this.timer=setTimeout(()=>{0===s?this.unlock():(s-=1,e.textContent=s,i())},1e3)};i()}unlock(){const{removeClass:t}=this.utils,{$send:e}=this.template;clearTimeout(this.timer),this.isLock=!1,e.textContent="发送",t(e,"apd-lock")}resize(){if(this.outside)return;if(this.art.fullscreen)return;if(this.art.fullscreenWeb)return;const{$player:t,$controlsCenter:e}=this.art.template,{$danmuku:s}=this.template;this.art.width<this.option.width?this.append(t,s):this.append(e,s)}reset(){const{inverseClass:t,tooltip:e}=this.utils,{$toggle:s,$colors:i}=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);const r=i.children,n=Array.from(r).find(t=>t.dataset.color===this.option.color.toUpperCase());n&&t(n,"apd-active"),e(s,this.option.visible?"关闭弹幕":"打开弹幕"),this.resize()}mount(t){const{errorHandle:e}=this.utils,s="string"==typeof t?document.querySelector(t):t;e(s,`Can not find the mount point: ${t}`),this.append(s,this.template.$danmuku),this.template.$mount=s,this.reset()}},"undefined"!=typeof document){const t="artplayer-plugin-danmuku";let e=document.getElementById(t);e||(e=document.createElement("style"),e.id=t,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{document.head.appendChild(e)}):(document.head||document.documentElement).appendChild(e)),e.textContent=".artplayer-plugin-danmuku {\n display: flex;\n position: relative;\n z-index: 99;\n align-items: center;\n justify-content: center;\n font-size: 12px;\n height: 32px;\n width: 100%;\n color: #fff;\n font-weight: 300;\n flex-shrink: 0;\n gap: 10px;\n}\n.artplayer-plugin-danmuku .apd-icon {\n cursor: pointer;\n opacity: 0.75;\n transition: all 0.2s ease;\n fill: #fff;\n}\n.artplayer-plugin-danmuku .apd-icon:hover {\n opacity: 1;\n}\n.artplayer-plugin-danmuku .apd-config {\n display: flex;\n position: relative;\n}\n.artplayer-plugin-danmuku .apd-config .apd-config-panel {\n position: absolute;\n bottom: 24px;\n left: 0;\n width: 320px;\n padding: 10px;\n opacity: 0;\n pointer-events: none;\n}\n.artplayer-plugin-danmuku .apd-config .apd-config-panel .apd-config-panel-inner {\n width: 100%;\n border-radius: 3px;\n background-color: rgba(0, 0, 0, 0.85);\n padding: 10px;\n}\n.artplayer-plugin-danmuku .apd-config:hover .apd-config-panel {\n opacity: 100;\n pointer-events: all;\n}\n.artplayer-plugin-danmuku .apd-config-mode,\n.artplayer-plugin-danmuku .apd-config-slider,\n.artplayer-plugin-danmuku .apd-config-other,\n.artplayer-plugin-danmuku .apd-style-mode {\n margin-bottom: 15px;\n}\n.artplayer-plugin-danmuku .apd-modes {\n display: flex;\n align-items: center;\n margin-top: 5px;\n gap: 20px;\n}\n.artplayer-plugin-danmuku .apd-modes .apd-mode {\n cursor: pointer;\n text-align: center;\n}\n.artplayer-plugin-danmuku .apd-modes .apd-mode:hover {\n color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-config-slider {\n display: flex;\n align-items: center;\n gap: 12px;\n}\n.artplayer-plugin-danmuku .apd-config-slider .apd-value {\n width: 32px;\n text-align: right;\n}\n.artplayer-plugin-danmuku .apd-slider {\n position: relative;\n flex: 1;\n display: flex;\n height: 20px;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-line {\n position: relative;\n height: 2px;\n width: 100%;\n overflow: hidden;\n border-radius: 3px;\n background-color: rgba(255, 255, 255, 0.25);\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-points {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: space-between;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-points .apd-slider-point {\n width: 2px;\n height: 2px;\n border-radius: 50%;\n background-color: rgba(255, 255, 255, 0.5);\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-progress {\n width: 0%;\n height: 100%;\n background-color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-dot {\n position: absolute;\n transform: translateX(-6px);\n left: 0%;\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background-color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-steps {\n display: flex;\n align-items: center;\n justify-content: space-between;\n position: absolute;\n bottom: -12px;\n width: calc(100% + 32px);\n color: #777;\n}\n.artplayer-plugin-danmuku .apd-slider .apd-slider-steps .apd-slider-step {\n flex-shrink: 0;\n width: 36px;\n text-align: center;\n scale: 0.95;\n}\n.artplayer-plugin-danmuku .apd-config-other {\n display: flex;\n align-items: center;\n gap: 20px;\n}\n.artplayer-plugin-danmuku .apd-config-other .apd-check-off,\n.artplayer-plugin-danmuku .apd-config-other .apd-check-on {\n width: 16px;\n height: 16px;\n}\n.artplayer-plugin-danmuku .apd-config-other .apd-other {\n display: flex;\n align-items: center;\n cursor: pointer;\n gap: 2px;\n}\n.artplayer-plugin-danmuku .apd-config-other .apd-other:hover {\n color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-emitter {\n display: flex;\n flex: 1;\n align-items: center;\n height: 100%;\n background-color: rgba(255, 255, 255, 0.25);\n border-radius: 5px;\n}\n.artplayer-plugin-danmuku .apd-style {\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.artplayer-plugin-danmuku .apd-style .apd-style-panel {\n position: absolute;\n bottom: 24px;\n left: 0;\n width: 200px;\n padding: 10px;\n opacity: 0;\n pointer-events: none;\n}\n.artplayer-plugin-danmuku .apd-style .apd-style-panel .apd-style-panel-inner {\n width: 100%;\n border-radius: 3px;\n background-color: rgba(0, 0, 0, 0.85);\n padding: 10px;\n}\n.artplayer-plugin-danmuku .apd-style:hover .apd-style-panel {\n opacity: 100;\n pointer-events: all;\n}\n.artplayer-plugin-danmuku .apd-colors {\n display: flex;\n flex-wrap: wrap;\n margin-top: 5px;\n gap: 8px;\n}\n.artplayer-plugin-danmuku .apd-colors .apd-color {\n width: 16px;\n height: 16px;\n border-radius: 2px;\n cursor: pointer;\n}\n.artplayer-plugin-danmuku .apd-colors .apd-color.apd-active {\n border: 1px solid black;\n box-shadow: 0 0 0 1px #fff;\n}\n.artplayer-plugin-danmuku .apd-input {\n outline: none;\n height: 100%;\n flex: 1;\n min-width: 0;\n width: auto;\n border: none;\n line-height: 1;\n color: #fff;\n background-color: transparent;\n}\n.artplayer-plugin-danmuku .apd-input::placeholder {\n color: rgba(255, 255, 255, 0.5);\n}\n.artplayer-plugin-danmuku .apd-send {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 60px;\n flex-shrink: 0;\n cursor: pointer;\n text-shadow: none;\n border-top-right-radius: 5px;\n border-bottom-right-radius: 5px;\n background-color: #00a1d6;\n}\n.artplayer-plugin-danmuku .apd-send.apd-lock {\n cursor: not-allowed;\n color: #666;\n background-color: #e7e7e7;\n}\n.art-controls-center .apd-emitter {\n width: 260px;\n flex: none;\n}\n.art-fullscreen .artplayer-plugin-danmuku,\n.art-fullscreen-web .artplayer-plugin-danmuku {\n height: 38px;\n gap: 16px;\n}\n.art-fullscreen .artplayer-plugin-danmuku .apd-config-icon,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-config-icon,\n.art-fullscreen .artplayer-plugin-danmuku .apd-toggle-off,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-toggle-off,\n.art-fullscreen .artplayer-plugin-danmuku .apd-toggle-on,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-toggle-on {\n width: 28px;\n height: 28px;\n}\n.art-fullscreen .artplayer-plugin-danmuku .apd-emitter,\n.art-fullscreen-web .artplayer-plugin-danmuku .apd-emitter {\n width: 400px;\n flex: none;\n}\n.art-video-player > .artplayer-plugin-danmuku {\n position: absolute;\n left: 0;\n right: 0;\n bottom: -40px;\n padding: 0 10px;\n}\n.art-video-player:has(> .artplayer-plugin-danmuku) {\n margin-bottom: 40px;\n}\n[data-danmuku-emitter='false'] .apd-emitter {\n display: none !important;\n}\n[data-danmuku-emitter='false'] .art-controls-center .artplayer-plugin-danmuku {\n justify-content: flex-end;\n gap: 18px;\n}\n[data-danmuku-emitter='false'].art-fullscreen .art-controls-center .artplayer-plugin-danmuku,\n[data-danmuku-emitter='false'].art-fullscreen-web .art-controls-center .artplayer-plugin-danmuku {\n gap: 24px;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-icon {\n fill: #333;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-emitter {\n background-color: #f1f2f3;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-input {\n color: #000;\n}\n[data-danmuku-theme='light'] > .artplayer-plugin-danmuku .apd-input::placeholder {\n color: rgba(0, 0, 0, 0.3);\n}\n[data-danmuku-visible='false'] .apd-toggle-off {\n display: block;\n}\n[data-danmuku-visible='false'] .apd-toggle-on {\n display: none;\n}\n[data-danmuku-visible='true'] .apd-toggle-off {\n display: none;\n}\n[data-danmuku-visible='true'] .apd-toggle-on {\n display: block;\n}\n[data-danmuku-anti-overlap='false'] .apd-anti-overlap .apd-check-on {\n display: none;\n}\n[data-danmuku-anti-overlap='false'] .apd-anti-overlap .apd-check-off {\n display: block;\n}\n[data-danmuku-anti-overlap='true'] .apd-anti-overlap .apd-check-on {\n display: block;\n}\n[data-danmuku-anti-overlap='true'] .apd-anti-overlap .apd-check-off {\n display: none;\n}\n[data-danmuku-sync-video='false'] .apd-sync-video .apd-check-on {\n display: none;\n}\n[data-danmuku-sync-video='false'] .apd-sync-video .apd-check-off {\n display: block;\n}\n[data-danmuku-sync-video='true'] .apd-sync-video .apd-check-on {\n display: block;\n}\n[data-danmuku-sync-video='true'] .apd-sync-video .apd-check-off {\n display: none;\n}\n[data-danmuku-mode0='false'] .apd-config-mode .apd-mode-0-off {\n display: block;\n}\n[data-danmuku-mode0='false'] .apd-config-mode .apd-mode-0-on {\n display: none;\n}\n[data-danmuku-mode0='false'] .art-danmuku [data-mode='0'] {\n opacity: 0 !important;\n}\n[data-danmuku-mode0='true'] .apd-config-mode .apd-mode-0-off {\n display: none;\n}\n[data-danmuku-mode0='true'] .apd-config-mode .apd-mode-0-on {\n display: block;\n}\n[data-danmuku-mode='0'] .apd-style-mode [data-mode='0'] {\n color: #00a1d6;\n}\n[data-danmuku-mode='0'] .apd-style-mode [data-mode='0'] path {\n fill: #00a1d6;\n}\n[data-danmuku-mode1='false'] .apd-config-mode .apd-mode-1-off {\n display: block;\n}\n[data-danmuku-mode1='false'] .apd-config-mode .apd-mode-1-on {\n display: none;\n}\n[data-danmuku-mode1='false'] .art-danmuku [data-mode='1'] {\n opacity: 0 !important;\n}\n[data-danmuku-mode1='true'] .apd-config-mode .apd-mode-1-off {\n display: none;\n}\n[data-danmuku-mode1='true'] .apd-config-mode .apd-mode-1-on {\n display: block;\n}\n[data-danmuku-mode='1'] .apd-style-mode [data-mode='1'] {\n color: #00a1d6;\n}\n[data-danmuku-mode='1'] .apd-style-mode [data-mode='1'] path {\n fill: #00a1d6;\n}\n[data-danmuku-mode2='false'] .apd-config-mode .apd-mode-2-off {\n display: block;\n}\n[data-danmuku-mode2='false'] .apd-config-mode .apd-mode-2-on {\n display: none;\n}\n[data-danmuku-mode2='false'] .art-danmuku [data-mode='2'] {\n opacity: 0 !important;\n}\n[data-danmuku-mode2='true'] .apd-config-mode .apd-mode-2-off {\n display: none;\n}\n[data-danmuku-mode2='true'] .apd-config-mode .apd-mode-2-on {\n display: block;\n}\n[data-danmuku-mode='2'] .apd-style-mode [data-mode='2'] {\n color: #00a1d6;\n}\n[data-danmuku-mode='2'] .apd-style-mode [data-mode='2'] path {\n fill: #00a1d6;\n}\n"}var e,Xi,Zi,er,ir,rr;sr.icons=A.icons,L=i((t,e)=>{"function"==typeof SubtitlesOctopusOnLoad&&SubtitlesOctopusOnLoad(),void 0!==t&&void 0!==e&&e.exports&&(t=e.exports=function(t){var e=!1;try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){const t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));t instanceof WebAssembly.Module&&(e=new WebAssembly.Instance(t)instanceof WebAssembly.Instance)}}catch(f){}console.log("WebAssembly support detected: "+(e?"yes":"no"));var s=this;function i(){s.setCurrentTime(s.video.currentTime+s.timeOffset)}function r(){s.setIsPaused(!1,s.video.currentTime+s.timeOffset)}function n(){s.setIsPaused(!0,s.video.currentTime+s.timeOffset)}function a(){s.video.removeEventListener("timeupdate",i,!1)}function o(){s.video.addEventListener("timeupdate",i,!1);var t=s.video.currentTime+s.timeOffset;s.setCurrentTime(t)}function l(){s.setRate(s.video.playbackRate)}function d(){s.setIsPaused(!0,s.video.currentTime+s.timeOffset)}function h(t){t.target.removeEventListener(t.type,h,!1),s.resize()}function c(){var t=s.renderFramesData,e=performance.now();s.ctx.clearRect(0,0,s.canvas.width,s.canvas.height);for(var i=0;i<t.canvases.length;i++){var r=t.canvases[i];s.bufferCanvas.width=r.w,s.bufferCanvas.height=r.h;var n=new Uint8ClampedArray(r.buffer);if(s.hasAlphaBug)for(var a=3;a<n.length;a+=4)n[a]=n[a]>=1?n[a]:1;var o=new ImageData(n,r.w,r.h);s.bufferCanvasCtx.putImageData(o,0,0),s.ctx.drawImage(s.bufferCanvas,r.x,r.y)}if(s.debug){var l=Math.round(performance.now()-e),d=t.blendTime;void 0!==d?console.log("render: "+Math.round(t.spentTime-d)+" ms, blend: "+Math.round(d)+" ms, draw: "+l+" ms; TOTAL="+Math.round(t.spentTime+l)+" ms"):console.log(Math.round(t.spentTime)+" ms (+ "+l+" ms draw)"),s.renderStart=performance.now()}}function u(){var t=s.renderFramesData,e=performance.now();s.ctx.clearRect(0,0,s.canvas.width,s.canvas.height);for(var i=0;i<t.bitmaps.length;i++){var r=t.bitmaps[i];s.ctx.drawImage(r.bitmap,r.x,r.y)}if(s.debug){var n=Math.round(performance.now()-e);console.log(t.bitmaps.length+" bitmaps, libass: "+Math.round(t.libassTime)+"ms, decode: "+Math.round(t.decodeTime)+"ms, draw: "+n+"ms"),s.renderStart=performance.now()}}s.canvas=t.canvas,s.renderMode=t.renderMode||(t.lossyRender?"lossy":"wasm-blend"),s.libassMemoryLimit=t.libassMemoryLimit||0,s.libassGlyphLimit=t.libassGlyphLimit||0,s.targetFps=t.targetFps||24,s.prescaleFactor=t.prescaleFactor||1,s.prescaleHeightLimit=t.prescaleHeightLimit||1080,s.maxRenderHeight=t.maxRenderHeight||0,s.dropAllAnimations=t.dropAllAnimations||!1,s.isOurCanvas=!1,s.video=t.video,s.canvasParent=null,s.fonts=t.fonts||[],s.availableFonts=t.availableFonts||[],s.fallbackFont=t.fallbackFont||"default.woff2",s.lazyFileLoading=t.lazyFileLoading||!1,s.onReadyEvent=t.onReady,s.workerUrl=e?t.workerUrl||"subtitles-octopus-worker.js":t.legacyWorkerUrl||"subtitles-octopus-worker-legacy.js",s.subUrl=t.subUrl,s.subContent=t.subContent||null,s.onErrorEvent=t.onError,s.debug=t.debug||!1,s.lastRenderTime=0,s.pixelRatio=window.devicePixelRatio||1,s.timeOffset=t.timeOffset||0,s.hasAlphaBug=!1,function(){if("function"==typeof ImageData.prototype.constructor)try{return void new window.ImageData(new Uint8ClampedArray([0,0,0,0]),1,1)}catch(f){console.log("detected that ImageData is not constructable despite browser saying so")}var t=document.createElement("canvas").getContext("2d");window.ImageData=function(){var e=0;if(arguments[0]instanceof Uint8ClampedArray)var s=arguments[e++];var i=arguments[e++],r=arguments[e],n=t.createImageData(i,r);return s&&n.data.set(s),n}}(),s.workerError=function(t){if(console.error("Worker error: ",t),s.onErrorEvent&&s.onErrorEvent(t),!s.debug)throw s.dispose(),new Error("Worker error: "+t)},s.init=function(){window.Worker?(s.worker||(s.worker=new Worker(s.workerUrl),s.worker.addEventListener("message",s.onWorkerMessage),s.worker.addEventListener("error",s.workerError)),s.workerActive=!1,s.createCanvas(),s.setVideo(t.video),s.setSubUrl(t.subUrl),s.worker.postMessage({target:"worker-init",width:s.canvas.width,height:s.canvas.height,URL:document.URL,currentScript:s.workerUrl,preMain:!0,renderMode:s.renderMode,subUrl:s.subUrl,subContent:s.subContent,fonts:s.fonts,availableFonts:s.availableFonts,fallbackFont:s.fallbackFont,lazyFileLoading:s.lazyFileLoading,debug:s.debug,targetFps:s.targetFps,libassMemoryLimit:s.libassMemoryLimit,libassGlyphLimit:s.libassGlyphLimit,dropAllAnimations:s.dropAllAnimations})):s.workerError("worker not supported")},s.createCanvas=function(){s.canvas||(s.video?(s.isOurCanvas=!0,s.canvas=document.createElement("canvas"),s.canvas.className="libassjs-canvas",s.canvas.style.display="none",s.canvasParent=document.createElement("div"),s.canvasParent.className="libassjs-canvas-parent",s.canvasParent.appendChild(s.canvas),s.video.nextSibling?s.video.parentNode.insertBefore(s.canvasParent,s.video.nextSibling):s.video.parentNode.appendChild(s.canvasParent)):s.canvas||s.workerError("Don't know where to render: you should give video or canvas in options.")),s.ctx=s.canvas.getContext("2d"),s.bufferCanvas=document.createElement("canvas"),s.bufferCanvasCtx=s.bufferCanvas.getContext("2d"),s.bufferCanvas.width=1,s.bufferCanvas.height=1;var t=new Uint8ClampedArray([0,255,0,0]),e=new ImageData(t,1,1);s.bufferCanvasCtx.clearRect(0,0,1,1),s.ctx.clearRect(0,0,1,1);var i=s.ctx.getImageData(0,0,1,1).data;s.bufferCanvasCtx.putImageData(e,0,0),s.ctx.drawImage(s.bufferCanvas,0,0);var r=s.ctx.getImageData(0,0,1,1).data;s.hasAlphaBug=i[1]!=r[1],s.hasAlphaBug&&console.log("Detected a browser having issue with transparent pixels, applying workaround")},s.setVideo=function(t){s.video=t,s.video&&(s.video.addEventListener("timeupdate",i,!1),s.video.addEventListener("playing",r,!1),s.video.addEventListener("pause",n,!1),s.video.addEventListener("seeking",a,!1),s.video.addEventListener("seeked",o,!1),s.video.addEventListener("ratechange",l,!1),s.video.addEventListener("waiting",d,!1),document.addEventListener("fullscreenchange",s.resizeWithTimeout,!1),document.addEventListener("mozfullscreenchange",s.resizeWithTimeout,!1),document.addEventListener("webkitfullscreenchange",s.resizeWithTimeout,!1),document.addEventListener("msfullscreenchange",s.resizeWithTimeout,!1),window.addEventListener("resize",s.resizeWithTimeout,!1),"undefined"!=typeof ResizeObserver&&(s.ro=new ResizeObserver(s.resizeWithTimeout),s.ro.observe(s.video)),s.video.videoWidth>0?s.resize():s.video.addEventListener("loadedmetadata",h,!1))},s.getVideoPosition=function(){var t=s.video.videoWidth/s.video.videoHeight,e=s.video.offsetWidth,i=s.video.offsetHeight,r=e,n=i;return e/i>t?r=Math.floor(i*t):n=Math.floor(e/t),{width:r,height:n,x:(e-r)/2,y:(i-n)/2}},s.setSubUrl=function(t){s.subUrl=t},s.renderFrameData=null,s.workerActive=!1,s.frameId=0,s.onWorkerMessage=function(t){s.workerActive||(s.workerActive=!0,s.onReadyEvent&&s.onReadyEvent());var e=t.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":s.ctx=s.canvas.getContext(e.type,e.attributes);break;case"resize":s.resize(e.width,e.height);break;case"renderCanvas":s.lastRenderTime<e.time&&(s.lastRenderTime=e.time,s.renderFramesData=e,window.requestAnimationFrame(c));break;case"renderFastCanvas":s.lastRenderTime<e.time&&(s.lastRenderTime=e.time,s.renderFramesData=e,window.requestAnimationFrame(u));break;case"setObjectProperty":s.canvas[e.object][e.property]=e.value;break;default:throw"eh?"}break;case"tick":s.frameId=e.id,s.worker.postMessage({target:"tock",id:s.frameId});break;case"custom":if(!s.onCustomMessage)throw"Custom message received but client onCustomMessage not implemented.";s.onCustomMessage(t);break;case"setimmediate":s.worker.postMessage({target:"setimmediate"});break;case"get-events":case"get-styles":case"ready":break;default:throw"what? "+e.target}},s.resize=function(t,e,i,r){var n=null;if(i=i||0,r=r||0,(!t||!e)&&s.video){var a=function(t,e){var i=s.prescaleFactor<=0?1:s.prescaleFactor;if(e<=0||t<=0)t=0,e=0;else{var r=i<1?-1:1,n=e;r*n*i<=r*s.prescaleHeightLimit?n*=i:r*n<r*s.prescaleHeightLimit&&(n=s.prescaleHeightLimit),s.maxRenderHeight>0&&n>s.maxRenderHeight&&(n=s.maxRenderHeight),t*=n/e,e=n}return{width:t,height:e}}((n=s.getVideoPosition()).width*s.pixelRatio,n.height*s.pixelRatio);t=a.width,e=a.height;var o=s.canvasParent.getBoundingClientRect().top-s.video.getBoundingClientRect().top;i=n.y-o,r=n.x}t&&e?s.canvas.width==t&&s.canvas.height==e&&s.canvas.style.top==i&&s.canvas.style.left==r||(s.canvas.width=t,s.canvas.height=e,null!=n&&(s.canvasParent.style.position="relative",s.canvas.style.display="block",s.canvas.style.position="absolute",s.canvas.style.width=n.width+"px",s.canvas.style.height=n.height+"px",s.canvas.style.top=i+"px",s.canvas.style.left=r+"px",s.canvas.style.pointerEvents="none"),s.worker.postMessage({target:"canvas",width:s.canvas.width,height:s.canvas.height})):s.video||console.error("width or height is 0. You should specify width & height for resize.")},s.resizeWithTimeout=function(){s.resize(),setTimeout(s.resize,100)},s.runBenchmark=function(){s.worker.postMessage({target:"runBenchmark"})},s.customMessage=function(t,e){e=e||{},s.worker.postMessage({target:"custom",userData:t,preMain:e.preMain})},s.setCurrentTime=function(t){s.worker.postMessage({target:"video",currentTime:t})},s.setTrackByUrl=function(t){s.worker.postMessage({target:"set-track-by-url",url:t})},s.setTrack=function(t){s.worker.postMessage({target:"set-track",content:t})},s.freeTrack=function(t){s.worker.postMessage({target:"free-track"})},s.render=s.setCurrentTime,s.setIsPaused=function(t,e){s.worker.postMessage({target:"video",isPaused:t,currentTime:e})},s.setRate=function(t){s.worker.postMessage({target:"video",rate:t})},s.dispose=function(){s.worker.postMessage({target:"destroy"}),s.worker.terminate(),s.worker.removeEventListener("message",s.onWorkerMessage),s.worker.removeEventListener("error",s.workerError),s.workerActive=!1,s.worker=null,s.video&&(s.video.removeEventListener("timeupdate",i,!1),s.video.removeEventListener("playing",r,!1),s.video.removeEventListener("pause",n,!1),s.video.removeEventListener("seeking",a,!1),s.video.removeEventListener("seeked",o,!1),s.video.removeEventListener("ratechange",l,!1),s.video.removeEventListener("waiting",d,!1),s.video.removeEventListener("loadedmetadata",h,!1),document.removeEventListener("fullscreenchange",s.resizeWithTimeout,!1),document.removeEventListener("mozfullscreenchange",s.resizeWithTimeout,!1),document.removeEventListener("webkitfullscreenchange",s.resizeWithTimeout,!1),document.removeEventListener("msfullscreenchange",s.resizeWithTimeout,!1),window.removeEventListener("resize",s.resizeWithTimeout,!1),s.video.parentNode.removeChild(s.canvasParent),s.video=null),s.ro&&(s.ro.disconnect(),s.ro=null),s.onCustomMessage=null,s.onErrorEvent=null,s.onReadyEvent=null},s.fetchFromWorker=function(t,e,i){try{var r=t.target,n=setTimeout(function(){o(Error("Error: Timeout while try to fetch "+r))},5e3),a=function(t){t.data.target==r&&(e(t.data),s.worker.removeEventListener("message",a),s.worker.removeEventListener("error",o),clearTimeout(n))},o=function(t){i(t),s.worker.removeEventListener("message",a),s.worker.removeEventListener("error",o),clearTimeout(n)};s.worker.addEventListener("message",a),s.worker.addEventListener("error",o),s.worker.postMessage(t)}catch(l){i(l)}},s.createEvent=function(t){s.worker.postMessage({target:"create-event",event:t})},s.getEvents=function(t,e){s.fetchFromWorker({target:"get-events"},function(e){t(e.events)},e)},s.setEvent=function(t,e){s.worker.postMessage({target:"set-event",event:t,index:e})},s.removeEvent=function(t){s.worker.postMessage({target:"remove-event",index:t})},s.createStyle=function(t){s.worker.postMessage({target:"create-style",style:t})},s.getStyles=function(t,e){s.fetchFromWorker({target:"get-styles"},function(e){t(e.styles)},e)},s.setStyle=function(t,e){s.worker.postMessage({target:"set-style",style:t,index:e})},s.removeStyle=function(t){s.worker.postMessage({target:"remove-style",index:t})},s.init()})}),I=s(L(),1),({fontsPath:b,libAssPath:R}=r()),k=`${R()}/subtitles-octopus-worker.js`,D=`${R()}/subtitles-octopus-worker.wasm`,w=`${b()}/TimesNewRoman.ttf`,P=`${b()}/SourceHanSansCN-Bold.woff2`,_=null,C=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},x=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=M},M=Number.MAX_SAFE_INTEGER||9007199254740991,O=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),F=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),$=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({}),N={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},U={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},B=class{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}},G=class{constructor(t,e,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new B(t),this.fast_=new B(e),this.defaultTTFB_=i,this.ttfb_=new B(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new B(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new B(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new B(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},K=class{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${t}]:`;this.trace=V,this.debug=e.debug.bind(null,s),this.log=e.log.bind(null,s),this.warn=e.warn.bind(null,s),this.info=e.info.bind(null,s),this.error=e.error.bind(null,s)}},H={trace:V=function(){},debug:V,log:V,warn:V,info:V,error:V},W=hr(),Y=W,j={exports:{}},q||(q=1,e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,Xi=/^(?=([^\/?#]*))\1([^]*)$/,Zi=/(?:\/|^)\.(?=\/)/g,er=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,ir={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var i=ir.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=ir.normalizePath(i.path),ir.buildURLFromParts(i)}var r=ir.parseURL(e);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return s.alwaysNormalize?(r.path=ir.normalizePath(r.path),ir.buildURLFromParts(r)):e;var n=ir.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=Xi.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,d=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=ir.normalizePath(d)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=s.alwaysNormalize?ir.normalizePath(r.path):r.path),ir.buildURLFromParts(o)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(Zi,"");t.length!==(t=t.replace(er,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},j.exports=ir),z=j.exports,X=class{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}}},Q={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Z=class{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,Tr(this,"stats")}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Q.AUDIO]:null,[Q.VIDEO]:null,[Q.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new X),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=z.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Q.AUDIO]=null,t[Q.VIDEO]=null,t[Q.AUDIOVIDEO]=null}},J=class extends Z{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(C(t)&&C(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const s=this._decryptdata=e[t[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=C(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),s=t.length;if(s>1||1===s&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){C(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return yr(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var s;const i=e[t];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}},tt=class extends Z{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}},et=Math.pow(2,32)-1,st=[].push,it={video:1,audio:2,id3:3,text:4},rt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),nt={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}},at={},ot=/flac|opus|mp4a\.40\.34/i,lt={supported:!1,smooth:!1,powerEfficient:!1},dt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},ht=["NONE","TYPE-0","TYPE-1",null],ct=["SDR","PQ","HLG"],ut={No:"",Yes:"YES",v2:"v2"},ft=class{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}},gt=class{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const s=null==(e=t.supplemental)?void 0:e.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return dn(this._audioGroups,t)}hasSubtitleGroup(t){return dn(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}},mt=t=>{const e=new WeakSet;return(s,i)=>{if(t&&(i=t(s,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}},pt=(t,e)=>JSON.stringify(t,mt(e)),vt=class extends K{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:s,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,d=i?i.duration:s.duration,h=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,m=!!t||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=r.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(h<=Math.max(v,d/(2*y)*1e3))return;const E=p?p.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,A=this.getBwEstimate(),L=r.levels,I=L[u],b=Math.max(l.loaded,Math.round(d*(s.bitrate||I.averageBitrate)/8));let R=S?h-T:h;R<1&&S&&(R=Math.min(h,8*l.loaded/A));const k=S?1e3*l.loaded/R:0,D=v/1e3,w=k?(b-l.loaded)/k:8*b/A+D;if(w<=E)return;const P=k?8*k:A,_=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),x=this.hls.config.abrBandWidthUpFactor;let M,O=Number.POSITIVE_INFINITY;for(M=u-1;M>c;M--){const t=L[M].maxBitrate,e=!L[M].details||_;if(O=this.getTimeToLoadFrag(D,P,d*t,e),O<Math.min(E,d+D))break}if(O>=w)return;if(O>10*d)return;S?this.bwEstimator.sample(h-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(h);const F=L[M].maxBitrate;this.getBwEstimate()*x>F&&this.resetEstimator(F);const N=this.findBestLevel(F,c,M,0,E,1,1);N>-1&&(M=N),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${w.toFixed(3)} s\n Estimated load time for down switch fragment: ${O.toFixed(3)} s\n TTFB estimate: ${0|T} ms\n Current BW estimate: ${C(A)?0|A:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|F} bps`),r.nextLoadLevel=r.nextAutoLevel=M,this.clearTimer();const U=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===M&&M>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,M>c){let e=this.findBestLevel(this.hls.levels[c].bitrate,c,M,0,t,1,1);-1===e&&(e=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};g||w>2*O?U():this.timer=self.setInterval(U,1e3*O),r.trigger($.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new G(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.FRAG_LOADING,this.onFragLoading,this),t.on($.FRAG_LOADED,this.onFragLoaded,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this),t.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.FRAG_LOADING,this.onFragLoading,this),t.off($.FRAG_LOADED,this.onFragLoaded,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this),t.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off($.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;var i;this.ignoreFragment(s)||(s.bitrateTest||(this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case F.BUFFER_ADD_CODEC_ERROR:case F.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case F.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.first;C(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===U.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:s,id:e.type};this.onFragBuffered($.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==U.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,e,t,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;t&&(c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1)}const u=this.findBestLevel(o,n,i,l,c,d,h);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,i,r,n,a){var o;const l=i+r,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[h],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===m||-1===d;let T,S="SDR",A=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:I}=p,b=this.audioTracksByGroup||(this.audioTracksByGroup=un(g));let R=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let h=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=hn(e,r);for(let L=n.length;L--;){const e=t[n[L]];h||(h=e.channels[2]>0),u=Math.min(u,e.minHeight),f=Math.min(f,e.minFramerate),g=Math.min(g,e.minBitrate),E.filter(t=>e.videoRanges[t]>0).length>0&&(c=!0)}u=C(u)?u:0,f=C(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=C(g)?g:s,s=Math.max(g,s),c||(e=void 0);const A=n.length>1;return{codecSet:n.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(v=c?E.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return cn(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return cn(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return cn(i,`audio codec preference "${o}" not found`),e;if(a&&!d){if(!r.channels[a])return cn(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||d)&&h&&0===r.channels[2])return cn(i,"no renditions with stereo sound found"),e;if(r.minHeight>T)return cn(i,`min resolution of ${r.minHeight} > maximum of ${T}`),e;if(r.minFramerate>S)return cn(i,`min framerate of ${r.minFramerate} > maximum of ${S}`),e;if(!v.some(t=>r.videoRanges[t]>0))return cn(i,`no variants with VIDEO-RANGE of ${pt(v)} found`),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return cn(i,`video codec preference "${l}" not found`),e;if(r.maxScore<p)return cn(i,`max score of ${r.maxScore} < selected max of ${p}`),e}return e&&(zr(i)>=zr(e)||r.fragmentError>t[e].fragmentError)?e:(m=r.minIndex,p=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce((t,s,i)=>{if(!s.codecSet)return t;const r=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const s=e.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]}))}),t},{})}(f,b,e,s)),S,t,L,I),{codecSet:r,videoRanges:n,minFramerate:a,minBitrate:o,minIndex:l,preferHDR:d}=i;R=l,T=r,S=d?n[n.length-1]:n[0],A=a,t=Math.max(t,o),this.log(`picked start tier ${pt(i)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const k=u?u.duration:c?c.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let _=s;_>=e;_--){var P;const e=f[_],o=_>h;if(!e)continue;if(p.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&rn(e,b,S,A,t,L)?(e.supportedPromise=nn(e,b,s,this.supportedCache),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${pt(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${pt(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${pt(t)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):e.supportedResult=dt}if((T&&e.codecSet!==T||S&&e.videoRange!==S||o&&A>e.frameRate||!o&&A>0&&A<e.frameRate||null!=(P=e.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some(t=>!1===t.smooth))&&(!E||_!==R)){w.push(_);continue}const c=e.details,g=(u?null==c?void 0:c.partTarget:null==c?void 0:c.averagetargetduration)||k;let v;v=o?a*t:n*t;const I=k&&i>=2*k&&0===r?e.averageBitrate:e.maxBitrate,x=this.getTimeToLoadFrag(D,v,I*g,void 0===c);if(v>=I&&(_===d||0===e.loadError&&0===e.fragmentError)&&(x<=D||!C(x)||y&&!this.bitrateTestDelay||x<l)){const t=this.forcedAutoLevel;return _===m||-1!==t&&t===m||(w.length&&this.trace(`Skipped level(s) ${w.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[w[0]].codecs}" ${f[w[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${h}->${_} adjustedbw(${Math.round(v)})-bitrate=${Math.round(v-I)} ttfb:${D.toFixed(1)} avgDuration:${g.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${E} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=_),_}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),e)}},yt={search:function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null}},Et={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Tt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},St=class extends K{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on($.ERROR,this.onError,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off($.ERROR,this.onError,this),t.off($.ERROR,this.onErrorOut,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===U.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,s=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===s?e.loadLevel:s}variantHasKey(t,e){if(t){var s;if(null!=(s=t.details)&&s.hasKey(e))return!0;const i=t.audioGroups;if(i)return this.hls.allAudioTracks.filter(t=>i.indexOf(t.groupId)>=0).some(t=>{var s;return null==(s=t.details)?void 0:s.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var s;if(e.fatal)return;const i=this.hls,r=e.context;switch(e.details){case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case F.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction=_n());case F.FRAG_GAP:case F.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Et.SendAlternateToPenaltyBox);case F.LEVEL_EMPTY_ERROR:case F.LEVEL_PARSING_ERROR:{var n;const t=e.parent===U.MAIN?e.level:i.loadLevel;e.details===F.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case F.LEVEL_LOAD_ERROR:case F.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case F.AUDIO_TRACK_LOAD_ERROR:case F.AUDIO_TRACK_LOAD_TIMEOUT:case F.SUBTITLE_LOAD_ERROR:case F.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=i.loadLevelObj;if(t&&(r.type===N.AUDIO_TRACK&&t.hasAudioGroup(r.groupId)||r.type===N.SUBTITLE_TRACK&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Et.SendAlternateToPenaltyBox,void(e.errorAction.flags=Tt.MoveAllAlternatesMatchingHost)}return;case F.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:Et.SendAlternateToPenaltyBox,flags:Tt.MoveAllAlternatesMatchingHDCP});case F.KEY_SYSTEM_SESSION_UPDATE_FAILED:case F.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case F.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:Et.SendAlternateToPenaltyBox,flags:Tt.MoveAllAlternatesMatchingKey});case F.BUFFER_ADD_CODEC_ERROR:case F.REMUX_ALLOC_ERROR:case F.BUFFER_APPEND_ERROR:var a;return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,null!=(a=e.level)?a:i.loadLevel)));case F.INTERNAL_EXCEPTION:case F.BUFFER_APPENDING_ERROR:case F.BUFFER_FULL_ERROR:case F.LEVEL_SWITCH_ERROR:case F.BUFFER_STALLED_ERROR:case F.BUFFER_SEEK_OVER_HOLE:case F.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=_n())}e.type===O.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=_n())}getPlaylistRetryOrSwitchAction(t,e){const s=Rn(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(wn(s,i,Ln(t),t.response))return{action:Et.RetryRequest,flags:Tt.None,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Rn(In(t)?n:r,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(i&&(t.details!==F.FRAG_GAP&&i.fragmentError++,!bn(t)&&wn(a,o,Ln(t),t.response)))return{action:Et.RetryRequest,flags:Tt.None,retryConfig:a,retryCount:o};const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,e===F.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===U.AUDIO&&e===F.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===F.BUFFER_ADD_CODEC_ERROR||e===F.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:t})=>i.audioCodec!==t),m="video"===t.sourceBufferName&&(e===F.BUFFER_ADD_CODEC_ERROR||e===F.BUFFER_APPEND_ERROR)&&d.some(({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let s=d.length;s--;){const r=(s+h)%d.length;if(r!==h&&r>=c&&r<=u&&0===d[r].loadError){var a,o;const s=d[r];if(e===F.FRAG_GAP&&f===U.MAIN&&t.frag){const e=d[r].details;if(e){const s=En(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===N.AUDIO_TRACK&&s.hasAudioGroup(v)||p===N.SUBTITLE_TRACK&&s.hasSubtitleGroup(v))continue;if(f===U.AUDIO&&null!=(a=i.audioGroups)&&a.some(t=>s.hasAudioGroup(t))||f===U.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(t=>s.hasSubtitleGroup(t))||g&&i.audioCodec===s.audioCodec||m&&i.codecSet===s.codecSet||!g&&i.codecSet!==s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Et.SendAlternateToPenaltyBox,flags:Tt.None,nextAutoLevel:l}}return{action:Et.SendAlternateToPenaltyBox,flags:Tt.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Et.DoNothing:break;case Et.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===F.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0;case Et.RetryRequest:}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Tt.None:this.switchLevel(t,r);break;case Tt.MoveAllAlternatesMatchingHDCP:{const i=this.getVariantLevelIndex(t.frag),r=e.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(s.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){e.maxHdcpLevel=ht[ht.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case Tt.MoveAllAlternatesMatchingKey:{const e=t.decryptdata;if(e){const i=this.hls.levels,r=i.length;for(let s=r;s--;)if(this.variantHasKey(i[s],e)){var n,a;this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(n=i[s].audioGroups)?void 0:n.join(",")}" (${null==(a=t.frag)?void 0:a.type} fragment) ${mr(e.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${t.error})`),this.hls.removeLevel(s)}const o=t.frag;if(this.hls.levels.length<r)s.resolved=!0;else if(o&&o.type!==U.MAIN){const t=o.decryptdata;t&&!e.matches(t)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===F.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=en(t.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${i} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(i))}}},At={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Lt=class{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.BUFFER_APPENDED,this.onBufferAppended,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this),t.on($.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.BUFFER_APPENDED,this.onBufferAppended,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this),t.off($.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let i=s.length;i--;){const e=s[i];if(!e)break;if(e.start<=t&&t<=e.end&&e.loaded)return e}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===e&&(!s||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i,r){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(a.body),s}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const s=t.frag,i=xn(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(e).forEach(i=>{const a=s.elementaryStreams[i];if(!a)return;const o=e[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,t.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),Cn(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(t,e){t.buffered=!0,(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=Mn(s,e=>e.fragment.sn>=t))}fragBuffered(t,e){const s=xn(t);let i=this.fragments[s];!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t))}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let d=0;d<i.length;d++){const t=i.start(d)-this.bufferPadding,e=i.end(d)+this.bufferPadding;if(l>=t&&o<=e){r.time.push({startPTS:Math.max(n,i.start(d)),endPTS:Math.min(a,i.end(d))});break}if(n<e&&a>t){const t=Math.max(n,i.start(d)),e=Math.min(a,i.end(d));e>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:e}))}else if(a<=t)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Cn(d)&&(s=d.body.start-a,i=d.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=d.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Cn(e))}getState(t){const e=xn(t),s=this.fragments[e];return s?s.buffered?Cn(s)?At.PARTIAL:At.OK:At.APPENDING:At.NOT_LOADED}isTimeBuffered(t,e,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,t>=i&&e<=r)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const s=e.frag,i=e.part?null:e,r=xn(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r,type:n}=e;if("initSegment"===s.sn)return;const a=s.type;if(i){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=xn(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,s=Object.keys(e);if(!t)return s.length>0;for(let i=s.length;i--;){const r=e[s[i]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=xn(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=Mn(s,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}},It={cbc:0,ctr:1},bt=class{constructor(t,e,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=s}decrypt(t,e){switch(this.aesMode){case It.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case It.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}},Rt=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=e.getUint32(4*i);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,d[s]=v<<16|v>>>16,h[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,A,L,I,b,R,k,D,w,P,_;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(R=C(p[e]),k=C(p[e+1]),D=C(p[e+2]),w=C(p[e+3]),A=R^r[0],L=w^r[1],I=D^r[2],b=k^r[3],P=4,_=1;_<i;_++)y=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&b]^r[P],E=o[L>>>24]^l[I>>16&255]^d[b>>8&255]^h[255&A]^r[P+1],T=o[I>>>24]^l[b>>16&255]^d[A>>8&255]^h[255&L]^r[P+2],S=o[b>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^r[P+3],A=y,L=E,I=T,b=S,P+=4;y=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&b]^r[P],E=n[L>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[P+1],T=n[I>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^r[P+2],S=n[b>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^r[P+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^m),u=R,f=k,g=D,m=w,e+=4}return v.buffer}},kt=class{constructor(t,e,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=s}expandKey(){const t=function(t){switch(t){case It.cbc:return"AES-CBC";case It.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}},Dt=class{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.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:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?t.slice(0,e-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s,i){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s,i)}softwareDecrypt(t,e,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==It.cbc||16!==e.byteLength)return Y.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Fr(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Rt),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,s,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s,i));this.key=e,this.fastAesKey=new kt(this.subtle,e,i)}return this.fastAesKey.expandKey().then(e=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bt(this.subtle,new Uint8Array(s),i).decrypt(t.buffer,e)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Y.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s,i)))}onWebCryptoError(t,e,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=t.slice(0,s),this.remainderData=t.slice(s)),e}logOnce(t){this.logEnabled&&(Y.log(`[decrypter]: ${t}`),this.logEnabled=!1)}},wt=Math.pow(2,17),Pt=class{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const s=t.url;if(!s)return Promise.reject(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void o(Fn(t));t.gap=!1}const l=this.loader=r?new r(i):new n(i),d=On(t);t.loader=l;const h=Dn(i.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:wt};t.stats=l.stats;const u={onSuccess:(e,s,i,r)=>{this.resetLoader(t,l);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,r,n)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:dr({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:e}))}};e&&(u.onProgress=(s,i,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})),l.load(d,c,u)})}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Fn(t,e));const l=this.loader=r?new r(i):new n(i),d=On(t,e);t.loader=l;const h=Dn(i.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:wt};e.stats=l.stats,l.load(d,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:i.data,networkDetails:o};s(d),a(d)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:dr({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new _t({type:O.NETWORK_ERROR,details:F.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}},_t=class extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}},Ct=class extends K{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},xt=class{constructor(t,e,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={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=s,this.size=i,this.part=r,this.partial=n}},Mt={length:0,start:()=>0,end:()=>0},Ot=class t{static isBuffered(e,s){if(e){const i=t.getBuffered(e);for(let t=i.length;t--;)if(s>=i.start(t)&&s<=i.end(t))return!0}return!1}static bufferedRanges(e){if(e){const s=t.getBuffered(e);return t.timeRangesToArray(s)}return[]}static timeRangesToArray(t){const e=[];for(let s=0;s<t.length;s++)e.push({start:t.start(s),end:t.end(s)});return e}static bufferInfo(e,s,i){if(e){const r=t.bufferedRanges(e);if(r.length)return t.bufferedInfo(r,s,i)}return{len:0,start:s,end:s,bufferedIndex:-1}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let i=-1,r=[];if(s)for(let d=0;d<t.length;d++){e>=t[d].start&&e<=t[d].end&&(i=d);const n=r.length;if(n){const e=r[n-1].end;t[d].start-e<s?t[d].end>e&&(r[n-1].end=t[d].end):r.push(t[d])}else r.push(t[d])}else r=t;let n,a=0,o=e,l=e;for(let d=0;d<r.length;d++){const t=r[d].start,h=r[d].end;if(-1===i&&e>=t&&e<=h&&(i=d),e+s>=t&&e<h)o=t,l=h,a=l-e;else if(e+s<t){n=t;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||Mt}catch(e){return Y.log("failed to get media.buffered",e),Mt}}},Ft=/\{\$([a-zA-Z0-9-_]+)\}/g,$t=/^(\d+)x(\d+)$/,Nt=/(.+?)=(".*?"|.*?)(?:,|$)/g,Ut=class t{constructor(e,s){"string"==typeof e&&(e=t.parseAttrList(e,s)),or(this,e)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const s=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)s[t]=parseInt(e.slice(2*t,2*t+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=$t.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let s;const i={};for(Nt.lastIndex=0;null!==(s=Nt.exec(t));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=Nn(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)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":Y.warn(`${t}: attribute ${r} is missing quotes`)}i[r]=n}return i}},Bt=class{constructor(t,e,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=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(i=null==e?void 0:e.tagOrder)?i:s,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){Y.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=or(new Ut({}),s,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);C(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(Y.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(C(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&C(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},Gt=class{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let s=e.decryptdata;return s||(e.setKeyFormat(t.keyFormat),s=e.decryptdata),!!s&&t.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&C(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let s=t.length;s--;)if(t[s].index>e)return t[s].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}},Kt="undefined"!=typeof self?self:void 0,Vt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ht={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"},Wt=null!=Kt&&null!=(rr=Kt.navigator)&&rr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null,Yt={},jt=class t{static clearKeyUriToKeyIdMap(){Yt={}}static setKeyIdForUri(t,e){Yt[t]=e}static addKeyIdForUri(t){const e=Object.keys(Yt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,e),Yt[t]=s,s}constructor(t,e,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Wn(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(pr(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Vn(t.keyFormatVersions,this.keyFormatVersions)&&Hn(t.iv,this.iv)&&Hn(t.keyId,this.keyId)}isSupported(){if(this.method){if(Wn(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ht.FAIRPLAY:case Ht.WIDEVINE:case Ht.PLAYREADY:case Ht.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,s){if(!this.encrypted||!this.uri)return null;if(Wn(this.method)){let s=this.iv;return s||("number"!=typeof e&&(Y.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),s=function(t){const e=new Uint8Array(16);for(let s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(e)),new t(this.method,this.uri,"identity",this.keyFormatVersions,s)}if(this.keyId){const e=Yt[this.uri];if(e&&!Vn(this.keyId,e)&&t.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Xn(this.uri);if(i)switch(this.keyFormat){case Ht.WIDEVINE:if(this.pssh=i,!this.keyId){const t=function(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32<s;){const s=Vr(new DataView(t,i));e.push(s),i+=s.size}}return e}(i.buffer);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=ea(s));break;case Ht.PLAYREADY:this.pssh=Kr(new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]),0,i),this.keyId=ta(i);break;default:{let t=i.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(t){const e=null==t?void 0:t[Ht.WIDEVINE];return e?e.keyId:null}(s),e||(e=ea(s),e||(e=Yt[this.uri])),e&&(this.keyId=e,t.setKeyIdForUri(this.uri,e))}return this}},qt=/#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,zt=/#EXT-X-MEDIA:(.*)/g,Xt=/^#EXT(?:INF|-X-TARGETDURATION):/m,Qt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Zt=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("|")),Jt=class t{static findGroup(t,e){for(let s=0;s<t.length;s++){const i=t[s];if(i.id===e)return i}}static resolve(t,e){return z.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Xt.test(t)}static parseMasterPlaylist(e,s){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:$n(e)},r=[];if(qt.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;null!=(n=qt.exec(e));)if(n[1]){var a;const e=new Ut(n[1],i),o=Nn(i,n[2]),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:t.resolve(o,s)},d=e.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),aa(e.CODECS,l);const h=e["SUPPLEMENTAL-CODECS"];h&&(l.supplemental={},aa(h,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),i.levels.push(l)}else if(n[3]){const e=n[3],r=n[4];switch(e){case"SESSION-DATA":{const t=new Ut(r,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=ra(r,s,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):Y.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":Un(i,new Ut(r,i),s);break;case"CONTENT-STEERING":{const e=new Ut(r,i);i.contentSteering={uri:t.resolve(e["SERVER-URI"],s),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=na(r)}}return i.levels=r.length>0&&r.length<i.levels.length?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,s,i){let r;const n={},a=i.levels,o={AUDIO:a.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:a.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(zt.lastIndex=0;null!==(r=zt.exec(e));){const e=new Ut(r[1],i),a=e.TYPE;if(a){const i=o[a],r=n[a]||[];n[a]=r;const d=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],c=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],g={attrs:e,bitrate:0,id:l++,groupId:e["GROUP-ID"]||"",name:e.NAME||d||"",type:a,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:d,url:e.URI?t.resolve(e.URI,s):""};if(h&&(g.assocLang=h),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const e=t.findGroup(i,g.groupId)||i[0];oa(g,e,"audioCodec"),oa(g,e,"textCodec")}r.push(g)}}return n}static parseLevelPlaylist(t,e,s,i,r,n){var a;const o={url:e},l=new Gt(e),d=l.fragments,h=[];let c,u,f,g,m=null,p=0,v=0,y=0,E=0,T=0,S=null,A=new J(i,o),L=-1,I=!1,b=null;if(Qt.lastIndex=0,l.m3u8=t,l.hasVariableRefs=$n(t),"#EXTM3U"!==(null==(a=Qt.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Qt.exec(t));){I&&(I=!1,A=new J(i,o),A.playlistOffset=y,A.setStart(y),A.sn=p,A.cc=E,T&&(A.bitrate=T),A.level=s,m&&(A.initSegment=m,m.rawProgramDateTime&&(A.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),b&&(A.setByteRange(b),b=null)));const t=c[1];if(t){A.duration=parseFloat(t);const e=(" "+c[2]).slice(1);A.title=e||null,A.tagList.push(e?["INF",t,e]:["INF",t])}else if(c[3]){if(C(A.duration)){A.playlistOffset=y,A.setStart(y),f&&ha(A,f,l),A.sn=p,A.level=s,A.cc=E,d.push(A);const t=(" "+c[3]).slice(1);A.relurl=Nn(l,t),la(A,S,h),S=A,y+=A.duration,p++,v=0,I=!0}}else{if(c=c[0].match(Zt),!c){Y.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const t=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(t){case"BYTERANGE":S?A.setByteRange(r,S):A.setByteRange(r);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=r,A.tagList.push(["PROGRAM-DATE-TIME",r]),-1===L&&(L=d.length);break;case"PLAYLIST-TYPE":l.type&&ca(l,t,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?ca(l,t,c):d.length>0&&ua(l,t,c),p=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&ca(l,t,c);const e=new Ut(r,l),s=e.decimalInteger("SKIPPED-SEGMENTS");if(C(s)){l.skippedSegments+=s;for(let t=s;t--;)d.push(null);p+=s}const i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&ca(l,t,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&ca(l,t,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||ca(l,t,c),l.live=!1;break;case"#":(r||a)&&A.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([t]);break;case"BITRATE":A.tagList.push([t,r]),T=1e3*parseInt(r),C(T)?A.bitrate=T:T=0;break;case"DATERANGE":{const t=new Ut(r,l),e=new Bt(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:Y.warn(`Ignoring invalid DATERANGE tag: "${r}"`),A.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new Ut(r,l);"IMPORT"in t?Bn(l,t,n):Un(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?ca(l,t,c):d.length>0&&ua(l,t,c),l.startCC=E=parseInt(r);break;case"KEY":{const t=ra(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=or({},f)),f[t.keyFormat]=t)}else Y.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=na(r);break;case"MAP":{const t=new Ut(r,l);if(A.duration){const e=new J(i,o);da(e,t,s,f),m=e,A.initSegment=m,m.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=m.rawProgramDateTime)}else{const e=A.byteRangeEndOffset;if(e){const t=A.byteRangeStartOffset;b=`${e-t}@${t}`}else b=null;da(A,t,s,f),m=A,I=!0}m.cc=E;break}case"SERVER-CONTROL":g&&ca(l,t,c),g=new Ut(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":l.partTarget&&ca(l,t,c),l.partTarget=new Ut(r).decimalFloatingPoint("PART-TARGET");break;case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,s=v++,i=new tt(new Ut(r,l),A,o,s,e);t.push(i),A.duration+=i.duration;break}case"PRELOAD-HINT":l.preloadHint=new Ut(r,l);break;case"RENDITION-REPORT":{const t=new Ut(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:Y.warn(`line parsed but not handled: ${c}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(la(A,S,h),A.cc=E,l.fragmentHint=A,f&&ha(A,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const R=d.length,k=d[0],D=d[R-1];if(y+=l.skippedSegments*l.targetduration,y>0&&R&&D){l.averagetargetduration=y/R;const t=D.sn;l.endSN="initSegment"!==t?t:0,l.live||(D.endList=!0),L>0&&(function(t,e){let s=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(d,L),k&&h.unshift(k))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,h.length&&l.dateRangeTagCount&&k&&sa(h,l),l.endCC=E,l}},te={toString:function(t){let e="";const s=t.length;for(let i=0;i<s;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e}},ee={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"},se=class extends Ct{constructor(t,e,s,i,r){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ee.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=Ot.bufferInfo(i||s,n,t.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${C(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===ee.ENDED)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,i=e.start-s,r=e.start+e.duration+s;if(o||r<a.start||i>a.end){const t=n>r;(n<i||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts)){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===ee.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Pt(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Dt(t.config)}registerListeners(){const{hls:t}=this;t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===ee.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ee.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const s=t.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=Ot.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>i&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return Ot.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;_a(s,"seeking",this.onMediaSeeking),_a(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===ee.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ca(i,"seeking",this.onMediaSeeking),Ca(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ee.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,s){this.startFragRequested=!0,this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,s=t.frag;this.fragContextChanged(s)?(e===ee.FRAG_LOADING||!this.fragCurrent&&e===ee.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=ee.IDLE):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger($.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==ee.STOPPED&&this.state!==ee.ERROR&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===At.APPENDING){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===At.PARTIAL&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger($.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:s,payload:i}=t,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&Wn(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,Yn(r.method)).catch(t=>{throw e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),t}).then(i=>{const r=self.performance.now();return e.trigger($.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),t.payload=i,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==ee.STOPPED&&this.state!==ee.ERROR&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state!==ee.STOPPED&&(this.state=ee.IDLE),t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var s,i;const r=t.tracks;if(r&&!e.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(s.message),!(!t||t.mediaKeys)&&(this.hls.trigger($.ERROR,{type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${s?te.toString(Ot.getBuffered(s)):"(detached)"})`),yr(t)){var i;if(t.type!==U.SUBTITLE){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=ee.IDLE)}const e=null==(i=this.levels)?void 0:i[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=ee.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),a=new xt(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,i){var r;this.fragCurrent=t;const n=e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key)t.encrypted||(a=this.keyLoader.loadClear(t,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=ee.KEY_LOADING,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger($.KEY_LOADED,t),this.state===ee.KEY_LOADING&&(this.state=ee.IDLE),t}),this.hls.trigger($.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(yr(t)&&(!o||t.sn!==o.sn)){const s=this.shouldLoadParts(e.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts&&yr(t)){const r=n.partList;if(r&&i){s>n.fragmentEnd&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,s);if(o>-1){const l=r[o];let d;return t=this.fragCurrent=l.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(t,!1,l)}) cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=ee.FRAG_LOADING,d=a?a.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,i)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,i).catch(t=>this.handleFragLoadError(t)),this.hls.trigger($.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}var l;if(yr(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),C(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ee.FRAG_LOADING;const d=this.config.progressive&&t.type!==U.SUBTITLE;let h;return h=d&&a?a.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,i)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,d?i:void 0),a]).then(([t])=>(!d&&i&&i(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger($.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,i).then(i=>{o[e.index]=i;const n=i.part;this.hls.trigger($.FRAG_LOADED,i);const a=Sa(s.details,t.sn,e.index+1)||Aa(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});d(a)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===F.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===O.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger($.ERROR,e)}else this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==ee.PARSING)return void(this.fragCurrent||this.state===ee.STOPPED||this.state===ee.ERROR||(this.state=ee.IDLE));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var s;const r=t.partList[0];if(r.fragment.type===U.SUBTITLE)return!1;var i;if(e>=r.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0)&&(this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?Sa(o,r,n):null,d=l?l.fragment:Ta(o,r,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,s,i,r){if(this.state!==ee.PARSING)return;const{data1:n,data2:a}=t;let o=n;if(a&&(o=Fr(n,a)),!o.length)return;const l=this.initPTS[e.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:t.type,frag:e,part:s,chunkMeta:i,offset:d,parent:e.type,data:o};if(this.hls.trigger($.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Ot.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const s=e.currentTime,i=Ot.bufferInfo(e,s,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,i.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var s;const i=this.getLoadPosition();if(!C(i))return null;const r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,r)}getFwdBufferInfoAtPos(t,e,s,i){const r=Ot.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-e,i);return Ot.bufferInfo(t,e,s)}}return r}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e),r=Math.max(t-3*e,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=U.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const s=this.hls.startPosition,i=this.hls.liveSyncPosition,r=o?(-1!==s&&s>=n?s:i)||o.start:t;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else t<=n&&(o=s[0]);if(!o){const s=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,s,e)}let d=this.filterReplacedPrimary(o,e);if(!d&&o){const t=o.sn-e.startSN;d=this.filterReplacedPrimary(s[t+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===At.OK||s===At.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,i,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==t&&s.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){var t;return!(!xa(this.config)||!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event))}filterReplacedPrimary(t,e){if(!t)return t;if(xa(this.config)&&t.type!==U.SUBTITLE){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(s.appendInPlace||Math.abs(t.start-i.start)>1||0===i.start)return null}else{if(t.end<=i.start&&!1===(null==e?void 0:e.live))return null;if(t.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||t.start-i.end>1))return null}}const r=null==s?void 0:s.playerQueue;if(r)for(let e=r.length;e--;){const s=r[e].interstitial;if(s.appendInPlace&&t.start>=s.startTime&&t.end<=s.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||(o.independent||n)&&o.fragment===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${o.start}`),i=a),r=l}return i}loadedEndOfParts(t,e){let s;for(let i=t.length;i--;){if(s=t[i],!s.loaded)return!1;if(e>s.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!C(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let i=0;i<t.length;++i){const r=t[i];if(Sn(e,s,r))return r}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=An(t,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,d=s.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;var u;(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),t<e)?c=En(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l):c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===At.OK||e===At.PARTIAL&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!h||d[0].fragment.sn>c.sn||!s.live)&&c.level===r.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==At.OK?e:null}}return c}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,n=!e,a=t.alignedSliding&&C(r);if(n||!a&&!r){!function(t,e){t&&(wa(e,t),e.alignedSliding||Pa(e,t),e.alignedSliding||e.skippedSegments||va(t,e,!1))}(s,t);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;s<e&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:t.startTimeOffset;null!==n&&C(n)?(s=e+n,n<0&&(s+=t.edge),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):t.live?(s=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var t;const{media:e}=this;let s=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?s=e.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&yr(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===ee.FRAG_LOADING_WAITING_RETRY)||(this.state=ee.IDLE)}onFragmentOrKeyLoadError(t,e){var s;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=e.details===F.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=e.errorAction;if(!a)return void(this.state=ee.ERROR);const{action:o,flags:l,retryCount:d=0,retryConfig:h}=a,c=!!h,u=c&&o===Et.RetryRequest,f=c&&!a.resolved&&l===Tt.MoveAllAlternatesMatchingHost,g=null==(s=this.hls.latestLevelDetails)?void 0:s.live;if(!u&&f&&yr(i)&&!i.endList&&g&&!bn(e))this.resetFragmentErrors(t),this.treatAsGap(i),a.resolved=!0;else if((u||f)&&d<h.maxNumRetry){var m;const s=Pn(null==(m=e.response)?void 0:m.code),r=kn(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=ee.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${r}ms`)}else if(h){if(this.resetFragmentErrors(t),!(d<h.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);n||o===Et.RemoveAlternatePermanently||(a.resolved=!0)}else o===Et.SendAlternateToPenaltyBox?this.state=ee.WAITING_LEVEL:this.state=ee.ERROR;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,s=e===1/0;(!e||t>=e||s&&!Pn(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ee.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===ee.PARSING||this.state===ee.PARSED){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===U.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ee.STOPPED&&(this.state=ee.IDLE)}afterBufferFlushed(t,e,s){if(!t)return;const i=Ot.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===ee.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ee.STOPPED&&(this.state=ee.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){const r=s.details;if(r){if(!Object.keys(t.elementaryStreams).reduce((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=i?0:ga(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger($.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1)){var n;const e=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===s.fragmentError||e&&(s.fragmentError<2||t.endList))&&this.treatAsGap(t,s),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=ee.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger($.FRAG_PARSED,{frag:t,part:e})}else this.warn("level.details undefined")}playlistLabel(){return this.playlistType===U.MAIN?"level":"track"}fragInfo(t,e=!0,s){var i,r;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${(null!=(i=e&&!s?t.startPTS:(s||t).start)?i:NaN).toFixed(3)}-${(null!=(r=e&&!s?t.endPTS:(s||t).end)?r:NaN).toFixed(3)}]${s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}},ie=class{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let i=0;for(let r=0;r<t.length;r++){const e=t[r];s.set(e,i),i+=e.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}},re={exports:{}},ae=vr((ne||(ne=1,function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||t,a),l=s?s+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,r,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,i),!0;case 4:return h.fn.call(h.context,e,i,r),!0;case 5:return h.fn.call(h.context,e,i,r,n),!0;case 6:return h.fn.call(h.context,e,i,r,n,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(t,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,e);break;case 3:h[d].fn.call(h[d].context,e,i);break;case 4:h[d].fn.call(h[d].context,e,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,i,r){var n=s?s+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==e||r&&!o[l].once||i&&o[l].context!==i)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(re)),re.exports)),oe="1.6.15",le={},de=10,he=10,ce=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({}),ue=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,s){}demux(t,e){this.cachedData&&(t=Fr(this.cachedData,t),this.cachedData=null);let s,i=$a(t,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?to(i):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&C(o))&&(this.basePTS=fe(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ce.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(n,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=l}else Ya(t,r)?(i=$a(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ce.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const e=t.slice(s);this.cachedData?this.cachedData=Fr(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:eo(),id3Track:a,textTrack:eo()}}demuxSampleAes(t,e,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:eo(),id3Track:this._id3Track,textTrack:eo()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},fe=(t,e,s)=>C(t)?90*t:9e4*e+(s?9e4*s.baseTime/s.timescale:0),ge=null,me=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],pe=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ve=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ye=[0,1,1,4],Ee=class extends ue{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const s=$a(t,0);let i=(null==s?void 0:s.length)||0;if(ao(t,i))return!1;for(let r=t.length;i<r;i++)if(Ka(t,i))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Na(t,e)&&Ba(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){Va(t,this.observer,e,s,t.manifestCodec);const i=Wa(t,e,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},Te=(t,e)=>{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],e+=1,i-=o}return s},Se=class extends ue{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=oo(t,e,s,this.basePTS,this.frameIndex);if(-1!==i)return{sample:t.samples[t.samples.length-1],length:i,missing:0}}static probe(t){if(!t)return!1;const e=$a(t,0);if(!e)return!1;const s=e.length;return 11===t[s]&&119===t[s+1]&&void 0!==to(e)&&Te(t,s)<16}},Ae=class extends ue{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=$a(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==to(e)&&Te(t,s)<=16)return!1;for(let i=t.length;s<i;s++)if(ao(t,s))return Y.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return ro(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return so(t,e,s,this.basePTS,this.frameIndex)}},Le=/\/emsg[-/]ID3/i,Ie=class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=eo("video",1),n=this.audioTrack=eo("audio",1),a=this.txtTrack=eo("text",1);if(this.id3Track=eo("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Dr(t);if(o.video){const{id:t,timescale:e,codec:s,supplemental:i}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s,r.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=it.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s<e;){const i=Lr(t,s);if(i>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=i>1?s+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Fr(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=Rr(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(s);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,e);return r.samples=$r(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=$r(t,e),{videoTrack:e,audioTrack:eo(),id3Track:i,textTrack:eo()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=Rr(t.samples,["emsg"]);i&&i.forEach(t=>{const i=function(t){const e=t[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==Sr(t.subarray(d,d+1));)s+=Sr(t.subarray(d,d+1)),d+=1;for(s+=Sr(t.subarray(d,d+1)),d+=1;"\0"!==Sr(t.subarray(d,d+1));)i+=Sr(t.subarray(d,d+1)),d+=1;i+=Sr(t.subarray(d,d+1)),d+=1,r=Lr(t,12),n=Lr(t,16),o=Lr(t,20),l=Lr(t,24),d=28}else if(1===e){d+=4,r=Lr(t,d),d+=4;const e=Lr(t,d);d+=4;const n=Lr(t,d);for(d+=4,a=2**32*e+n,x(a)||(a=Number.MAX_SAFE_INTEGER,Y.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Lr(t,d),d+=4,l=Lr(t,d),d+=4;"\0"!==Sr(t.subarray(d,d+1));)s+=Sr(t.subarray(d,d+1)),d+=1;for(s+=Sr(t.subarray(d,d+1)),d+=1;"\0"!==Sr(t.subarray(d,d+1));)i+=Sr(t.subarray(d,d+1)),d+=1;i+=Sr(t.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(Le.test(i.schemeIdUri)){const t=lo(i,e);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:ce.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=lo(i,e);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:ce.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(t,e,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}},be=class{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Dt(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,It.cbc)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}).catch(s)}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32||(this.decryptAacSample(t,e,s),this.decrypter.isSync())))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let i=0;for(let r=32;r<t.length-16;r+=160,i+=16)s.set(t.subarray(r,r+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let r=32;r<t.length-16;r+=160,i+=16)t.set(s.subarray(i,i+16),r);return t}decryptAvcSample(t,e,s,i,r){const n=Gr(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}).catch(i)}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}},Re=class{constructor(){this.VideoSample=null}createVideoSample(t,e,s){return{key:t,frame:!1,pts:e,dts:s,units:[],length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,s){const i=e.byteLength;let r=t.naluState||0;const n=r,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(e,0),r=0,h=1);h<i;)if(o=e[h++],r)if(1!==r)if(o)if(1===o){if(l=h-r-1,c>=0){const t={data:e.subarray(c,l),type:u};a.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(n&&h<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=Fr(s.data,e.subarray(0,l)),s.state=0))}h<i?(d=this.getNALuType(e,h),c=h,u=d,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const t={data:e.subarray(c,i),type:u,state:r};a.push(t)}if(0===a.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Fr(s.data,e))}return t.naluState=r,a}},ke=class{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&Y.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?s<<e|this.readBits(e):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},De=class extends Re{parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 1:{let e=!1;n=!0;const r=i.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;e&&null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Br(i.data,1,s.pts,e.samples);break;case 7:{var h,c;n=!0,o=!0;const e=i.data,s=this.readSPS(e);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(h=t.pixelRatio)?void 0:h[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:n=!0,t.pps=[i.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}a&&n&&a.units.push(i)}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new ke(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let s,i=8,r=8;for(let n=0;n<t;n++)0!==r&&(s=e.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(t){const e=new ke(t);let s,i,r,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=c();if(3===t&&f(1),m(),m(),f(1),u())for(i=3!==t?8:12,r=0;r<i;r++)u()&&p(r<6?16:64,e)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();m(),f(1);const E=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let A=[1,1];if(u()&&u())switch(d()){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=[d()<<8|d(),d()<<8|d()]}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}},we=class extends Re{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(i=>{var r,l;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;n=!0,o&&null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Br(i.data,2,s.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=or(t.params,this.readVPS(i.data)),this.initVPS=i.data),t.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],i.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(i.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const s in e.params)t.params[s]=e.params[s]}this.pushParameterSet(t.sps,i.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(i.data);for(const s in e)t.params[s]=e[s]}this.pushParameterSet(t.pps,i.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:n=!1}a&&n&&a.units.push(i)}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let s=0;for(let i=0;i<t.byteLength;i++)i>=2&&3===t[i]&&0===t[i-1]&&0===t[i-2]||(e[s]=t[i],s++);return new Uint8Array(e.buffer,0,s)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ke(t);return e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6),{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new ke(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const s=e.readBits(3);e.readBoolean();const i=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let W=0;W<s;W++)v.push(e.readBoolean()),y.push(e.readBoolean());if(s>0)for(let W=s;W<8;W++)e.readBits(2);for(let W=0;W<s;W++)v[W]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[W]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),A=e.readBoolean();let L=0,I=0,b=0,R=0;A&&(L+=e.readUEG(),I+=e.readUEG(),b+=e.readUEG(),R+=e.readUEG());const k=e.readUEG(),D=e.readUEG(),w=e.readUEG();for(let W=e.readBoolean()?0:s;W<=s;W++)e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.readBoolean()&&e.readBoolean())for(let W=0;W<4;W++)for(let t=0;t<(3===W?2:6);t++)if(e.readBoolean()){const t=Math.min(64,1<<4+(W<<1));W>1&&e.readEG();for(let s=0;s<t;s++)e.readEG()}else e.readUEG();e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let _=0;for(let W=0;W<P;W++){let t=!1;if(0!==W&&(t=e.readBoolean()),t){W===P&&e.readUEG(),e.readBoolean(),e.readUEG();let t=0;for(let s=0;s<=_;s++){const s=e.readBoolean();let i=!1;s||(i=e.readBoolean()),(s||i)&&t++}_=t}else{const t=e.readUEG(),s=e.readUEG();_=t+s;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let i=0;i<s;i++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let s=0;s<t;s++){for(let t=0;t<w+4;t++)e.readBits(1);e.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,$=0;e.readBoolean(),e.readBoolean();let N=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),M=e.readBits(16))}if(e.readBoolean()&&e.readBoolean(),e.readBoolean()&&(e.readBits(3),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())),e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),N=e.readBoolean(),N&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG()),e.readBoolean()&&(F=e.readBits(32),$=e.readBits(32),e.readBoolean()&&e.readUEG(),e.readBoolean())){const t=e.readBoolean(),i=e.readBoolean();let r=!1;(t||i)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=s;n++){O=e.readBoolean();let s=!1;O||e.readBoolean()?e.readEG():s=e.readBoolean();const n=s?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(i)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let U=T,B=S;if(A){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),U=T-t*I-t*L,B=S-e*R-e*b}const G=i?["A","B","C"][i]:"",K=a<<24|o<<16|l<<8|d;let V=0;for(let W=0;W<32;W++)V=(V|(K>>W&1)<<31-W)>>>0;let H=V.toString(16);return 1===n&&"2"===H&&(H="6"),{codecString:`hvc1.${G}${n}.${H}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:$/F}},width:U,height:B,pixelRatio:[x,M]}}readPPS(t){const e=new ke(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2),e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const s=e.readBoolean(),i=e.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}},Pe=188,_e=class t{constructor(t,e,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=t,this.config=e,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,s){const i=t.syncOffset(e);return i>0&&s.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let s=Math.min(940,e-Pe)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<e;o+=Pe){if(71!==t[o]||e-o!==Pe&&71!==t[o+Pe]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-Pe)+1)),r||(r=0===ho(t,o)),r&&a>1&&(0===n&&a>2||o+Pe>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:it[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(e,s,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=t.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=t.createTrack("audio",r),this._id3Track=t.createTrack("id3"),this._txtTrack=t.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=s,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,s,i=!1,r=!1){let n;i||(this.sampleAes=null);const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack;let h=a.pid,c=a.pesData,u=o.pid,f=l.pid,g=o.pesData,m=l.pesData,p=null,v=this.pmtParsed,y=this._pmtId,E=e.length;if(this.remainderData&&(E=(e=Fr(this.remainderData,e)).length,this.remainderData=null),E<Pe&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};const T=Math.max(0,t.syncOffset(e));E-=(E-T)%Pe,E<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let S=0;for(let t=T;t<E;t+=Pe)if(71===e[t]){const s=!!(64&e[t+1]),r=ho(e,t);let E;if((48&e[t+3])>>4>1){if(E=t+5+e[t+4],E===t+Pe)continue}else E=t+4;switch(r){case h:s&&(c&&(n=mo(c,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,d,n,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(E,t+Pe)),c.size+=t+Pe-E);break;case u:if(s){if(g&&(n=mo(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}g={data:[],size:0}}g&&(g.data.push(e.subarray(E,t+Pe)),g.size+=t+Pe-E);break;case f:s&&(m&&(n=mo(m,this.logger))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(e.subarray(E,t+Pe)),m.size+=t+Pe-E);break;case 0:s&&(E+=e[E]+1),y=this._pmtId=co(e,E);break;case y:{s&&(E+=e[E]+1);const r=uo(e,E,this.typeSupported,i,this.observer,this.logger);h=r.videoPid,h>0&&(a.pid=h,a.segmentCodec=r.segmentVideoCodec),u=r.audioPid,u>0&&(o.pid=u,o.segmentCodec=r.segmentAudioCodec),f=r.id3Pid,f>0&&(l.pid=f),null===p||v||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${p}'. Backtracking to sync byte @${T} to parse all TS packets.`),p=null,t=T-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=r}}else S++;S>0&&fo(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=c,o.pesData=g,l.pesData=m;const A={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(A),A}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:s,id3Track:i,textTrack:r}=t,n=s.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=mo(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,a&&(l=mo(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=mo(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,s){const i=this.demux(t,s,!0,!this.config.progressive),r=this.sampleAes=new be(this.observer,this.config,e);return this.decrypt(i,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new De:"hevc"===t&&(this.videoParser=new we))}decrypt(t,e){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{s(t)}):s(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{s(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let s=0;const i=this.aacOverFlow;let r,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,r=i.sample.unit.byteLength;if(-1===e)o=Fr(i.sample.unit,o);else{const n=r-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!Ga(o,r);r++);if(r!==s){let t;const e=r<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",fo(this.observer,new Error(t),e,this.logger),!e)return}if(Va(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Ha(t.samplerate);a=i.sample.pts+e}}let l,d=0;for(;r<n;){if(l=Wa(t,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!Ga(o,r);r++);}}parseMPEGPES(t,e){const s=e.data,i=s.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(no(s,n)){const e=so(t,s,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const s=e.data,i=e.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=oo(t,s,o,i,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=or({},e,{type:this._videoTrack?ce.emsg:ce.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}},Ce=class{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}},xe=Math.pow(2,32)-1,(Me=class t{static init(){let e;for(e in t.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:[]},t.types)t.types.hasOwnProperty(e)&&(t.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);t.HDLR_TYPES={video: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]),audio: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])};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);t.STTS=t.STSC=t.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),t.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),t.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),t.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),t.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),r=new Uint8Array([97,118,99,49]),n=new Uint8Array([0,0,0,1]);t.FTYP=t.box(t.types.ftyp,i,n,i,r),t.DINF=t.box(t.types.dinf,t.box(t.types.dref,s))}static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),i=0,s=8;i<r;i++)n.set(e[i],s),s+=e[i].byteLength;return n}static hdlr(e){return t.box(t.types.hdlr,t.HDLR_TYPES[e])}static mdat(e){return t.box(t.types.mdat,e)}static mdhd(e,s){s*=e;const i=Math.floor(s/(xe+1)),r=Math.floor(s%(xe+1));return t.box(t.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,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return t.box(t.types.mdia,t.mdhd(e.timescale||0,e.duration||0),t.hdlr(e.type),t.minf(e))}static mfhd(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))}static moof(e,s,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,s))}static moov(e){let s=e.length;const i=[];for(;s--;)i[s]=t.trak(e[s]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(t.mvex(e)))}static mvex(e){let s=e.length;const i=[];for(;s--;)i[s]=t.trex(e[s]);return t.box.apply(null,[t.types.mvex,...i])}static mvhd(e,s){s*=e;const i=Math.floor(s/(xe+1)),r=Math.floor(s%(xe+1)),n=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,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,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 t.box(t.types.mvhd,n)}static sdtp(e){const s=e.samples||[],i=new Uint8Array(4+s.length);let r,n;for(r=0;r<s.length;r++)n=s[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return t.box(t.types.sdtp,i)}static stbl(e){return t.box(t.types.stbl,t.stsd(e),t.box(t.types.stts,t.STTS),t.box(t.types.stsc,t.STSC),t.box(t.types.stsz,t.STSZ),t.box(t.types.stco,t.STCO))}static avc1(e){let s,i,r,n=[],a=[];for(s=0;s<e.sps.length;s++)i=e.sps[s],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));for(s=0;s<e.pps.length;s++)i=e.pps[s],r=i.byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));const o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(a))),l=e.width,d=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return t.box(t.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,l>>8&255,255&l,d>>8&255,255&d,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,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const e=t.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,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(e){return t.box(t.types.mp4a,t.audioStsd(e),t.box(t.types.esds,t.esds(e)))}static mp3(e){return t.box(t.types[".mp3"],t.audioStsd(e))}static ac3(e){return t.box(t.types["ac-3"],t.audioStsd(e),t.box(t.types.dac3,e.config))}static stsd(e){const{segmentCodec:s}=e;if("audio"===e.type){if("aac"===s)return t.box(t.types.stsd,t.STSD,t.mp4a(e));if("ac3"===s&&e.config)return t.box(t.types.stsd,t.STSD,t.ac3(e));if("mp3"===s&&"mp3"===e.codec)return t.box(t.types.stsd,t.STSD,t.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===s)return t.box(t.types.stsd,t.STSD,t.avc1(e));if("hevc"===s&&e.vps)return t.box(t.types.stsd,t.STSD,t.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${s}/${e.codec})`)}static tkhd(e){const s=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(i/(xe+1)),o=Math.floor(i%(xe+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,s>>24&255,s>>16&255,s>>8&255,255&s,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,r>>8&255,255&r,0,0,n>>8&255,255&n,0,0]))}static traf(e,s){const i=t.sdtp(e),r=e.id,n=Math.floor(s/(xe+1)),a=Math.floor(s%(xe+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),t.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))}static trex(e){const s=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,s){const i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n);let o,l,d,h,c,u;for(s+=8+n,a.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s],0),o=0;o<r;o++)l=i[o],d=l.duration,h=l.size,c=l.flags,u=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,255&d,h>>>24&255,h>>>16&255,h>>>8&255,255&h,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*o);return t.box(t.types.trun,a)}static initSegment(e){t.types||t.init();const s=t.moov(e);return Fr(t.FTYP,s)}static hvc1(e){const s=e.params,i=[e.vps,e.sps,e.pps],r=new Uint8Array([1,s.general_profile_space<<6|(s.general_tier_flag?32:0)|s.general_profile_idc,s.general_profile_compatibility_flags[0],s.general_profile_compatibility_flags[1],s.general_profile_compatibility_flags[2],s.general_profile_compatibility_flags[3],s.general_constraint_indicator_flags[0],s.general_constraint_indicator_flags[1],s.general_constraint_indicator_flags[2],s.general_constraint_indicator_flags[3],s.general_constraint_indicator_flags[4],s.general_constraint_indicator_flags[5],s.general_level_idc,240|s.min_spatial_segmentation_idc>>8,255&s.min_spatial_segmentation_idc,252|s.parallelismType,252|s.chroma_format_idc,248|s.bit_depth_luma_minus8,248|s.bit_depth_chroma_minus8,0,parseInt(s.frame_rate.fps),3|s.temporal_id_nested<<2|s.num_temporal_layers<<3|(s.frame_rate.fixed?64:0),i.length]);let n=r.length;for(let t=0;t<i.length;t+=1){n+=3;for(let e=0;e<i[t].length;e+=1)n+=2+i[t][e].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=i.length-1;for(let t=0;t<i.length;t+=1){a.set(new Uint8Array([32+t|(t===o?128:0),0,i[t].length]),n),n+=3;for(let e=0;e<i[t].length;e+=1)a.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),n),n+=2,a.set(i[t][e],n),n+=i[t][e].length}const l=t.box(t.types.hvcC,a),d=e.width,h=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return t.box(t.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,d>>8&255,255&d,h>>8&255,255&h,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,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}}).types=void 0,Me.HDLR_TYPES=void 0,Me.STTS=void 0,Me.STSC=void 0,Me.STCO=void 0,Me.STSZ=void 0,Me.VMHD=void 0,Me.SMHD=void 0,Me.STSD=void 0,Me.FTYP=void 0,Me.DINF=void 0,Oe=9e4,Fe=null,$e=null,Ne=class extends K{constructor(t,e,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===Fe){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fe=t?parseInt(t[1]):0}if(null===$e){const t=navigator.userAgent.match(/Safari\/(\d+)/i);$e=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?yo(e):e} > ${t?yo(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t[0].pts,i=t.reduce((t,i)=>{let r=i.pts,n=r-t;return n<-4294967296&&(e=!0,r=To(r,s),n=r-t),n>0?t:r},s);return e&&this.debug("PTS rollover detected"),i}remux(t,e,s,i,r,n,a,o){let l,d,h,c,u,f,g=r,m=r;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,I;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(A=t.pixelRatio)?void 0:A[0])||(null==(L=e.pixelRatio)?void 0:L[1])!==(null==(I=t.pixelRatio)?void 0:I[1]))||!t&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,r,n));const s=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const s=this.getVideoStartPts(e.samples),i=(To(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,r,n)),d=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===U.AUDIO?m:void 0),T){const i=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,s,i)}}else T&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=So(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Ao(i,r,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:c,id3:u}}computeInitPts(t,e,s,i){const r=Math.round(s*e);let n=To(t,r);if(n<r+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${i}`);n<r+e;)n+=8589934592;return n-r}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,c,u=!l||i,f="audio/mp4",g=-1;if(u&&(d=h=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Me.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(g=t.id,c=t.inputTimeScale,l&&c===l.timescale?u=!1:d=h=this.computeInitPts(r[0].pts,c,s,"audio"))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Me.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(g=e.id,c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=To(n[0].dts,t),i=this.computeInitPts(e,c,s,"video"),r=this.computeInitPts(t,c,s,"video");h=Math.min(h,i),d=Math.min(d,r)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/c} (${d}/${c}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:c,trackId:g},this._initDTS={baseTime:h,timescale:c,trackId:g}):d=c=void 0,{tracks:o,initPTS:d,timescale:c,trackId:g}}remuxVideo(t,e,s,i){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let h,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!s||null===u){const t=d+e*r,i=n[0].pts-To(n[0].dts,n[0].pts);Fe&&null!==u&&Math.abs(t-i-(u+d))<15e3?s=!0:u=t-i-d}const y=u+d;for(let M=0;M<o;M++){const t=n[M];t.pts=To(t.pts,y),t.dts=To(t.dts,y),t.dts<n[M>0?M-1:M].dts&&(v=!0)}v&&n.sort(function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i}),h=n[0].dts,c=n[n.length-1].dts;const E=c-h,T=E?Math.round(E/(o-1)):g||t.inputTimeScale/30;if(s){const s=h-y,i=s>T,r=s<-1;if((i||r)&&(i?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${vo(s,!0)} ms (${s}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${vo(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||y>=n[0].pts||Fe)){h=y;const t=n[0].pts-s;if(i)n[0].dts=h,n[0].pts=t;else{let e=!0;for(let i=0;i<n.length&&!(n[i].dts>t&&e);i++){const t=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i<n.length-1){const s=n[i+1].pts;e=s<=n[i].pts==s<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${vo(t,!0)}/${vo(h,!0)}, delta: ${vo(s,!0)} ms`)}}h=Math.max(0,h);let S=0,A=0,L=h;for(let M=0;M<o;M++){const t=n[M],e=t.units,s=e.length;let i=0;for(let r=0;r<s;r++)i+=e[r].data.length;A+=i,S+=s,t.length=i,t.dts<L?(t.dts=L,L+=T/4|0||1):L=t.dts,m=Math.min(t.pts,m),p=Math.max(t.pts,p)}c=n[o-1].dts;const I=A+4*S+8;let b;try{b=new Uint8Array(I)}catch(x){return void this.observer.emit($.ERROR,$.ERROR,{type:O.MUX_ERROR,details:F.REMUX_ALLOC_ERROR,fatal:!1,error:x,bytes:I,reason:`fail allocating video mdat ${I}`})}const R=new DataView(b.buffer);R.setUint32(0,I),b.set(Me.types.mdat,4);let k=!1,D=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY;for(let M=0;M<o;M++){const t=n[M],e=t.units;let s,l=0;for(let i=0,r=e.length;i<r;i++){const t=e[i],s=t.data,r=t.data.byteLength;R.setUint32(f,r),f+=4,b.set(s,f),f+=r,l+=4+r}if(M<o-1)g=n[M+1].dts-t.dts,s=n[M+1].pts-t.pts;else{const e=this.config,a=M>0?t.dts-n[M-1].dts:T;if(s=M>0?t.pts-n[M-1].pts:T,e.stretchShortVideoTrack&&null!==this.nextAudioTs){const s=Math.floor(e.maxBufferHole*r),n=(i?m+i*r:this.nextAudioTs+d)-t.pts;n>s?(g=n-a,g<0?g=a:k=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const h=Math.round(t.pts-t.dts);D=Math.min(D,g),P=Math.max(P,g),w=Math.min(w,s),_=Math.max(_,s),a.push(Eo(t.key,g,l,h))}if(a.length)if(Fe){if(Fe<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if($e&&_-w<P-D&&T/P<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=h;for(let e=0,s=a.length;e<s;e++){const i=t+a[e].duration,r=t+a[e].cts;if(e<s-1){const t=i+a[e+1].cts;a[e].duration=t-r}else a[e].duration=e?a[e-1].duration:T;a[e].cts=0,t=i}}g=k||!g?T:g,this.nextVideoTs=u=c+g-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const C={data1:Me.moof(t.sequenceNumber++,h,or(t,{samples:a})),data2:b,startPTS:(m-d)/r,endPTS:(p+g-d)/r,startDTS:(h-d)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,C}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,s,i,r){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,d=this._initPTS,h="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=t.samples,g=h?0:8,m=this.nextAudioTs||-1;const p=d.baseTime*n/d.timescale,v=p+e*n;if(this.isAudioContiguous=s=s||f.length&&m>0&&(i&&Math.abs(v-(m+p))<9e3||Math.abs(To(f[0].pts,v)-(m+p))<20*l),f.forEach(function(t){t.pts=To(t.pts,v)}),!s||m<0){const t=f.length;if(f=f.filter(t=>t.pts>=0),t!==f.length&&this.warn(`Removed ${f.length-t} of ${t} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===r?0:i&&!u?Math.max(0,v-p):f[0].pts-p}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=m+p;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,d=Math.abs(1e3*o/n);if(o<=-e*l&&u)0===s&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=m=a-p,i=a);else if(o>=e*l&&d<1e4&&u){let e=Math.round(o/l);for(i=a-e*l;i<0&&e&&l;)e--,i+=l;0===s&&(this.nextAudioTs=m=i-p),this.warn(`Injecting ${e} audio frames @ ${((i-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){let e=Ce.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),f.splice(s,0,{unit:e,pts:i}),i+=l,s++}}r.pts=i,i+=l}}let y,E=null,T=null,S=0,A=f.length;for(;A--;)S+=f[A].unit.byteLength;for(let P=0,_=f.length;P<_;P++){const e=f[P],i=e.unit;let r=e.pts;if(null!==T)c[P-1].duration=Math.round((r-T)/a);else{if(s&&"aac"===t.segmentCodec&&(r=m+p),E=r,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(w){return void this.observer.emit($.ERROR,$.ERROR,{type:O.MUX_ERROR,details:F.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:S,reason:`fail allocating audio mdat ${S}`})}h||(new DataView(y.buffer).setUint32(0,S),y.set(Me.types.mdat,4))}y.set(i,g);const n=i.byteLength;g+=n,c.push(Eo(!0,o,n,0)),T=r}const L=c.length;if(!L)return;const I=c[c.length-1];m=T-p,this.nextAudioTs=m+a*I.duration;const b=h?new Uint8Array(0):Me.moof(t.sequenceNumber++,E/a,or({},t,{samples:c}));t.samples=[];const R=(E-p)/n,k=this.nextAudioTs/n,D={data1:b,data2:y,startPTS:R,endPTS:k,startDTS:R,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,D}},Ue=class extends K{constructor(t,e,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(t,i),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:s,videoCodec:i}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=Dr(t);if(e)!function(t,e){if(!t||!e)return;const s=e.keyId;s&&e.isCommonEncryption&&Mr(t,(t,e)=>{const i=t.subarray(8,24);i.some(t=>0!==t)||(Y.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${mr(i)} -> ${mr(s)}`),t.set(s,8))})}(t,e);else{const t=r||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(s=Io(r,Q.AUDIO,this)),n&&(i=Io(n,Q.VIDEO,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:r?a.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,e,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};C(d)||(d=this.lastEndTime=r||0);const c=e.samples;if(!c.length)return h;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e,s){const i={},r=Rr(t,["moof","traf"]);for(let n=0;n<r.length;n++){const t=r[n],a=Rr(t,["tfhd"])[0],o=Lr(a,4),l=e[o];if(!l)continue;i[o]||(i[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=i[o],h=Rr(t,["tfdt"])[0];if(h){const t=h[0];let e=Lr(h,4);1===t&&(e===et?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=et+1,e+=Lr(h,8))),C(e)&&(!C(d.start)||e<d.start)&&(d.start=e)}const c=l.default,u=Lr(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=Lr(a,2&u?12:8));const g=Rr(t,["trun"]);let m=d.start||0,p=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],s=Lr(t,4),i=d.sampleCount;d.sampleCount+=s;const r=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],h=8&t[2];let c=8,u=s;for(r&&(c+=4),n&&s&&(1&t[c+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=i),c+=4,a?(v=Lr(t,c),c+=4):v=f,o&&(c+=4),h&&(c+=4),m+=v,p+=v,u--);u--;)a?(v=Lr(t,c),c+=4):v=f,o&&(c+=4),l&&(1&t[c+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(u+1),d.keyFrameStart=m),c+=4),h&&(c+=4),m+=v,p+=v;!p&&f&&(p+=f*s)}d.duration+=p}if(!Object.keys(i).some(t=>i[t].duration)){let e=1/0,s=0;const r=Rr(t,["sidx"]);for(let t=0;t<r.length;t++){const i=kr(r[t]);if(null!=i&&i.references){e=Math.min(e,i.earliestPresentationTime/i.timescale);const t=i.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+i.earliestPresentationTime/i.timescale)}}s&&C(s)&&Object.keys(i).forEach(t=>{i[t].duration||(i[t].duration=s*i[t].timescale-i[t].start)})}return i}(c,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,v=Lo(p,1/0),y=Lo(m,1/0),E=Lo(p,0,!0),T=Lo(m,0,!0);let S=r,A=0;const L=m&&(!p||!l&&y<v||l&&l.trackId===f.audio.id),I=L?m:p;if(I){const t=I.timescale,e=I.start-r*t,s=L?f.audio.id:f.video.id;S=I.start/t,A=L?T-y:E-v,!n&&l||!function(t,e,s,i){if(null===t)return!0;const r=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>r}(l,S,r,A)&&t===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${e/t} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${S-r} (${e}/${t}) trackId: ${s}`),l=null,u.initPTS=e,u.timescale=t,u.trackId=s)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=S,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const b=S-l.baseTime/l.timescale,R=b+A;A>0?this.lastEndTime=R:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const k=!!f.audio,D=!!f.video;let w="";k&&(w+="audio"),D&&(w+="video");const P={data1:c,startPTS:b,startDTS:b,endPTS:R,endDTS:R,type:w,hasAudio:k,hasVideo:D,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=k&&!D?P:void 0,h.video=D?P:void 0;const _=null==p?void 0:p.sampleCount;if(_){const t=p.keyFrameIndex,e=-1!==t;P.nb=_,P.dropped=0===t||this.isVideoContiguous?0:e?t:_,P.independent=e,P.firstKeyFrame=t,e&&p.keyFrameStart&&(P.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),P.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${_} dropped: ${P.dropped} start: ${P.firstKeyFramePTS||"NA"}`)}return h.initSegment=u,h.id3=So(s,r,l,l),i.samples.length&&(h.text=Ao(i,r,l)),h}};try{Be=self.performance.now.bind(self.performance)}catch(nr){Be=Date.now}(Ge=[{demux:Ie,remux:Ue},{demux:_e,remux:Ne},{demux:Ee,remux:Ne},{demux:Ae,remux:Ne}]).splice(2,0,{demux:Se,remux:Ne}),Ke=class{constructor(t,e,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=t,this.typeSupported=e,this.config=s,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,i){const r=s.transmuxing;r.executeStart=Be();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,E=function(t,e){let s=null;return t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e),s}(n,e);if(E&&Wn(E.method)){const t=this.getDecrypter(),e=Yn(E.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,e).then(t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e}),this.decryptionPromise;{let i=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer,e);if(s.part>-1){const e=t.flush();i=e?e.buffer:e}if(!i)return r.executeEnd=Be(),Ve(s);n=new Uint8Array(i)}}const T=this.needsProbing(d,h);if(T){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit($.ERROR,$.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=Be(),Ve(s)}(d||h||f||T)&&this.resetInitSegment(y,g,m,v,e),(d||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,u,c,s);this.asyncResult=bo(S);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Be(),S}flush(t){const e=t.transmuxing;e.executeStart=Be();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Be();const s=[Ve(t)];return this.asyncResult?Promise.resolve(s):s}const d=o.flush(a);return bo(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===U.MAIN?"level":"track"} ${s.level}`);const d=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=Be()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,i,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer.demuxSampleAes(t,e,s).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i}=this;let r;for(let h=0,c=Ge.length;h<c;h++){var n;if(null!=(n=Ge[h].demux)&&n.probe(t,this.logger)){r=Ge[h];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;o&&o instanceof l||(this.remuxer=new l(s,e,i,this.logger)),a&&a instanceof d||(this.demuxer=new d(s,e,i,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Dt(this.config)),t}},Ve=t=>({remuxResult:{},chunkMeta:t}),He=class{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}},We=class{constructor(t,e,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}},Ye=0,je=class{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ye++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,s=this.hls;if(s&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":s.logger[e.data.logType]&&s.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,s.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===$.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new ae,this.observer.on($.FRAG_DECRYPTED,n),this.observer.on($.ERROR,n);const a=tn(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=le[t];if(e)return e.clientCount++,e;const s=new self.URL(t,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return le[t]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=le[oe];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(e),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return le[oe]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:pt(r)})}catch(nr){s.warn(`Error setting up "${e}" Web Worker, fallback to inline`,nr),this.terminateWorker(),this.error=null,this.transmuxer=new Ke(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new Ke(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Ye++;const e=this.hls.config,s=tn(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:pt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=le[t||oe];if(e&&1===e.clientCount--){const{worker:s,objectURL:i}=e;delete le[t||oe],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!(p&&r.cc===p.cc),y=!(p&&l.level===p.level),E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!y&&(1===E||0===E&&(1===T||S&&T<=0)),L=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!T&&A||(n.stats.parsing.start=L);const I=!(p&&(null==(h=r.initSegment)?void 0:h.url)===(null==(c=p.initSegment)?void 0:c.url)),b=new We(v,A,o,y,g,I);if(!A||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===U.MAIN?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const t=new He(s,i,e,a,d);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,b);bo(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(s){const e=s.flush(t);bo(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}},qe=class extends se{constructor(t,e,s){super(t,e,s,"audio-stream-controller",U.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:t}=this;t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on($.BUFFER_RESET,this.onBufferReset,this),t.on($.BUFFER_CREATED,this.onBufferCreated,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on($.FRAG_LOADING,this.onFragLoading,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off($.BUFFER_RESET,this.onBufferReset,this),t.off($.BUFFER_CREATED,this.onBufferCreated,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off($.FRAG_LOADING,this.onFragLoading,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r,trackId:n}){if(s===U.MAIN){const t=e.cc,s=this.fragCurrent;if(this.initPTS[t]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${t} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=e,this.state===ee.WAITING_INIT_PTS){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==t)&&this.syncWithAnchor(e,null==s?void 0:s.frag)}else!this.hls.hasEnoughToStart&&s&&s.cc!==t?(s.abortRequests(),this.syncWithAnchor(e,s)):this.state===ee.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(e&&(null==i?void 0:i.cc)===e.cc)return;const r=(i||t).cc,n=An(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===ee.IDLE&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=ee.STOPPED);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s,this.state=ee.IDLE):this.state=ee.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case ee.IDLE:this.doTickIdle();break;case ee.WAITING_TRACK:{const{levels:t,trackId:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=ee.WAITING_INIT_PTS}break}case ee.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case ee.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=ee.FRAG_LOADING;const t={frag:e,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=ee.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:s,media:i,trackId:r}=this,n=e.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=ee.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Q.AUDIO,U.AUDIO));const d=this.getFwdBufferInfo(l,U.AUDIO);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return e.trigger($.BUFFER_EOS,{type:"audio"}),void(this.state=ee.ENDED);const h=d.len,c=e.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:d.end;if(this.switchingTrack&&i){const t=g;o.PTSKnown&&t<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(h>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,d,U.MAIN,c)),!p)return void(this.bufferFlushed=!0);let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&yr(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===At.OK&&(this.mainFragLoading=v=null),v&&yr(v))){if(p.start>v.end){const t=this.fragmentTracker.getFragAtPos(m,U.MAIN);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new gt(t))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==ee.STOPPED&&(this.setInterval(100),this.state=ee.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded($.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,e){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=e;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==ee.STOPPED&&(this.state=ee.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=i[n];let h=0;if(r.live||null!=(s=d.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;d.details&&(h=this.alignPlaylists(r,d.details,null==(c=this.levelLastLoaded)?void 0:c.details)),r.alignedSliding||(wa(r,l),r.alignedSliding||Pa(r,l),h=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger($.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==ee.WAITING_TRACK||this.waitForCdnTuneIn(r)||(this.state=ee.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const h=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new je(this.hls,U.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new xt(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n);c.push(r,f,h,"",s,i,d.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new ie,complete:!1};t.push(new Uint8Array(r)),this.state!==ee.STOPPED&&(this.state=ee.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===U.MAIN&&yr(e.frag)&&(this.mainFragLoading=e,this.state===ee.IDLE&&this.tick())}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===U.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(yr(s)){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger($.AUDIO_TRACK_SWITCHED,dr({},t)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==U.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var s;if(e.fatal)this.state=ee.ERROR;else switch(e.details){case F.FRAG_GAP:case F.FRAG_PARSING_ERROR:case F.FRAG_DECRYPT_ERROR:case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.AUDIO,e);break;case F.AUDIO_TRACK_LOAD_ERROR:case F.AUDIO_TRACK_LOAD_TIMEOUT:case F.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ee.WAITING_TRACK||(null==(s=e.context)?void 0:s.type)!==N.AUDIO_TRACK||(this.state=ee.IDLE);break;case F.BUFFER_ADD_CODEC_ERROR:case F.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case F.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case F.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Q.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Q.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ee.ENDED&&(this.state=ee.IDLE);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,U.AUDIO),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:h}=d,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&h){if(this.state=ee.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,t,n),i.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}if(c){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[Q.AUDIO]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(Q.AUDIO,t,e,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=or({id:s,frag:o,details:h},f);i.trigger($.FRAG_PARSING_METADATA,t)}if(u){const t=or({id:s,frag:o,details:h},u);i.trigger($.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s,i){if(this.state!==ee.PARSING)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=U.AUDIO;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger($.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger($.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||i===At.NOT_LOADED||i===At.PARTIAL)if(yr(t))if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=ee.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==e.details.fragmentStart&&Pa(e.details,s)}else super.loadFragment(t,e,s);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;mn({name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},t,pn)||(yn(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger($.AUDIO_TRACK_SWITCHED,dr({},t))}},ze=class extends K{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let n=-1;for(let s=0;s<i.length;s++){const a=i[s];let o;try{o=new self.URL(a.URI,e.url).href}catch(r){this.warn(`Could not construct new URL for Rendition Report: ${r}`),o=a.URI||""}if(o===t){n=s;break}o===t.substring(0,o.length)&&(n=s)}if(-1!==n){const t=i[n],r=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=s&&ln(s);return new ft(r,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return t}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const t=Math.max(o||0,0);i.appliedTimelineOffset=t,i.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(i.live||null!=s&&s.live){const o="levelInfo"in e?e.levelInfo:e.track;if(i.reloaded(s),s&&i.fragments.length>0){ma(s,i,this);const t=i.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=e;return void s.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,c=Ea(i,1e3*(i.edge-h));if(i.requestScheduled+c<n?i.requestScheduled=n:i.requestScheduled+=c,this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let u,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,d=r===a;-1!==l?d?(f=a+1,g=t?0:l):(f=r,g=t?l+1:i.maxPartIndex):f=a+1;const h=i.age,c=h+i.ageHeader;let m=Math.min(c-i.partTarget,1.5*i.targetduration);if(m>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${m} with playlist age: ${i.age}`),m=0;else{const t=Math.floor(m/i.targetduration);f+=t,void 0!==g&&(g+=Math.round(m%i.targetduration/i.partTarget)),this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${m} skip sn ${t} to part ${g}`)}i.tuneInGoal=m}if(u=this.getDeliveryDirectives(i,e.deliveryDirectives,f,g),t||!d)return i.requestScheduled=n,void this.loadingPlaylist(o,u)}else(i.canBlockReload||i.canSkipUntil)&&(u=this.getDeliveryDirectives(i,e.deliveryDirectives,f,g));u&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,i)}else this.clearTimer()}scheduleLoading(t,e,s){const i=s||t.details;if(!i)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,s,i){let r=ln(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=ut.No),new ft(s,i,r)}checkRetry(t){const e=t.details,s=Ln(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Et.RetryRequest||!i.resolved&&r===Et.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=kn(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}},Xe=class extends ze{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVEL_LOADING,this.onLevelLoading,this),t.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off($.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=gn(e,t,pn);if(s>-1)r=t[s];else{const t=gn(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger($.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==N.AUDIO_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&mn(t,i,pn))return i;const r=gn(t,this.tracksInGroup,pn);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=vn(e,i,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==d)return!1;const i=e.audioGroups;return gn(t,s.filter(t=>!i||-1!==i.indexOf(t.groupId)),r)>-1});return h>-1?h:vn(e,i,e=>{const i=e.audioGroups;return gn(t,s.filter(t=>!i||-1!==i.indexOf(t.groupId)),r)>-1})}(t,e.levels,s,i,pn);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=gn(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t],r=i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger($.AUDIO_TRACK_SWITCHING,dr({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if((!this.selectDefaultTrack||i.default)&&(!t||mn(t,i,pn)))return s}if(t){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++)if(mn({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],pn))return t;for(let l=0;l<e.length;l++){const s=e[l];if(ko(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<e.length;l++){const s=e[l];if(ko(t.attrs,s.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&yn(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger($.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}},Qe=class{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const s={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const s={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const s=null==(e=t[0])?void 0:e.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){null!==this.queues&&this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const r=e[0];try{r.execute()}catch(i){var s;if(r.onError(i),null===this.queues||null===this.tracks)return;const e=null==(s=this.tracks[t])?void 0:s.buffer;null!=e&&e.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,s;return null!=(e=this.queues)&&e[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const s=null==(e=this.tracks)?void 0:e[t],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}},Ze=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Je="HlsJsTrackRemovedError",ts=class extends Error{constructor(t){super(t),this.name=Je}},es=class extends K{constructor(t,e){var s;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:s}=this;t&&this.log("Media source opened"),e&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger($.MEDIA_ATTACHED,{media:e,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(s=ur(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.BUFFER_RESET,this.onBufferReset,this),t.on($.BUFFER_APPENDING,this.onBufferAppending,this),t.on($.BUFFER_CODECS,this.onBufferCodecs,this),t.on($.BUFFER_EOS,this.onBufferEos,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.FRAG_PARSED,this.onFragParsed,this),t.on($.FRAG_CHANGED,this.onFragChanged,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.BUFFER_RESET,this.onBufferReset,this),t.off($.BUFFER_APPENDING,this.onBufferAppending,this),t.off($.BUFFER_CODECS,this.onBufferCodecs,this),t.off($.BUFFER_EOS,this.onBufferEos,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.FRAG_PARSED,this.onFragParsed,this),t.off($.FRAG_CHANGED,this.onFragChanged,this),t.off($.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const s={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===e?or(s,i.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(s[e]=or({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var s;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const s=this.media=e.media;this.transferData=this.overrides=void 0;const i=ur(this.appendSource);if(i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const n=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(n),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&n instanceof e,wo(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,t),s.load()}catch(r){s.src=t}else s.src=t}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,s;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const s=this.tracks,i=e.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${pt(s,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${pt(i,(t,e)=>"initSegment"===t?void 0:e)}}`),!fr(i,s)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching($.MEDIA_DETACHING,{}),this.onMediaAttaching($.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach(t=>{const e=t,s=i[e];if(s){const t=s.buffer;if(t){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=Ot.getBuffered(t);i.detectEvictedFragments(e,s,r,null,!0)}const n=Po(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const s=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let s=e.length;s--;)t&&e[s].abort(),r.removeSourceBuffer(e[s]);t&&r.endOfStream()}catch(nr){this.warn(`onMediaDetaching: ${nr.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&&wo(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger($.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(nr){this.warn(`onBufferReset ${t}`,nr)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Po(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Qe(this.tracks)}onBufferCodecs(t,e){var s;const i=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!i[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var s,r;const{id:n,codec:a,levelCodec:o,container:l,metadata:d,supplemental:h}=e[t];let c=i[t];const u=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[t],f=null!=u&&u.buffer?u:c,g=(null==f?void 0:f.pendingCodec)||(null==f?void 0:f.codec),m=null==f?void 0:f.levelCodec;c||(c=i[t]={buffer:void 0,listeners:[],codec:a,supplemental:h,container:l,levelCodec:o,metadata:d,id:n});const p=Qr(g,m),v=null==p?void 0:p.replace(Ze,"$1");let y=Qr(a,o);const E=null==(r=y)?void 0:r.replace(Ze,"$1");y&&p&&v!==E&&("audio"===t.slice(0,5)&&(y=Xr(y,this.appendSource)),this.log(`switching codec ${g} to ${y}`),y!==(c.pendingCodec||c.codec)&&(c.pendingCodec=y),c.container=l,this.appendChangeType(t,l,y))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(s=e.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const s=this.tracks[e];return t[e]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t},{})}appendChangeType(t,e,s){const i=`${e};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const s=t.start,i=s+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,U.MAIN))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>i||null!=e&&e.buffer&&Ot.isBuffered(e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,U.MAIN))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=e,h=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();h.start=f;const g=a.stats.buffering,m=o?o.stats.buffering:null;0===g.start&&(g.start=f),m&&0===m.start&&(m.start=f);const p=s.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==p?void 0:p.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=s.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==c){const t=o||a,e=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const s=t.end;if(e){const t=e.frag.start;(s>t||s<this.lastVideoAppendEnd||Ot.isBuffered(E,t))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const e=t.start+.05*t.duration,s=E.buffered,i=this.currentOp("video");s.length||i?!i&&!Ot.isBuffered(E,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const T=(o||a).start,S={label:`append-${r}`,execute:()=>{var t;h.executeStart=self.performance.now();const e=null==(t=this.tracks[r])?void 0:t.buffer;e&&(v?this.updateTimestampOffset(e,T,.1,r,c,u):void 0!==d&&C(d)&&this.updateTimestampOffset(e,d,1e-6,r,c,u)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();h.executeEnd=h.end=t,0===g.first&&(g.first=t),m&&0===m.first&&(m.first=t);const e={};this.sourceBuffers.forEach(([t,s])=>{t&&(e[t]=Ot.getBuffered(s))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger($.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:e})},onError:t=>{var e;const s={type:O.MEDIA_ERROR,parent:a.type,details:F.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},i=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)s.details=F.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)s.errorAction=_n(!0);else if(t.name===Je&&0===this.sourceBufferCount)s.errorAction=_n(!0);else{const t=++this.appendErrors[r];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${i||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||i)&&(s.fatal=!0)}this.hls.trigger($.ERROR,s)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===U.MAIN?"level":"track"} ${a.level} cc: ${u}`),this.append(S,r,this.isPending(this.tracks[r]))}getFlushOp(t,e,s){return this.log(`queuing "${t}" remove ${e}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger($.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove ${e}-${s} from "${t}" SourceBuffer`,i)}}}onBufferFlushing(t,e){const{type:s,startOffset:i,endOffset:r}=e;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,i,r),t)})}onFragParsed(t,e){const{frag:s,part:i}=e,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[Q.AUDIOVIDEO]?r.push("audiovideo"):(n[Q.AUDIO]&&r.push("audio"),n[Q.VIDEO]&&r.push("video")),0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.hls.trigger($.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type})},r).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var s;this.sourceBuffers.forEach(([t])=>{if(t){const s=this.tracks[t];e.type&&e.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger($.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger($.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===F.BUFFER_APPEND_ERROR&&e.frag){var s;const t=null==(s=e.errorAction)?void 0:s.nextAutoLevel;C(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||null===e)return;if(!this.sourceBufferCount)return;const i=t.config,r=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(C(a)&&a>=0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}const o=i.frontBufferFlushThreshold;if(C(o)&&o>0){const t=Math.max(i.maxBufferLength,o),e=Math.max(t,n),s=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(t,e,s){this.sourceBuffers.forEach(([t,e])=>{if(e){const r=Ot.getBuffered(e);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger($.BACK_BUFFER_REACHED,{bufferEnd:s});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger($.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}})}flushFrontBuffer(t,e,s){this.sourceBuffers.forEach(([e,i])=>{if(i){const r=Ot.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||t>=a&&t<=o)return;this.hls.trigger($.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:s}=this;if(!e||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,i)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return C(r)?{duration:r}:null;const n=this.media.duration;return i>(C(s.duration)?s.duration:0)&&i>n||!C(n)?{duration:i}:null}updateMediaSource({duration:t,start:e,end:s}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==t&&(C(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),i.duration=t),void 0!==e&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${e}-${s}.`),i.setLiveSeekableRange(e,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${pt(s)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,s])=>{if(e){const i=this.tracks[e];t[e]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger($.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in t){const a=n,o=t[a];if(this.isPending(o)){const t=this.getTrackCodec(o,a),n=`${o.container};codecs=${t}`;o.codec=t,this.log(`creating sourceBuffer(${n})${this.currentOp(a)?" Queued":""} ${pt(o)}`);try{const t=s.addSourceBuffer(n);e[Po(a)]=[a,t],o.buffer=t}catch(r){var i;return this.error(`error while trying to add sourceBuffer: ${r.message}`),this.shiftAndExecuteNext(a),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[a],void this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:r,sourceBufferName:a,mimeType:n,parent:o.id})}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(t,e){const s=t.supplemental;let i=t.codec;s&&("video"===e||"audiovideo"===e)&&Wr(s,"video")&&(i=function(t,e){const s=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)Hr(e[t],"video")||s.push(e[t])}return e&&s.push(e),s.join(",")}(i,s));const r=Qr(i,t.levelCodec);return r?"audio"===e.slice(0,5)?Xr(r,this.appendSource):r:""}trackSourceBuffer(t,e){const s=e.buffer;if(!s)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:s,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger($.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const s=this.currentOp(t);s&&(s.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const r=this.currentOp(t);r&&r.onError(i)}updateTimestampOffset(t,e,s,i,r,n){const a=e-t.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,s){const{media:i,mediaSource:r}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!i||!r||!a)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=C(i.duration)?i.duration:1/0,l=C(r.duration)?r.duration:1/0,d=Math.max(0,e),h=Math.min(s,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${t} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.tracks[e],i=null==s?void 0:s.buffer;if(!i)throw new ts(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:s}=this,i=e.map(t=>this.appendBlocker(t));return e.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(e=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;s&&!s.updating&&this.shiftAndExecuteNext(t)})}append(t,e,s){this.operationQueue&&this.operationQueue.append(t,e,s)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,s){const i=this.tracks[t];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,t);i.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const s=e.buffer;s&&(e.listeners.forEach(t=>{s.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}},ss=class t{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.BUFFER_CODECS,this.onBufferCodecs,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.BUFFER_CODECS,this.onBufferCodecs,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&C(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(e){const s=this.hls.levels;if(!s.length)return-1;const i=s.filter((t,s)=>this.isLevelAllowed(t)&&s<=e);return this.clientRect=null,t.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(e){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,s){if(null==t||!t.length)return-1;const i=(t,e)=>!e||t.width!==e.width||t.height!==e.height;let r=t.length-1;const n=Math.max(e,s);for(let a=0;a<t.length;a+=1){const e=t[a];if((e.width>=n||e.height>=n)&&i(e,t[a+1])){r=a;break}}return r}},is={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},rs={HLS:"h"},ns=class t{constructor(e,s){Array.isArray(e)&&(e=e.map(e=>e instanceof t?e:new t(e))),this.value=e,this.params=s}},as="Dict",os=class{constructor(t){this.description=t}},ls="Bare Item",ds="Boolean",hs="Byte Sequence",cs="Integer",us="Decimal",fs="String",gs=/[\x00-\x1f\x7f]+/,ms="Token",ps="Key",Ss={br:vs="CMCD-Object",ab:vs,d:vs,ot:vs,tb:vs,tpb:vs,lb:vs,tab:vs,lab:vs,url:vs,pb:ys="CMCD-Request",bl:ys,tbl:ys,dl:ys,ltc:ys,mtp:ys,nor:ys,nrr:ys,rc:ys,sn:ys,sta:ys,su:ys,ttfb:ys,ttfbb:ys,ttlb:ys,cmsdd:ys,cmsds:ys,smrt:ys,df:ys,cs:ys,ts:ys,cid:Es="CMCD-Session",pr:Es,sf:Es,sid:Es,st:Es,v:Es,msd:Es,bs:Ts="CMCD-Status",bsd:Ts,cdn:Ts,rtp:Ts,bg:Ts,pt:Ts,ec:Ts,e:Ts},As={REQUEST:ys},Ls="event",bs=(t,e)=>Array.isArray(t)?t.map(t=>bs(t,e)):t instanceof ns&&"string"==typeof t.value?new ns(bs(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const s=new URL(t),i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),Rs=t=>100*Is(t/100),ks={br:Is=t=>Math.round(t),d:Is,bl:Rs,dl:Rs,mtp:Rs,nor:(t,e)=>{let s=t;return e.version>=2&&(t instanceof ns&&"string"==typeof t.value?s=new ns([t]):"string"==typeof t&&(s=[t])),bs(s,e)},rtp:Rs,tb:Is},Ds="request",ws="response",Ps=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],_s=["e"],Cs=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/,xs=["d","dl","nor","ot","rtp","su"],Ms=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Os=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Fs={[ws]:qo,[Ls]:Yo,[Ds]:jo},$s="CMCD",Ns=/CMCD=[^&#]+/,Us=class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:is.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=t=>{try{const{frag:e,part:s}=t,i=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*(s||e).duration,ot:r};r!==is.VIDEO&&r!==is.AUDIO&&r!=is.MUXED||(n.br=i.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=s?this.getNextPart(s):this.getNextFrag(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||t.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHED,this.onMediaDetached,this),t.on($.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHED,this.onMediaDetached,this),t.off($.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,i;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer}createData(){var t;return{v:1,sf:rs.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){or(e,this.createData());const s=e.ot===is.INIT||e.ot===is.VIDEO||e.ot===is.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce((t,s)=>(i.includes(s)&&(t[s]=e[s]),t),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),Qo(t.headers,e,r)):t.url=Jo(t.url,e,r)}getNextFrag(t){var e;const s=null==(e=this.hls.levels[t.level])?void 0:e.details;if(s){const e=t.sn-s.startSN;return s.fragments[e+1]}}getNextPart(t){var e;const{index:s,fragment:i}=t,r=null==(e=this.hls.levels[i.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=i;for(let e=r.length-1;e>=0;e--){const i=r[e];if(i.index===s&&i.fragment.sn===t)return r[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?is.TIMED_TEXT:"initSegment"===t.sn?is.INIT:"audio"===e?is.AUDIO:"main"===e?this.hls.audioTracks.length?is.VIDEO:is.MUXED:void 0}getTopBandwidth(t){let e,s=0;const i=this.hls;if(t===is.AUDIO)e=i.audioTracks;else{const t=i.maxAutoLevel,s=t>-1?t+1:i.levels.length;e=i.levels.slice(0,s)}return e.forEach(t=>{t.bitrate>s&&(s=t.bitrate)}),s>0?s:NaN}getBufferLength(t){const e=this.media,s=t===is.AUDIO?this.audioBuffer:this.videoBuffer;return s&&e?1e3*Ot.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}},Bs=class extends K{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Et.SendAlternateToPenaltyBox&&s.flags===Tt.MoveAllAlternatesMatchingHost){const t=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),e.details!==F.BUFFER_APPEND_ERROR||e.fatal?s.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${pt(i)} penalized: ${pt(this.penalizedPathways)}`):s.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(t=>{i-s[t]>3e5&&delete s[t]});for(let r=0;r<t.length;r++){const i=t[r];if(i in s)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(i),e.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,La(e),this.hls.trigger($.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(e===N.AUDIO_TRACK&&i[r].hasAudioGroup(t)||e===N.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(t))return i[r].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new Ut(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=el(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new gt({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let s=1;s<t.audioGroups.length;s++)d.addGroupId("audio",`${t.audioGroups[s]}_clone_${r}`);if(t.subtitleGroups)for(let s=1;s<t.subtitleGroups.length;s++)d.addGroupId("text",`${t.subtitleGroups[s]}_clone_${r}`);return d});e.push(...o),tl(this.audioTracks,s,a,r),tl(this.subtitleTracks,i,a,r)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(e);try{i=new self.URL(t)}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:i.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger($.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},Gs=class t extends K{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.debug(i),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Jn(this.config));const e=t.map(Zn).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{const n=Qn(r);if("sinf"!==e||n!==Vt.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);let a;try{const t=Sr(new Uint8Array(s)),e=Or(jn(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24))}catch(c){return void this.warn(`${i} Failed to parse sinf: ${c}`)}const o=mr(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let h=l[o];for(let t=0;t<d.length;t++){const i=d[t],r=i.decryptdata;if(!r.keyId)continue;const n=mr(r.keyId);if(Vn(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(h=l[n],!h)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(s),r.keyId=a,h=l[o]=h.then(()=>this.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match")),h.catch(t=>this.handleError(t));break}}h||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on($.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off($.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=null==e?void 0:e[t];return i?i.licenseUrl:t===Vt.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=null==e?void 0:e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map(t=>t.audioCodec).filter(s),r=e.map(t=>t.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):s(e instanceof Ks?e:new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};n(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===Wt&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){var i;const r=function(t,e,s,i){let r;switch(t){case Vt.FAIRPLAY:r=["cenc","sinf"];break;case Vt.WIDEVINE:case Vt.PLAYREADY:r=["cenc"];break;case Vt.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${pt(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,i.then(e=>e?this.setMediaKeysServerCertificate(s,t,e):s)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${mr(t.keyId||[])} keyUri: ${t.uri}`);const i={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:s.createSession(),keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=sl(e),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${mr(t.decryptdata.keyId||[])}\n } (data length: ${e.byteLength})`),s.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Zn(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return new Promise((e,s)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const i=Zn(t);i?e(i):s(new Error(`Unable to find format for key-system "${t}"`))}).catch(s)})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=Jn(this.config),s=t.map(Qn).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(s)}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let s=0;s<e.length;s++){const i=il(t,e[s]);if(i)return i}}loadKey(t){const e=t.keyInfo.decryptdata,s=sl(e),i=this.bannedKeyIds[s];if(i||"internal-error"===this.getKeyStatus(e)){const s=rl(i||"internal-error",e);return this.handleError(s,t.frag),Promise.reject(s)}const r=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const i=this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:e}))))).then(t=>{const s=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",s,"playlist-key")});return i.catch(e=>this.handleError(e,t.frag)),this.keyIdToKeySessionPromise[s]=i,i}return n.catch(s=>{if(s instanceof Ks){const i=dr({},s.data);"internal-error"===this.getKeyStatus(e)&&(i.decryptdata=e);const r=new Ks(i,s.message);this.handleError(r,t.frag)}}),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof Ks){e&&(t.data.frag=e);const s=t.data.decryptdata;this.error(`${t.message}${s?` (${mr(s.keyId||[])})`:""}`),this.hls.trigger($.ERROR,t.data)}else this.error(t.message),this.hls.trigger($.ERROR,{type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=sl(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=Qn(t.keyFormat),s=e?[e]:Jn(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=Jn(this.config)),0===t.length)throw new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${pt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(s)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===s.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,s,i){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[t.keySystem])?void 0:r.generateRequest;if(n)try{const i=n.call(this.hls,e,s,t);if(!i)throw new Error("Invalid response from configured generateRequest filter");e=i.initDataType,s=i.initData?i.initData:null,t.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const a=sl(t.decryptdata),o=t.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${a} URI: ${o} (init data type: ${e} length: ${s.byteLength})`);const l=new ae,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void l.emit("error",new Error("invalid state"));const{messageType:i,message:r}=e;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(t,r).catch(t=>{l.eventNames().length?l.emit("error",t):this.handleError(t)}):"license-release"===i?t.keySystem===Vt.FAIRPLAY&&this.updateKeySession(t,qn("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${i}"`)},h=(t,e)=>{let s;e.keyStatus=t,t.startsWith("usable")?l.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?s=rl(t,e.decryptdata):"expired"===t?s=new Error(`key expired (keyId: ${a})`):"released"===t?s=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${a})`),s&&(l.eventNames().length?l.emit("error",s):this.handleError(s))},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const s=this.getKeyStatuses(t);if(!Object.keys(s).some(t=>"status-pending"!==s[t]))return;if("expired"===s[a])return this.log(`Expired key ${pt(s)} in key-session "${t.mediaKeysSession.sessionId}"`),void this.renewKeySession(t);let i=s[a];if(i)h(i,t);else{var r;const e=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(r=t.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const s=this.getKeyStatus(t.decryptdata);if(s&&"status-pending"!==s)return this.log(`No status for keyId ${a} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${s} from other session.`),h(s,t);this.log(`key status for ${a} in key-session "${t.mediaKeysSession.sessionId}" timed out after ${e}ms`),i="internal-error",h(i,t)},e)),this.log(`No status for keyId ${a} (${pt(s)}).`)}};_a(t.mediaKeysSession,"message",d),_a(t.mediaKeysSession,"keystatuseschange",c);const u=new Promise((t,e)=>{l.on("error",e),l.on("resolved",t)});return t.mediaKeysSession.generateRequest(e,s).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(e=>{throw new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>u).catch(e=>(l.removeAllListeners(),this.removeSession(t).then(()=>{throw e}))).then(()=>(l.removeAllListeners(),t))}getKeyStatuses(t){const e={};return t.mediaKeysSession.keyStatuses.forEach((s,i)=>{if("string"==typeof i&&"object"==typeof s){const t=i;i=s,s=t}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(t.keySystem===Vt.PLAYREADY&&16===r.length){const t=mr(r);e[t]=s,zn(r)}const n=mr(r);"internal-error"===s&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${t.mediaKeysSession.sessionId}"`),e[n]=s}),e}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};s.load(a,l,{onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:dr({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise((i,r)=>{t.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${e}"`),i(t)}).catch(t=>{r(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(e=>{throw new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s<i;s++){var n,a;e=r[s];const i=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;i&&o&&t.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return qn(atob(l))}setupLicenseXHR(t,e,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,s,i)}).then(s=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:s||i})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(o){this.error(o)}i(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Ks({type:O.KEY_SYSTEM_ERROR,details:F.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(i,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then(({xhr:e,licenseChallenge:s})=>{t.keySystem==Vt.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,_a(s,"encrypted",this.onMediaEncrypted),_a(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const t=this.media;t&&(Ca(t,"encrypted",this.onMediaEncrypted),Ca(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const s=this.mediaResolved;if(s&&s(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,jt.clearKeyUriToKeyIdMap();const n=r.length;t.CDMCleanupPromise=Promise.all(r.map(t=>this.removeSession(t)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s,decryptdata:i}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}" keyId: ${mr((null==i?void 0:i.keyId)||[])}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=t;n&&Object.keys(n).forEach(t=>self.clearTimeout(n[t]));const{drmSystemOptions:a}=this.config;return(function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(a)?new Promise((t,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(s)}):Promise.resolve()).catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}},Gs.CDMCleanupPromise=void 0,Ks=class extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}},Vs=class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off($.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger($.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger($.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},Hs=class extends ze{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=dl(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVEL_LOADING,this.onLevelLoading,this),t.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off($.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const s=this.media;if(!s)return;const i=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i||dl(s.textTracks).forEach(t=>{ol(t)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=gn(e,t);if(s>-1)r=t[s];else{const t=gn(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger($.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const r=e[i];if((!s||r.default)&&(s||t)&&(!t||mn(r,t)))return i}if(t){for(let s=0;s<e.length;s++){const i=e[s];if(ko(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(ko(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++)if(Do(e[s],t))return s}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==N.SUBTITLE_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&mn(t,s))return s;const i=gn(t,this.tracksInGroup);if(i>-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i),t}if(s)return null;{const s=gn(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger($.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=dl(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter(t=>Do(s,t))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==i&&(t.mode="disabled")}),i){const t=this.subtitleDisplay?"showing":"hidden";i.mode!==t&&(i.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!C(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=i;this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const h=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(h)}},Ws=.025,Ys=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({}),js=class{constructor(t,e){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=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const s=this.playoutLimit;return!(t<=0||isNaN(s))&&(0===s||((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>s)}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return ul(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-ul(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=C(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return ul(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Ws))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ys.Range:Ys.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}},qs=class{constructor(t,e,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&&this.hls.trigger($.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once($.LEVEL_LOADED,n),r.once($.AUDIO_TRACK_LOADED,n),r.once($.SUBTITLE_TRACK_LOADED,n),r.on($.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e,this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on($.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger($.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let s=this.assetItem.uri;try{s=fl(s,t.config.primarySessionId||"").href}catch(e){}t.loadSource(s)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=Ot.bufferInfo(t,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=Ot.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const s=e-this.startOffset;if(s>0&&s<t)return s}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const s=t-e;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,t-e),s)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,s){var i;null==(i=this.hls)||i.on(t,e)}once(t,e,s){var i;null==(i=this.hls)||i.once(t,e)}off(t,e,s){var i;null==(i=this.hls)||i.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${ml(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}},zs=class extends K{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((s,i)=>t<=i.startOffset&&e>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===e&&(e=t.start),s=this.findItemIndexAtTime(e));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(t,e){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(e&&"primary"!==e&&(r=r[e]),t===r.start||t>r.start&&t<r.end)return i}return-1}findJumpRestrictedIndex(t,e){const s=this.items;if(s)for(let i=t;i<=e&&s[i];i++){const t=s[i].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return i}return-1}findEventIndex(t){const e=this.items;if(e)for(let i=e.length;i--;){var s;if((null==(s=e[i].event)?void 0:s.identifier)===t)return i}return-1}findAssetIndex(t,e){const s=t.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const t=s[r];if(!t.error){const s=t.timelineStart;if(e===s||e>s&&(e<s+(t.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,s=t[t.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(t,e){const s=t.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},e),a=Object.keys(i),o=r?r.filter(t=>!a.includes(t.identifier)):[];n.length&&n.sort((t,e)=>{const s=t.cue.pre,i=t.cue.post,r=e.cue.pre,n=e.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=t.startTime,i=e.startTime;if(s!==i)return s-i}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=n,o.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,o)}updateSchedule(t,e=[],s=!1){const i=this.events||[];if(i.length||e.length||this.length<2){const r=this.items,n=this.parseSchedule(i,t);(s||e.length||(null==r?void 0:r.length)!==n.length||n.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,s){const i=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new js(o,e),this.eventMap[a]=t,!1===s&&(t.appendInPlace=s)),i.push(t)}}return i}parseSchedule(t,e){const s=[],i=e.main.details,r=i.live?1/0:i.edge;let n=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let i=0,o=0;if(t.forEach((e,a)=>{const l=e.cue.pre,d=e.cue.post,h=t[a-1]||null,c=e.appendInPlace,u=d?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===Ys.Range?f:0,m=e.resumptionOffset,p=(null==h?void 0:h.startTime)===u,v=u+e.cumulativeDuration;let y=c?v+f:u+m;if(l||!d&&u<=0){const t=o;o+=g,e.timelineStart=v;const i=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:i,end:n},integrated:{start:t,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-i;if(r>.033){const l=i,d=o;o+=r;const h=n;n+=r;const c={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+r,playout:{start:h,end:n},integrated:{start:d,end:o}};s.push(c)}else r>0&&h&&(h.cumulativeDuration+=r,s[s.length-1].end=u)}d&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=e.resumeTime;i=d||E>r?r:E}),i<r){var a;const t=i,e=o,l=r-i;o+=l;const d=n;n+=l,s.push({previousEvent:(null==(a=s[s.length-1])?void 0:a.event)||null,nextEvent:null,start:i,end:t+l,playout:{start:d,end:n},integrated:{start:e,end:o}})}this.setDurations(r,n,o)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return s}setDurations(t,e,s){this.durations={primary:t,playout:e,integrated:s}}resolveOffsets(t,e){const s=e.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;t.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,h=l?0:d?i:a.startTime;this.updateAssetDurations(a),n===h?a.cumulativeDuration=r:(r=0,n=h),!d&&a.snapOptions.in&&(a.resumeAnchor=En(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)),!a.appendInPlace&&o+1<t.length&&t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const c=C(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(t,e){const s=t.resumeTime,i=t.startTime+t.resumptionOffset;return Math.abs(s-i)>Ws?(this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(e).some(i=>{const r=e[i].details,n=r.edge;if(s>=n)return this.log(`"${t.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=En(null,r.fragments,s);if(!a)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<Ws+o||Math.abs(a.end-s)<Ws+o||(this.log(`"${t.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),0))})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error),s+=a.error?0:a.duration||0}t.duration=i&&!r?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}},Xs=class{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const s=t.assetListUrl;let i;try{i=fl(s,this.hls.sessionId,t.baseUrl)}catch(d){const e=this.assignAssetListError(t,F.ASSET_LIST_LOAD_ERROR,d,s);return void this.hls.trigger($.ERROR,e)}e&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return n.load(a,l,{onSuccess:(e,s,i,r)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const e=this.assignAssetListError(t,F.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger($.ERROR,e)}t.assetListResponse=n,this.hls.trigger($.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:r})},onError:(e,s,i,r)=>{const n=this.assignAssetListError(t,F.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${s.url})`),s.url,r,i);this.hls.trigger($.ERROR,n)},onTimeout:(e,s,i)=>{const r=this.assignAssetListError(t,F.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,e,i);this.hls.trigger($.ERROR,r)}}),this.hls.trigger($.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,s,i,r,n){return t.error=s,{type:O.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:i,error:s,networkDetails:n,stats:r}}},Qs=class extends K{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const s=e<=-.01;this.timelinePos=t,this.bufferedPos=t;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0),this.checkBuffer(),s&&t<i.start||t>=i.end){var r;const e=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const e=i.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&t<a||t>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const s=this.playingAsset;s&&t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,e)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=t.map(t=>t.identifier),l=!(!r.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>pl(t))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,h=null;i&&(d=this.updateItem(i,this.timelinePos),this.itemsMatch(i,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const c=this.bufferingItem;if(c&&(h=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,h)?this.bufferingItem=h:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const s=t.assetItem.timelineStart,i=t.timelineOffset-s;if(i)try{t.timelineOffset=s}catch(e){Math.abs(i)>Ws&&this.warn(`${e} ("${t.assetId}" ${t.timelineOffset}->${s})`)}}}),l||e){if(this.hls.trigger($.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.includes(i.event.identifier))return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(d,i),c&&h!==d&&this.trimInPlace(h,c),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Xs(t),this.schedule=new zs(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on($.BUFFER_APPENDED,this.onBufferAppended,this),t.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on($.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on($.MEDIA_ENDED,this.onMediaEnded,this),t.on($.ERROR,this.onError,this),t.on($.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off($.BUFFER_CODECS,this.onBufferCodecs,this),t.off($.BUFFER_APPENDED,this.onBufferAppended,this),t.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off($.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off($.MEDIA_ENDED,this.onMediaEnded,this),t.off($.ERROR,this.onError,this),t.off($.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Ca(t,"play",this.onPlay),Ca(t,"pause",this.onPause),Ca(t,"seeking",this.onSeeking),Ca(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const s=this.media=e.media;_a(s,"seeking",this.onSeeking),_a(s,"timeupdate",this.onTimeupdate),_a(s,"play",this.onPlay),_a(s,"pause",this.onPause)}onMediaAttached(t,e){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,s=e=>e?t.getAssetPlayer(e.identifier):e,i=(e,i,n,a,o)=>{if(e){let l=e[i].start;const d=e.event;if(d){if("playout"===i||d.timelineOccupancy!==Ys.Point){const t=s(n);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else l+=("bufferedPos"===a?r():t[a])-e.start;return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var s,i;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:(null==(i=t.schedule)?void 0:i.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,r),h=null==(a=t.schedule.items)?void 0:a[d],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,h);if(l&&(f||g)){const n=s(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-s,d=(f?s:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(h){let s=e;if("primary"!==r){const t=e-h[r].start;s=h.start+t}const i=!t.isInterstitial(h);if(t.isInterstitial(l)&&!l.event.appendInPlace||!i&&!h.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(d>n){const e=t.schedule.findJumpRestrictedIndex(n+1,d);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(i)t.timelinePos=s,t.checkBuffer();else{const t=h.event.assetList,s=e-(h[r]||h).start;for(let e=t.length;e--;){const i=t[e];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=e;break}}}t.setSchedulePosition(d,a)}}else{const e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=s)}}},o=()=>{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const i=e();return t.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=e(),r=t.bufferingItem;var n;return r&&r===s&&(i(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),s=t.effectivePlayingItem;return s&&s===e?i(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(e){const s=o(),i=t.effectivePlayingItem;i&&i===s&&a(e+i.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const s=null==(e=o())?void 0:e.event.assetList;return s?s.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const s=null==(e=o())?void 0:e.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const s=e();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){var e;return((e,s)=>{var i;if(0!==e&&"primary"!==s&&null!=(i=t.schedule)&&i.length){var r;const i=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[i];if(n)return e+(n[s].start-n.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,s=null==e?void 0:e.event;if(s&&!s.restrictions.skip){const i=t.findItemIndex(e);s.appendInPlace?a(e.playout.start+e.event.duration+.001,"playout"):t.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&s)&&this.findItemIndex(e)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(i=this.primaryMedia);const r=null==(e=i)?void 0:e.currentTime;return void 0!==r&&C(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,e)}transferMediaFromPlayer(t,e){const s=t.interstitial.appendInPlace,i=t.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&i)return void(this.detachedData={media:i});const s=t.transferMedia();this.log(`transfer MediaSource from ${t} ${pt(s)}`),this.detachedData=s}else e&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(t,e){var s,i;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const t=this.getBufferingPlayer();t?(r=t.transferMedia(),d=`${t}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${pt(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const h=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState),c=h&&r?r:e;this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`);const u=this.schedule;if(c===r&&u){const e=a&&t.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(-1===s){const s=this.hls.startPosition;if(this.log(yl("checkStart",s)),this.timelinePos=s,e.length&&e[0].cue.pre){const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const e=this.timelinePos=s>0?s:0,i=t.findItemIndexAtTime(e);this.setSchedulePosition(i)}}else if(i&&!this.playingItem){const e=t.findItemIndex(i);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const s=t.event,i=gl(s,s.findAssetIndex(e));if(s.isAssetPastPlayoutLimit(i)){if(this.schedule){var r;const e=null==(r=this.schedule.items)?void 0:r[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,i)}advanceAfterAssetEnded(t,e,s){const i=gl(t,s);if(t.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=e+1;if(i>=s.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(yl("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(i)}}}else{if(t.appendInPlace){const e=t.assetList[i];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,i)}}setScheduleToAssetAtTime(t,e){const s=this.schedule;if(!s)return;const i=e.parentIdentifier,r=s.getEvent(i);if(r){const e=s.findEventIndex(i),n=s.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=t>=0?i[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?pl(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,d=this.playingAsset,h=null==d?void 0:d.identifier,c=h?this.getAssetPlayer(h):null;if(c&&h&&(!this.eventItemsMatch(n,r)||void 0!==e&&h!==s.assetList[e].identifier)){var o;const e=s.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${s.assetList.length} ${ml(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger($.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:e,event:s,schedule:i.slice(0),scheduleIndex:t,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(h,r),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${pl(n)}`),s.hasPlayed=!0,this.hls.trigger($.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:t}),s.cue.once)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(r&&t){const s=this.findItemIndex(r);this.advanceSchedule(s,t,e,n,a)}return}}this.advanceSchedule(t,i,e,n,a)}advanceSchedule(t,e,s,i,r){const n=this.schedule;if(!n)return;const a=e[t]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(e=>{const s=e.interstitial,i=n.findEventIndex(s.identifier);(i<t||i>t+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const e=gl(r,(s=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,t,s);s=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${pl(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger($.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const h=r.assetList[s];if(!h)return void this.advanceAfterAssetEnded(r,t,s||0);if(d||(d=this.getAssetPlayer(h.identifier)),null===d||d.destroyed){const t=r.assetList.length;this.warn(`asset ${s+1}/${t} player destroyed ${r}`),d=this.createAssetPlayer(r,h,s),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(d,s,e,t,o),this.shouldPlay&&vl(d.media)}else a?(this.resumePrimary(a,t,i),this.shouldPlay&&vl(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,s){var i,r;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${pl(t)}`),null==(i=this.detachedData)||!i.mediaSource){let s=this.timelinePos;(s<t.start||s>=t.end)&&(s=this.getPrimaryResumption(t,e),this.log(yl("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,t)}if(!s)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${pl(t)}`),this.hls.trigger($.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const s=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(s<t.fragmentStart||s>t.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);return null!=e&&e.hls?e.hls.bufferedToEnd:Ot.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,s){e?this.setBufferingItem(e):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(t,s)),s||(this.log(yl("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,e){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(s=i.mainForwardBufferInfo)?void 0:s.start)||i.media.currentTime)-t)>.5?i.startLoad(t,e):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.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($.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on($.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const s=this.hls.levels[e.level];if(!s.details)return;const i=dr(dr({},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(t,e){const s=this.hls.audioTracks[e.id],i=this.mediaSelection;i?this.mediaSelection=dr(dr({},i),{},{audio:s}):this.altSelection=dr(dr({},this.altSelection),{},{audio:s})}onSubtitleTrackUpdated(t,e){const s=this.hls.subtitleTracks[e.id],i=this.mediaSelection;i?this.mediaSelection=dr(dr({},i),{},{subtitles:s}):this.altSelection=dr(dr({},this.altSelection),{},{subtitles:s})}onAudioTrackSwitching(t,e){const s=fn(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(s)))}onSubtitleTrackSwitch(t,e){const s=fn(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(s)))}onBufferCodecs(t,e){const s=e.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const s=this.playingItem;!s||this.itemsMatch(s,this.bufferingItem)||this.isInterstitial(s)||(this.bufferedPos=this.timelinePos,this.checkBuffer())}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const i=e[t];if(i.cue.post){var s;const t=this.schedule.findEventIndex(i.identifier),e=null==(s=this.schedule.items)?void 0:s[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;return t&&i&&i[this.findItemIndex(t,e)]||null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,s)=>{t.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(e.identifier,null)});const s=t.end+.25,i=Ot.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${pl(t)} (was ${pl(e)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var s;return!!e&&(t===e||t.event.identifier===(null==(s=e.event)?void 0:s.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const s=this.mediaSelection;s&&(null==(e=this.schedule)||e.updateSchedule(s,[],t))}checkBuffer(t){var e;const s=null==(e=this.schedule)?void 0:e.items;if(!s)return;const i=Ot.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=i.len<1),this.updateBufferedPos(i.end,s,t)}updateBufferedPos(t,e,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!i)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const s=this.findItemIndex(r),i=Math.min(s+1,e.length-1),n=e[i];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=i),this.isInterstitial(r)){const t=r.event;if(i-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>s&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(t,e)&&s){const{items:i,events:r}=s;if(!i||!r)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${pl(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=s.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,s)=>{const i=this.getAssetPlayer(t.identifier);i&&(s===e&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger($.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==s){this.bufferingAsset=null;const e=this.detachedData;e&&e.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),s=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(s)}bufferedToEvent(t,e){const s=t.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const t=this.preloadAssets(s,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const s=t.assetUrl,i=t.assetList.length,r=0===i&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${s?1:i} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&i){for(let r=e;r<i;r++){const e=t.assetList[r],s=this.getAssetPlayerQueueIndex(e.identifier);-1!==s&&!this.playerQueue[s].destroyed||e.error||this.createAssetPlayer(t,e,r)}const s=t.assetList[e];if(s){const t=this.getAssetPlayer(s.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;e&&(this.log(`Removing front buffer starting at ${t}`),Object.keys(e).forEach(e=>{this.hls.trigger($.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})}))}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let s=0;s<e.length;s++)if(t===e[s].assetId)return s;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let s=0;s<t.length;s++)if(t[s].media===e)return t[s];return null}createAsset(t,e,s,i,r,n){const a={parentIdentifier:t.identifier,identifier:cl(t,n,e),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const a=i.loadLevelObj||i.levels[i.currentLevel];(n||a)&&(n=or({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let d=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const s=e.duration;s&&t<s&&(d=t)}}const h=e.identifier,c=dr(dr({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(c.timelineOffset=e.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=or({},u,{contentId:hl(e.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${t} and asset ${h}`);const f=new qs(this.HlsPlayerClass,c,t,e);this.playerQueue.push(f),t.assetList[s]=e;let g=!0;const m=i=>{if(i.live){var r;const e=new Error(`Interstitials MUST be VOD assets ${t}`),i={fatal:!0,type:O.OTHER_ERROR,details:F.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=(null==(r=this.schedule)?void 0:r.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(i,t,n,s,e.message)}const n=i.edge-i.fragmentStart,a=e.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${h}" duration change ${a} > ${n}`),e.duration=n,this.updateSchedule())};f.on($.LEVEL_UPDATED,(t,{details:e})=>m(e)),f.on($.LEVEL_PTS_UPDATED,(t,{details:e})=>m(e)),f.on($.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(t,e)=>{const s=this.getAssetPlayer(h);if(s&&e.tracks){s.off($.BUFFER_CODECS,p),s.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};f.on($.BUFFER_CODECS,p),f.on($.BUFFERED_TO_END,()=>{var s;const i=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${i}`),!i||!this.schedule)return;const r=this.schedule.findEventIndex(t.identifier),n=null==(s=this.schedule.items)?void 0:s[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,e)});const v=e=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,e)};return f.once($.MEDIA_ENDED,v(s)),f.once($.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on($.ERROR,(e,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(h);if(i.details===F.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,`Asset player error ${i.error} ${t}`)}),f.on($.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${h}`),i={fatal:!0,type:O.OTHER_ERROR,details:F.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ml(e)}`),this.hls.trigger($.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:s,event:t,player:f}),f}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const s=this.playerQueue[e];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(t,e){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){const t=this.playerQueue[s];this.log(`clear ${t} toSegment: ${e?pl(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(s,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=t,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,s[i]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${ml(a)}`),this.hls.trigger($.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:s.slice(0),scheduleIndex:i,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=t,a=this.schedule.findEventIndex(r.identifier),o=null==(s=this.schedule.items)?void 0:s[a];if(!o)return;t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===t)return;const d=r.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const h=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(h&&!fr(h,t.tracks)){const e=new Error(`Asset ${ml(n)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),s={fatal:!0,type:O.OTHER_ERROR,details:F.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},i=r.findAssetIndex(n);return void this.handleAssetItemError(s,r,a,i,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,s=this.primaryMedia;if(!e||!s)return;const i=s.currentTime,r=e.findAssetIndex(t,i),n=t.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s))&&a.hls){const s=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,r)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,s,i,r){if(t.details===F.BUFFER_STALLED_ERROR)return;const n=e.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?ml(n):n} ${t.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,h=or({},t,{fatal:!1,errorAction:_n(!0),asset:n,assetListIndex:i,event:e,schedule:d,scheduleIndex:s,player:l});if(this.hls.trigger($.INTERSTITIAL_ASSET_ERROR,h),!t.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),e.assetList.some(t=>!t.error))for(let g=i;g<e.assetList.length;g++)this.resetAssetPlayer(e.assetList[g].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):c&&c.identifier===a?this.advanceAfterAssetEnded(e,s,i):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(t){const e=t.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${i} playing: ${pl(s)} error: ${t.error}`),-1===i&&(i=this.hls.startPosition);const r=this.updateItem(s,i);this.itemsMatch(s,r)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===i)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(t,e){var s,i;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((t,e)=>{const s=parseFloat(t.DURATION);this.createAsset(r,e,d,o+d,s,t.URI),d+=s}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const h=this.waitingItem,c=(null==h?void 0:h.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(c){var f;const t=this.schedule.findEventIndex(n),e=null==(f=this.schedule.items)?void 0:f[t];if(e){if(!this.playingItem&&this.timelinePos>e.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r);this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case F.ASSET_LIST_PARSING_ERROR:case F.ASSET_LIST_LOAD_ERROR:case F.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case F.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Zs=class extends se{constructor(t,e,s){super(t,e,s,"subtitle-stream-controller",U.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=ee.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:i}=e;if(this.fragContextChanged(s)||(yr(s)&&(this.fragPrevious=s),this.state=ee.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let l=0;l<r.length;l++)if(a>=r[l].start&&a<=r[l].end){n=r[l];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}}),this.fragmentTracker.removeFragmentsInRange(s,t,U.SUBTITLE)}}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===U.SUBTITLE&&(e.details===F.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ee.STOPPED&&(this.state=ee.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Ro(this.levels,e)?this.levels=e.map(t=>new gt(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new gt(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,U.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==ee.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var d;o.details?(l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&e&&(l=e.start,ya(n,l))):n.hasProgramDateTime&&t.hasProgramDateTime?(Pa(n,t),l=n.fragmentStart):e&&(l=e.start,ya(n,l)),t&&!this.startFragRequested&&this.setStartPosition(t,l)}o.details=n,this.levelLastLoaded=o,a===i&&(this.hls.trigger($.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===ee.IDLE&&(En(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&Wn(i.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,Yn(i.method)).catch(t=>{throw r.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(s=>{const i=performance.now();r.trigger($.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:i}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=ee.IDLE})}}doTick(){if(this.media){if(this.state===ee.IDLE){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;if(this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),{end:n,len:a}=Ot.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),o=s.details;if(a>this.hls.maxBufferLength+o.levelTargetDuration)return;const l=o.fragments,d=l.length,h=o.edge;let c=null;const u=this.fragPrevious;if(n<h){const t=i.maxFragLookUpTolerance,e=n>h-t?0:t;c=En(u,l,Math.max(l[0].start,n),e),!c&&u&&u.start<l[0].start&&(c=l[0])}else c=l[d-1];if(c=this.filterReplacedPrimary(c,s.details),!c)return;const f=l[c.sn-o.startSN-1];if(f&&f.cc===c.cc&&this.fragmentTracker.getState(f)===At.NOT_LOADED&&(c=f),this.fragmentTracker.getState(c)===At.NOT_LOADED){const t=this.mapToInitFragWhenRequired(c);t&&this.loadFragment(t,s,n)}}}else this.state=ee.IDLE}loadFragment(t,e,s){yr(t)?super.loadFragment(t,e,s):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Js(this.tracksBuffered[this.currentTrackId]||[])}},Js=class{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}},ti={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},ei=t=>String.fromCharCode(ti[t]||t),si=15,ii=100,ri={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ni={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ai={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},oi={25:2,26:4,29:6,30:8,31:10,27:13,28:15},li=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],di=class{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;Y.log(`${this.time} [${t}] ${s}`)}}},hi=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e},ci=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let s=0;s<e.length;s++){const i=e[s];t.hasOwnProperty(i)&&(this[i]=t[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},ui=class{constructor(){this.uchar=" ",this.penState=new ci}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}},fi=class{constructor(t){this.chars=[],this.pos=0,this.currPenState=new ci,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<ii;e++)this.chars.push(new ui);this.logger=t}equals(t){for(let e=0;e<ii;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<ii;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<ii;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>ii&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ii)}moveCursor(t){const e=this.pos+t;if(t>1)for(let s=this.pos+1;s<e+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=ei(t);this.pos>=ii?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<ii;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let s=0;s<ii;s++){const i=this.chars[s].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}},gi=class{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<si;e++)this.rows.push(new fi(t));this.logger=t}reset(){for(let t=0;t<si;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<si;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<si;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<si;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+pt(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let e=0;e<si;e++)this.rows[e].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[t].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let n=0;n<this.nrRollUpRows;n++)this.rows[e-this.nrRollUpRows+n+1].copy(s.rows[t+n])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,i=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+pt(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",i=-1;for(let r=0;r<si;r++){const s=this.rows[r].getTextString();s&&(i=r+1,t?e.push("Row "+i+": '"+s+"'"):e.push(s.trim()))}return e.length>0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}},mi=class{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new gi(s),this.nonDisplayedMemory=new gi(s),this.lastOutputScreen=new gi(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let s=0;s<t.length;s++)this.writeScreen.insertChar(t[s]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};e.underline=t%2==1,e.italics=t>=46,e.italics?e.foreground="white":e.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(t/2)-16],this.logger.log(2,"MIDROW: "+pt(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}},pi=class{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new di;this.channels=[null,new mi(t,e,i),new mi(t+1,s,i)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let s=0;s<e.length;s+=2){const t=127&e[s],i=127&e[s+1];let r=!1,n=null;if(0===t&&0===i)continue;this.logger.log(3,()=>"["+hi([e[s],e[s+1]])+"] -> ("+hi([t,i])+")");const a=this.cmdHistory;if(t>=16&&t<=31){if(Tl(t,i,a)){El(null,null,a),this.logger.log(3,()=>"Repeated command ("+hi([t,i])+") is dropped");continue}El(t,i,this.cmdHistory),r=this.parseCmd(t,i),r||(r=this.parseMidrow(t,i)),r||(r=this.parsePAC(t,i)),r||(r=this.parseBackgroundAttributes(t,i))}else El(null,null,a);if(!r&&(n=this.parseChars(t,i),n)){const t=this.currentChannel;t&&t>0?this.channels[t].insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+hi([t,i])+" orig: "+hi([e[s],e[s+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=s,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+hi([t,e])+")"),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127||(16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?ri[t]:ai[t]:1===i?ni[t]:oi[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+ei(t)+"' in channel "+s),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,()=>"Char codes = "+hi(i).join(",")),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;let s;const i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=li[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}El(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}},vi=function(){if(null!=Kt&&Kt.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function i(t){return s(e,t)}function r(t,...e){let s=1;for(;s<arguments.length;s++){const e=arguments[s];for(const s in e)t[s]=e[s]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=e,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const i=function(e){return s(t,e)}(e);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return A},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");A=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),yi=class{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}},Ei=class{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i<s.length;++i)if(e===s[i]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}},Ti=new vi(0,0,""),Si="middle"===Ti.align?"middle":"center",Ai=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new yi,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=Il(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const i=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),i}function i(t){Al(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=s();const i=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let n=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(n?n=!1:t=s(),e.state){case"HEADER":/:/.test(t)?i(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new vi(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{Ll(t,e.cue,e.regionList)}catch(r){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(n=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(r){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}},Li=/\r\n|\n\r|\n|\r/g,Ii=function(t,e,s=0){return t.slice(s,s+e.length)===e},bi=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(C(e)&&C(s)&&C(i)&&C(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e},Ri=function(t,e,s){let i=t[e],r=t[i.prevCC];if(!r||!r.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=i.start-r.start,i.new=!1,i=r,r=t[i.prevCC]}t.presentationOffset=s},ki="stpp.ttml.im1t",Di=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wi=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Pi={left:"start",center:"center",right:"end",start:"start",end:"end"},_i=class{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Ci=class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on($.FRAG_LOADING,this.onFragLoading,this),t.on($.FRAG_LOADED,this.onFragLoaded,this),t.on($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on($.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off($.FRAG_LOADING,this.onFragLoading,this),t.off($.FRAG_LOADED,this.onFragLoaded,this),t.off($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off($.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new _i(this,"textTrack1"),e=new _i(this,"textTrack2"),s=new _i(this,"textTrack3"),i=new _i(this,"textTrack4");this.cea608Parser1=new pi(1,t,e),this.cea608Parser2=new pi(3,s,i)}addCues(t,e,s,i,r){let n=!1;for(let a=r.length;a--;){const t=r[a],i=Fl(t[0],t[1],e,s);if(i>=0&&(t[0]=Math.min(t[0],e),t[1]=Math.max(t[1],s),n=!0,i/(s-e)>.5))return}if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,s,i)}else{const r=this.Cues.newCue(null,e,s,i);this.hls.trigger($.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;s===U.MAIN&&(this.initPTS[e.cc]={baseTime:i,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded($.FRAG_LOADED,t):this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Ol(r,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=e[t],a=this.getExistingTrack(r,n);if(a)s[t]=a,ol(s[t]),nl(s[t],i);else{const e=this.createTextTrack("captions",r,n);e&&(e[t]=!0,s[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger($.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,s){const i=this.media;if(i)return i.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const s=!!e.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(t=>{ol(i[t]),delete i[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let s=0;s<e.length;s++)ol(e[s])}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],i=s.some(t=>t.textCodec===ki);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Ro(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?dl(t.textTracks):null;if(this.tracks.forEach((t,s)=>{let i;if(e){let s=null;for(let i=0;i<e.length;i++)if(e[i]&&Ol(e[i],t)){s=e[i],e[i]=null;break}s&&(i=s)}if(i)ol(i);else{const e=Ml(t);i=this.createTextTrack(e,t.name,t.lang),i&&(i.mode="disabled")}i&&this.textTracks.push(i)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger($.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s=`textTrack${e[1]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===U.MAIN){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.type===U.SUBTITLE)if(i.byteLength){const t=s.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===ki?this._parseIMSC1(s,i):this._parseVTTs(e)}}else this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;kl(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{s.logger.log(`Failed to parse IMSC1: ${e}`),s.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(t);const o=this.hls;Rl(null!=(e=s.initSegment)&&e.data?Fr(s.initSegment.data,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,t=>{this._appendCues(t,s.level),o.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(s,i),o.logger.log(`Failed to parse VTT cue: ${e}`),r&&a>s.cc||o.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})})}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||kl(e,this.initPTS[t.cc],()=>{s.textCodec=ki,this._parseIMSC1(t,e)},()=>{s.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach(t=>al(s,t))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger($.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===U.SUBTITLE&&this.onFragLoaded($.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=e;if(s.type!==U.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let r=0;r<i.length;r++){const t=i[r].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const e=this.extractCea608Data(t);this.cea608Parser1.addData(i[r].pts,e[0]),this.cea608Parser2.addData(i[r].pts,e[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach(i=>ll(t[i],e,s))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==i){const{textTracks:t}=this;Object.keys(t).forEach(s=>ll(t[s],e,i))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r<s;r++){const s=t[i++],r=127&t[i++],n=127&t[i++];if((0!==r||0!==n)&&4&s){const t=3&s;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},xi=/\s/,Mi={newCue(t,e,s,i){const r=[];let n,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,d="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)xi.test(n.chars[t].uchar)&&o?l++:(d+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const i=Il(d.trim()),f=bl(e,s,i);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new h(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>al(t,e))),r}},Oi=/(\d+)-(\d+)\/(\d+)/,Fi=class{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Nl,this.controller=new self.AbortController,this.stats=new X}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(or({},t.headers))};return t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),s}(t,this.controller.signal),n="arraybuffer"===t.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&C(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))},e.timeout),(bo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(s=>{var r;this.response=this.loader=s;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))},l-(a-i.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new $i(e||"fetch, bad network response",t,s)}i.loading.first=a,i.total=$l(s.headers)||i.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&C(e.highWaterMark)?this.loadProgressively(s,i,t,e.highWaterMark,o):n?s.arrayBuffer():"json"===t.responseType?s.json():s.text()}).then(s=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=s[a];l&&(i.loaded=i.total=l);const d={url:o.url,data:s,code:o.status},h=null==(r=this.callbacks)?void 0:r.onProgress;h&&!C(e.highWaterMark)&&h(i,t,s,o),null==(n=this.callbacks)||n.onSuccess(d,i,t,o)}).catch(e=>{var s;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=e&&e.code||0,n=e?e.message:null;null==(s=this.callbacks)||s.onError({code:r,text:n},t,e?e.details:null,i)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,i=0,r){const n=new ie,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,s,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(e,s,n.flush().buffer,t)):r(e,s,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}},$i=class extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}},Ni=/^age:\s*[\d.]+\s*$/im,Ui=class{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new X,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r(s,e.url)}).catch(t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r(s,e.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:t.message},e,s,i)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const a in i)t.setRequestHeader(a,i[a]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&C(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const r=null!=l?l:e.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first),s.loaded=s.total="arraybuffer"===e.responseType?r.byteLength:r.length,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const o=null==(n=this.callbacks)?void 0:n.onProgress;o&&o(s,t,r,e);const l={url:e.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(l,s,t,e))}}const d=r.loadPolicy.errorRetry;var o;wn(d,s.retry,!1,{url:t.url,data:void 0,code:i})?this.retry(d):(Y.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,s))}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(wn(t,this.stats.retry,!0))this.retry(t);else{var e;Y.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=kn(t,s.retry),s.retry++,Y.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Ni.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}},Bi=dr(dr({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Ui,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:vt,bufferController:es,capLevelController:ss,errorController:St,fpsController:Vs,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:Wt,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Mi,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:Zs,subtitleTrackController:Hs,timelineController:Ci,audioStreamController:qe,audioTrackController:Xe,emeController:Gs,cmcdController:Us,contentSteeringController:Bs,interstitialsController:Qs}),Gi=class extends Ct{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const s=this.media=e.media;_a(s,"playing",this.onMediaPlaying),_a(s,"waiting",this.onMediaWaiting),_a(s,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:s}=this;s&&(Ca(s,"playing",this.onMediaPlaying),Ca(s,"waiting",this.onMediaWaiting),Ca(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(d)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1})));if(!Ot.getBuffered(n).length)return void(this.nudgeRetry=0);const h=Ot.bufferInfo(n,t,0),c=h.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const e=Gl(this.hls.inFlightFragments,t),s=h.len>2,i=!c||e||c-t>2&&!u.getPartialFragment(t);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(h.len>0||c))return;const e=Math.max(c,h.start||0)-t,s=null!=f&&f.live?2*f.targetduration:2,i=Vl(t,u);if(e>0&&(e<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let v=this.stalled;if(null===v){if(!(p>0&&m-p<g))return void(this.stalled=m);v=this.stalled=p}const y=m-v;if(!a&&(y>=g||p)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger($.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const T=Ot.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(T,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger($.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&t>i.end(0)){const s=Ot.bufferedInfo(Ot.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&e>=s.start){const s=Ot.timeRangesToArray(i),r=Ot.bufferedInfo(s,e,0).bufferedIndex;if(r>-1&&r<s.length-1){const e=Ot.bufferedInfo(s,t,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===e||e>r)&&n-i<1&&t-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=Vl(t,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=Ot.bufferInfo(this.media,t,0);this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=Vl(s,n);if((d||null!=l&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const h=t.buffered,c=this.adjacentTraversal(t,s);(h&&h.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-s<o.maxBufferHole||c))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const s=this.fragmentTracker,i=t.nextStart;if(s&&i){const t=s.getFragAtPos(e,U.MAIN),r=s.getFragAtPos(i,U.MAIN);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${pt(t)})`);this.warn(i.message),e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:s,media:i}=this,r=null==(e=this.hls)?void 0:e.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=Ot.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const e=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&i.readyState<3,h=o-n;if(h>0&&(e||d)){if(h>r.maxBufferHole){let e=!1;if(0===n){const t=s.getAppendedFrag(0,U.MAIN);t&&o<t.end&&(e=!0)}if(!e&&t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Gl(this.hls.inFlightFragments,o))return 0;let e=!1,i=t.end;for(;i<o;){const t=Vl(i,s);if(!t){e=!0;break}i+=t.duration}if(e)return 0}}const e=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${e}`),this.moved=!0,i.currentTime=e,null==t||!t.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`),i={type:O.MEDIA_ERROR,details:F.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?i.part=t:i.frag=t),this.hls.trigger($.ERROR,i)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:s,nudgeRetry:i}=this,r=null==e?void 0:e.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),e.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:t.len,bufferInfo:t})}}},Ki=(()=>{const t=Hl();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Vi=class{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger($.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var s;this.media=e.media,!1===(null==(s=e.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null,e.transferMedia||(this.id3Track&&(this.removeCues&&ol(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const s=t[e];if("metadata"===s.kind&&"id3"===s.label)return nl(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Hl();if(n)for(let a=0;a<r.length;a++){const t=r[a].type;if(t===ce.emsg&&!s||!i)continue;const e=Qa(r[a].data),o=r[a].pts;let l=o+r[a].duration;l>Ki&&(l=Ki),l-o<=0&&(l=o+.25);for(let s=0;s<e.length;s++){const i=e[s];if(!Za(i)){this.updateId3CueEnds(o,t);const e=Wl(n,o,l,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(t,e){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let r=i.length;r--;){const s=i[r];s.type===e&&s.startTime<t&&s.endTime===Ki&&(s.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===i?t=>t.type===ce.audioId3&&o:"video"===i?t=>t.type===ce.emsg&&a:t=>t.type===ce.audioId3&&o||t.type===ce.emsg&&a,ll(r,e,s,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Hl();if(s&&i&&!n){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):a&&(r=this.assetCue=Wl(a,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,d=Object.keys(l);let h=this.dateRangeCuesAppended;var c;if(o&&e)if(null!=(c=o.cues)&&c.length){const t=Object.keys(h).filter(t=>!d.includes(t));for(let e=t.length;e--;){var u;const s=t[e],i=null==(u=h[s])?void 0:u.cues;delete h[s],i&&Object.keys(i).forEach(t=>{const e=i[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(e)}catch(s){}}})}}else h=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==d.length&&C(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],s=l[e],i=s.startTime,r=h[e],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=Ki;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,c=!0;else if(s.endOnNext&&!c){const t=d.reduce((t,e)=>{if(e!==s.id){const i=l[e];if(i.class===s.class&&i.startDate>s.startDate&&(!t||s.startDate<t.startDate))return i}return t},null);t&&(u=t.startTime,c=!0)}const m=Object.keys(s.attr);for(let t=0;t<m.length;t++){const l=m[t];if(!Gn(l))continue;const d=o[l];if(d)!c||null!=r&&r.durationKnown?Math.abs(d.startTime-i)>.01&&(d.startTime=i,d.endTime=u):d.endTime=u;else if(a){let t=s.attr[l];Kn(l)&&(t=pr(t));const r=Wl(a,i,u,{key:l,data:t},ce.dateRange);r&&(r.id=e,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}h[e]={cues:o,dateRange:s,durationKnown:c}}}}},Hi=class{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(e,Math.max(1,s));this.changeMediaPlaybackRate(t,i)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:s,targetduration:i}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const d=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on($.MEDIA_ATTACHED,this.onMediaAttached,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this),t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_UPDATED,this.onLevelUpdated,this),t.on($.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off($.MEDIA_ATTACHED,this.onMediaAttached,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this),t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_UPDATED,this.onLevelUpdated,this),t.off($.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var s;e.details===F.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var s,i;t.playbackRate!==e&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}},Wi=class extends ze{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.MANIFEST_LOADED,this.onManifestLoaded,this),t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this),t.on($.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.MANIFEST_LOADED,this.onManifestLoaded,this),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this),t.off($.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:d,videoCodec:h}=t;d&&(t.audioCodec=d=Xr(d,s)||void 0),h&&(h=t.videoCodec=function(t){const e=t.split(",");for(let s=0;s<e.length;s++){const t=e[s].split(".");t.length>2&&"avc1"===t[0]&&(e[s]=`avc1.${parseInt(t[1]).toString(16)}${("000"+parseInt(t[2]).toString(16)).slice(-4)}`)}return e.join(",")}(h));const{width:c,height:u,unknownCodecs:f}=t,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!h),l||(l=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=e,S=`${y||"."}-${t.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(r[S])if(r[S].uri===t.url||t.attrs["PATHWAY-ID"])r[S].addGroupId("audio",e.AUDIO),r[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=this.createLevel(t);r[S]=s,i.push(s)}else{const e=this.createLevel(t);r[S]=e,n[S]=1,i.push(e)}}),this.filterAndSortMediaOptions(i,e,a,o,l)}createLevel(t){const e=new gt(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),e.supportedResult=sn(t,[])}return e}isAudioSupported(t){return Wr(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Wr(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,s,i,r){var n;let a=[],o=[],l=t;const d=(null==(n=e.stats)?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&!!(r=e)&&ct.indexOf(r)>-1;var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;e.levels.length&&(s=`one or more CODECS in variant not supported: ${pt(e.levels.map(t=>t.attrs.CODECS).filter((t,e,s)=>s.indexOf(t)===e))}`,this.warn(s),t+=` (${s})`);const i=new Error(t);this.hls.trigger($.ERROR,{type:O.MEDIA_ERROR,details:F.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:s})}}),void(d.end=performance.now());e.audioTracks&&(a=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),Yl(a)),e.subtitles&&(o=e.subtitles,Yl(o));const h=l.slice(0);l.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return ct.indexOf(t.videoRange)-ct.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=qr(t.videoCodec),i=qr(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=zr(t.codecSet),i=zr(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length))for(let v=0;v<h.length;v++)if(h[v].pathwayId===l[0].pathwayId){c=h[v];break}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===c){var u;this._firstLevel=v;const t=c.bitrate,e=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const s=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);s>e&&e===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=s)}break}const f=r&&!i,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:m&&!f&&a.some(t=>!!t.url)};d.end=performance.now(),this.hls.trigger($.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const s=new Error("invalid level idx"),i=t<0;if(this.hls.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger($.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),s=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=s}}onError(t,e){!e.fatal&&e.context&&e.context.type===N.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===U.MAIN){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger($.LEVEL_LOADING,{url:s,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const s=this._levels.filter((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));La(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.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($.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger($.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}},Yi=class extends se{constructor(t,e,s){super(t,e,s,"stream-controller",U.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 t=this.media,e=t?t.currentTime:null;if(null===e||!C(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const s=this.getFwdBufferInfoAtPos(t,e,U.MAIN,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.LEVEL_LOADED,this.onLevelLoaded,this),t.on($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on($.BUFFER_CREATED,this.onBufferCreated,this),t.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVEL_LOADED,this.onLevelLoaded,this),t.off($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off($.BUFFER_CREATED,this.onBufferCreated,this),t.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}s>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=ee.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=ee.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ee.WAITING_LEVEL:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=ee.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=ee.IDLE;break}break}case ee.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===ee.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger($.BUFFER_EOS,t),void(this.state=ee.ENDED)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===ee.WAITING_LEVEL||this.waitForLive(n))return this.level=r,this.state=ee.WAITING_LEVEL,void(this.startFragRequested=!1);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&yr(u)&&this.fragmentTracker.getState(u)!==At.OK){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?Q.AUDIO:Q.VIDEO,e=(t===Q.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,U.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,U.MAIN,h)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i===At.NOT_LOADED||i===At.PARTIAL?yr(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,s):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,U.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let s;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case ee.KEY_LOADING:case ee.FRAG_LOADING:case ee.FRAG_LOADING_WAITING_RETRY:case ee.PARSING:case ee.PARSED:this.state=ee.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;_a(s,"playing",this.onMediaPlaying),_a(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:s}=this;s&&(Ca(s,"playing",this.onMediaPlaying),Ca(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e),e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger($.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let s=!1,i=!1;for(let r=0;r<e.levels.length;r++){const t=e.levels[r].audioCodec;t&&(s=s||-1!==t.indexOf("mp4a.40.2"),i=i||-1!==t.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var t;const e=jl();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==ee.IDLE)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=ee.WAITING_LEVEL)}onLevelLoaded(t,e){var s;const{levels:i,startFragRequested:r}=this,n=e.level,a=e.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,d=this.fragCurrent;!d||this.state!==ee.FRAG_LOADING&&this.state!==ee.FRAG_LOADING_WAITING_RETRY||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,h),this.hls.trigger($.LEVEL_UPDATED,{details:a,level:n}),this.state===ee.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=ee.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const t=Ot.bufferInfo(s,i,0);if(null==(l=t.buffered)||!l.length)return void(s.currentTime=i);if(t.start<=r)return void(s.currentTime=i);const{nextStart:e}=Ot.bufferedInfo(t.buffered,r,0);e&&(s.currentTime=e)}else s.currentTime=i}}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new je(this.hls,U.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new xt(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,h,c,l,s,i,o.totalduration,d,m,p)}onAudioTrackSwitching(t,e){const s=this.hls,i=0!==this.altAudio;if(yn(e.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once($.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger($.AUDIO_TRACK_SWITCHED,e)}),void s.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger($.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=yn(e.url,this.hls);if(s){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=s?2:0,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const a in s){const t=s[a];if("main"===t.id){if(r=a,i=t,"video"===a){const t=s[a];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e,r=s.type===U.MAIN;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===ee.PARSED&&(this.state=ee.IDLE));const t=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),yr(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&Ot.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var s;if(e.fatal)this.state=ee.ERROR;else switch(e.details){case F.FRAG_GAP:case F.FRAG_PARSING_ERROR:case F.FRAG_DECRYPT_ERROR:case F.FRAG_LOAD_ERROR:case F.FRAG_LOAD_TIMEOUT:case F.KEY_LOAD_ERROR:case F.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.MAIN,e);break;case F.LEVEL_LOAD_ERROR:case F.LEVEL_LOAD_TIMEOUT:case F.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ee.WAITING_LEVEL||(null==(s=e.context)?void 0:s.type)!==N.LEVEL||(this.state=ee.IDLE);break;case F.BUFFER_ADD_CODEC_ERROR:case F.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case F.BUFFER_FULL_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case F.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=ee.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Q.AUDIO||!this.altAudio){const t=(e===Q.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,U.MAIN),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${e}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=Ot.getBuffered(t),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),e<s&&(this.log(`seek to target start position ${s} from current time ${e} buffer start ${a}`),t.currentTime=s)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:s}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=ee.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger($.FRAG_LOADED,t),i.bitrateTest=!1}).catch(e=>{this.state!==ee.STOPPED&&this.state!==ee.ERROR&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=t,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:h,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=ee.PARSING,u){const t=u.tracks;if(t){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,t,i,r),s.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:e,tracks:t})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(C(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const t=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:t},s.trigger($.INIT_PTS_FOUND,{frag:a,id:e,initPTS:i,timescale:n,trackId:t})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,s=!t||a.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:i,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,i,a.start,l,!0)}else e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,t,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,e||s)}else{if(!e&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[Q.AUDIO]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(Q.AUDIO,t,e,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const t={id:e,frag:a,details:f,samples:c.samples};s.trigger($.FRAG_PARSING_METADATA,t)}if(f&&h){const t={id:e,frag:a,details:f,samples:h.samples};s.trigger($.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${yr(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,s,i){if(this.state!==ee.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=e;if(r){const s=t.audioCodec;let i=Qr(r.codec,s);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=U.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=U.MAIN;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){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"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger($.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger($.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,U.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,s=null==t?void 0:t[e];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=ee.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(Ot.isBuffered(t,s)?e=this.getAppendedFrag(s):Ot.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger($.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger($.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return C(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(C(e)){const t=this.getLevelDetails(),s=this.currentFrag||(t?En(null,t.fragments,e):null);if(s){const t=s.programDateTime;if(null!==t){const i=t+1e3*(e-s.start);return new Date(i)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}},ji=class extends K{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=F.KEY_LOAD_ERROR,s,i,r){return new _t({type:O.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i})}loadClear(t,e,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let i=0,r=e.length;i<r;i++){const n=e[i];if(t.cc<=n.cc&&(!yr(t)||!yr(n)||t.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(t=>{if(!this.emeController)return;n.setKeyFormat(t);const e=Qn(t);return e?this.emeController.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=Jn(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var s,i;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const s=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,F.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,F.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=zl(r);let o=this.keyIdToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:t,keyInfo:o});if(this.emeController&&null!=(i=o)&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(e=>{const{keyInfo:s}=e;return r.key=s.decryptdata.key,{frag:t,keyInfo:s}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+mr(r.keyId):""} URI: ${r.uri} from ${t.type} ${t.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,F.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var i;if(!t.decryptdata.keyId&&null!=(i=e.initSegment)&&i.data){const s=function(t){const e=[];return Mr(t,t=>e.push(t.subarray(8,24))),e}(e.initSegment.data);if(s.length){let e=s[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${mr(e)}`),jt.setKeyIdForUri(t.decryptdata.uri,e)):(e=jt.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${mr(e)}`)),t.decryptdata.keyId=e}}return t.decryptdata.keyId||yr(e)?(t.keyLoadPromise=this.emeController.loadKey(s).then(e=>(t.mediaKeySessionContext=e,s))).catch(s=>{throw t.keyLoadPromise=null,"data"in s&&(s.data.frag=e),s}):Promise.resolve(s)}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,i=new(0,s.loader)(s);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(a,l,{onSuccess:(t,e,s,i)=>{const{frag:a,keyInfo:o}=s,l=zl(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,F.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,F.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,dr({url:a.url,data:void 0},t)))},onTimeout:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,F.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,F.INTERNAL_ABORTED,new Error("key loading aborted"),i))}})})}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=null,s.loader=null);const n=zl(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}},qi=class{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on($.MANIFEST_LOADING,this.onManifestLoading,this),t.on($.LEVEL_LOADING,this.onLevelLoading,this),t.on($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off($.MANIFEST_LOADING,this.onManifestLoading,this),t.off($.LEVEL_LOADING,this.onLevelLoading,this),t.off($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:N.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:N.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:N.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:N.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const s=this.loaders[N.LEVEL];if(s){const t=s.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(s.abort(),delete this.loaders[N.LEVEL])}}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,s=r.context;if(s&&s.levelOrTrack===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void(s.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===N.MANIFEST?s.manifestLoadPolicy.default:or({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),C(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===N.LEVEL&&null!==t.level?e=this.hls.levels[t.level].details:t.type===N.AUDIO_TRACK&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===N.SUBTITLE_TRACK&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);i=or({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};r.load(t,a,{onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;e.parsing.start=performance.now(),Jt.isMediaPlaylist(n)||s.type!==N.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}})}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Ql(t,s),o=Jt.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];Wr(a,"audio",s)?(t.audioCodec=i=i?`${i},${a}`:a,nt.audio[i.substring(0,4)]=2,e.splice(n,1)):Wr(a,"video",s)&&(t.videoCodec=r=r?`${r},${a}`:a,nt.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Jt.parseMasterPlaylistMedia(n,a,o);g.length&&(g.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ut({}),bitrate:0,url:""}))),r.trigger($.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,d=Ql(t,s),h=C(o)?o:C(a)?a:0,c=Xl(s),u=Jt.parseLevelPlaylist(t.data,d,h,c,0,this.variableList);if(l===N.MANIFEST){const t={attrs:new Ut({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=e.loading.start+Ea(u,0),n.trigger($.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.MANIFEST_PARSING_ERROR,fatal:e.type===N.MANIFEST,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===N.LEVEL?n+=`: ${t.level} id: ${t.id}`:t.type!==N.AUDIO_TRACK&&t.type!==N.SUBTITLE_TRACK||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=F.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case N.MANIFEST:o=s?F.MANIFEST_LOAD_TIMEOUT:F.MANIFEST_LOAD_ERROR,l=!0;break;case N.LEVEL:o=s?F.LEVEL_LOAD_TIMEOUT:F.LEVEL_LOAD_ERROR,l=!1;break;case N.AUDIO_TRACK:o=s?F.AUDIO_TRACK_LOAD_TIMEOUT:F.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case N.SUBTITLE_TRACK:o=s?F.SUBTITLE_TRACK_LOAD_TIMEOUT:F.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const h={type:O.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:r};i&&(h.response=dr({url:(null==e?void 0:e.url)||t.url,data:void 0},i)),this.hls.trigger($.ERROR,h)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:h,groupId:c,deliveryDirectives:u}=i,f=Ql(e,i),g=Xl(i);let m="number"==typeof i.level&&g===U.MAIN?l:void 0;const p=t.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:e,context:i,level:m,parent:g,networkDetails:r,stats:s});t.playlistParsingError=null}if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger($.ERROR,{type:O.NETWORK_ERROR,details:F.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:e,context:i,level:m,parent:g,networkDetails:r,stats:s})}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case N.MANIFEST:case N.LEVEL:if(m)if(d){if(d!==a.levels[m]){const t=a.levels.indexOf(d);t>-1&&(m=t)}}else m=0;a.trigger($.LEVEL_LOADED,{details:t,levelInfo:d||a.levels[0],level:m||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===N.MANIFEST});break;case N.AUDIO_TRACK:a.trigger($.AUDIO_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case N.SUBTITLE_TRACK:a.trigger($.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u})}}},t("t",zi=class t{static get version(){return oe}static isMSESupported(){return ql()}static isSupported(){return function(){if(!ql())return!1;const t=ur();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(jr(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(jr(e,"audio"))))}()}static getMediaSource(){return ur()}static get Events(){return $}static get MetadataSchema(){return ce}static get ErrorTypes(){return O}static get ErrorDetails(){return F}static get DefaultConfig(){return t.defaultConfig?t.defaultConfig:Bi}static set DefaultConfig(e){t.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 ae,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 s=this.logger=function(t,e,s){const i=hr();if("object"==typeof console&&!0===t||"object"==typeof t){const n=["debug","log","info","warn","error"];n.forEach(e=>{i[e]=cr(e,t,s)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch(r){return hr()}n.forEach(e=>{W[e]=cr(e,t)})}else or(W,i);return i}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(t,e,s){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Ul(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach(s=>{const r=`${t}Loading${s}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=i[n].default;switch(e[n]={default:t},s){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${pt(e[n])}`)}),dr(dr({},i),e)}(t.DefaultConfig,e,s);this.userConfig=e,i.progressive&&Bl(i,s);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=i,d=new o(this),h=this.abrController=new r(this),c=new Lt(this),u=i.interstitialsController,f=u?this.interstitialsController=new u(this,t):null,g=this.bufferController=new n(this,c),m=this.capLevelController=new a(this),p=new l(this),v=new qi(this),y=i.contentSteeringController,E=y?new y(this):null,T=this.levelController=new Wi(this,E),S=new Vi(this),A=new ji(this.config,this.logger),L=this.streamController=new Yi(this,c,A),I=this.gapController=new Gi(this,c);m.setStreamController(L),p.setStreamController(L);const b=[v,T,L];f&&b.splice(1,0,f),E&&b.splice(1,0,E),this.networkControllers=b;const R=[h,g,I,m,p,S,c];this.audioTrackController=this.createController(i.audioTrackController,b);const k=i.audioStreamController;k&&b.push(this.audioStreamController=new k(this,c,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,b);const D=i.subtitleStreamController;D&&b.push(this.subtititleStreamController=new D(this,c,A)),this.createController(i.timelineController,R),A.emeController=this.emeController=this.createController(i.emeController,R),this.cmcdController=this.createController(i.cmcdController,R),this.latencyController=this.createController(Hi,R),this.coreComponents=R,b.push(d);const w=d.onErrorOut;"function"==typeof w&&this.on($.ERROR,w,d),this.on($.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(s){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const e=t===$.ERROR;this.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.INTERNAL_EXCEPTION,fatal:e,event:t,error:s}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger($.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger($.ERROR,{type:O.OTHER_ERROR,details:F.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,s=e?t.media:t,i=e?t:{media:s};this._media=s,this.trigger($.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger($.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger($.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,s=this._url,i=this._url=z.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),e&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger($.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,e),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[U.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[U.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[U.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return ht.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let i=0;i<s;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let r=i;r--;){const e=t[r].attrs["HDCP-LEVEL"];if(e&&e<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return nn(t,un(e),navigator.mediaCapabilities)}}),zi.defaultConfig=void 0}}});