hr-design-system-handlebars 1.121.1 → 1.122.0

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 (190) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/assets/index.css +11 -13
  3. package/dist/assets/vendor/ardplayer/ardplayer-hr-7.7.0.074b3034.css +1 -0
  4. package/dist/assets/vendor/ardplayer/ardplayer-hr-7.7.0.eeb199f0.js +1 -0
  5. package/dist/assets/vendor/ardplayer/ardplayer-libimsc.e88e8ba8.chunk.js +12 -0
  6. package/dist/assets/vendor/ardplayer/ardplayer-pluginchromecast.280aebab.chunk.js +1 -0
  7. package/dist/assets/vendor/ardplayer/ardplayer-plugindash.e096df69.chunk.js +10 -0
  8. package/dist/assets/vendor/ardplayer/ardplayer-pluginhls.33094be9.chunk.js +1 -0
  9. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmla.084c4a0c.chunk.js +1 -0
  10. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmlv.b0dd7eb3.chunk.js +1 -0
  11. package/dist/assets/vendor/ardplayer/assets/c1bd5269b4ca32e4e463-ardplayer-audio.woff +0 -0
  12. package/dist/assets/vendor/ardplayer/assets/e672be94f918ce5743ed-ardplayer.woff +0 -0
  13. package/dist/assets/vendor/ardplayer/assets/img/3sat-316aa089.svg +1 -0
  14. package/dist/assets/vendor/ardplayer/assets/img/alpha-aa80e0b1.svg +1 -0
  15. package/dist/assets/vendor/ardplayer/assets/img/ard-7c1adb6a.svg +1 -0
  16. package/dist/assets/vendor/ardplayer/assets/img/arte-78b35a1c.svg +1 -0
  17. package/dist/assets/vendor/ardplayer/assets/img/br-91122637.svg +1 -0
  18. package/dist/assets/vendor/ardplayer/assets/img/daserste-b4a7fce0.svg +1 -0
  19. package/dist/assets/vendor/ardplayer/assets/img/deutschlandradio-8ae68d1e.svg +1 -0
  20. package/dist/assets/vendor/ardplayer/assets/img/dw-b25a6e21.svg +1 -0
  21. package/dist/assets/vendor/ardplayer/assets/img/funk-14d5562d.svg +1 -0
  22. package/dist/assets/vendor/ardplayer/assets/img/hr-f8858d2d.svg +1 -0
  23. package/dist/assets/vendor/ardplayer/assets/img/kika-cc093c6d.svg +1 -0
  24. package/dist/assets/vendor/ardplayer/assets/img/mdr-d2d11760.svg +1 -0
  25. package/dist/assets/vendor/ardplayer/assets/img/ndr-b942fbbe.svg +1 -0
  26. package/dist/assets/vendor/ardplayer/assets/img/one-bfd695dd.svg +1 -0
  27. package/dist/assets/vendor/ardplayer/assets/img/phoenix-25ae77e8.svg +1 -0
  28. package/dist/assets/vendor/ardplayer/assets/img/radiobremen-c9a22aec.svg +1 -0
  29. package/dist/assets/vendor/ardplayer/assets/img/rbb-857d0436.svg +1 -0
  30. package/dist/assets/vendor/ardplayer/assets/img/sportschau-66955185.svg +1 -0
  31. package/dist/assets/vendor/ardplayer/assets/img/sr-4d2bb786.svg +1 -0
  32. package/dist/assets/vendor/ardplayer/assets/img/swr-151e2af6.svg +1 -0
  33. package/dist/assets/vendor/ardplayer/assets/img/tagesschau24-4a1c7ee6.svg +1 -0
  34. package/dist/assets/vendor/ardplayer/assets/img/wdr-be1aba5e.svg +1 -0
  35. package/dist/assets/vendor/ardplayer/assets/img/zdf-ebb6d646.svg +1 -0
  36. package/dist/assets/vendor/ardplayer/assets/img/zdfinfo-90fdcd3b.svg +1 -0
  37. package/dist/assets/vendor/ardplayer/assets/img/zdfneo-2fba1e20.svg +1 -0
  38. package/package.json +1 -1
  39. package/src/assets/fixtures/audio/audios.inc.json +8 -8
  40. package/src/assets/fixtures/page/podcast/podcast_player_episode.json +4 -4
  41. package/src/assets/fixtures/video/videos.inc.json +8 -8
  42. package/src/assets/vendor/ardplayer/ardplayer-hr-7.7.0.074b3034.css +1 -0
  43. package/src/assets/vendor/ardplayer/ardplayer-hr-7.7.0.eeb199f0.js +1 -0
  44. package/src/assets/vendor/ardplayer/ardplayer-libimsc.e88e8ba8.chunk.js +12 -0
  45. package/src/assets/vendor/ardplayer/ardplayer-pluginchromecast.280aebab.chunk.js +1 -0
  46. package/src/assets/vendor/ardplayer/ardplayer-plugindash.e096df69.chunk.js +10 -0
  47. package/src/assets/vendor/ardplayer/ardplayer-pluginhls.33094be9.chunk.js +1 -0
  48. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmla.084c4a0c.chunk.js +1 -0
  49. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmlv.b0dd7eb3.chunk.js +1 -0
  50. package/src/assets/vendor/ardplayer/assets/c1bd5269b4ca32e4e463-ardplayer-audio.woff +0 -0
  51. package/src/assets/vendor/ardplayer/assets/e672be94f918ce5743ed-ardplayer.woff +0 -0
  52. package/src/assets/vendor/ardplayer/assets/img/3sat-316aa089.svg +1 -0
  53. package/src/assets/vendor/ardplayer/assets/img/alpha-aa80e0b1.svg +1 -0
  54. package/src/assets/vendor/ardplayer/assets/img/ard-7c1adb6a.svg +1 -0
  55. package/src/assets/vendor/ardplayer/assets/img/arte-78b35a1c.svg +1 -0
  56. package/src/assets/vendor/ardplayer/assets/img/br-91122637.svg +1 -0
  57. package/src/assets/vendor/ardplayer/assets/img/daserste-b4a7fce0.svg +1 -0
  58. package/src/assets/vendor/ardplayer/assets/img/deutschlandradio-8ae68d1e.svg +1 -0
  59. package/src/assets/vendor/ardplayer/assets/img/dw-b25a6e21.svg +1 -0
  60. package/src/assets/vendor/ardplayer/assets/img/funk-14d5562d.svg +1 -0
  61. package/src/assets/vendor/ardplayer/assets/img/hr-f8858d2d.svg +1 -0
  62. package/src/assets/vendor/ardplayer/assets/img/kika-cc093c6d.svg +1 -0
  63. package/src/assets/vendor/ardplayer/assets/img/mdr-d2d11760.svg +1 -0
  64. package/src/assets/vendor/ardplayer/assets/img/ndr-b942fbbe.svg +1 -0
  65. package/src/assets/vendor/ardplayer/assets/img/one-bfd695dd.svg +1 -0
  66. package/src/assets/vendor/ardplayer/assets/img/phoenix-25ae77e8.svg +1 -0
  67. package/src/assets/vendor/ardplayer/assets/img/radiobremen-c9a22aec.svg +1 -0
  68. package/src/assets/vendor/ardplayer/assets/img/rbb-857d0436.svg +1 -0
  69. package/src/assets/vendor/ardplayer/assets/img/sportschau-66955185.svg +1 -0
  70. package/src/assets/vendor/ardplayer/assets/img/sr-4d2bb786.svg +1 -0
  71. package/src/assets/vendor/ardplayer/assets/img/swr-151e2af6.svg +1 -0
  72. package/src/assets/vendor/ardplayer/assets/img/tagesschau24-4a1c7ee6.svg +1 -0
  73. package/src/assets/vendor/ardplayer/assets/img/wdr-be1aba5e.svg +1 -0
  74. package/src/assets/vendor/ardplayer/assets/img/zdf-ebb6d646.svg +1 -0
  75. package/src/assets/vendor/ardplayer/assets/img/zdfinfo-90fdcd3b.svg +1 -0
  76. package/src/assets/vendor/ardplayer/assets/img/zdfneo-2fba1e20.svg +1 -0
  77. package/src/stories/views/components/content/copytext/fixtures/copytext_audio-livestream.json +8 -8
  78. package/src/stories/views/components/content/copytext/fixtures/copytext_audio.json +1 -1
  79. package/src/stories/views/components/content/copytext/fixtures/copytext_audio_livestream.json +1 -1
  80. package/src/stories/views/components/content/copytext/fixtures/copytext_image.json +1 -1
  81. package/src/stories/views/components/content/copytext/fixtures/copytext_livestream.json +1 -1
  82. package/src/stories/views/components/content/copytext/fixtures/copytext_media_components.json +1 -1
  83. package/src/stories/views/components/content/copytext/fixtures/copytext_non_media_components.json +1 -1
  84. package/src/stories/views/components/content/copytext/fixtures/copytext_podcastepisode.json +1 -1
  85. package/src/stories/views/components/content/copytext/fixtures/copytext_video.json +1 -1
  86. package/src/stories/views/components/content/copytext/fixtures/copytext_video_vertical.json +1 -1
  87. package/src/stories/views/components/mediaplayer/fixtures/mediaplayer.json +1 -1
  88. package/src/stories/views/components/mediaplayer/fixtures/mediaplayer_snapshots.json +1 -1
  89. package/src/stories/views/components/page/fixtures/page.json +1 -1
  90. package/src/stories/views/components/page/podcast/fixtures/podcast_player_episode.json +1 -1
  91. package/src/stories/views/components/page/podcast/fixtures/podcast_player_playlist.json +1 -1
  92. package/src/stories/views/components/page/story/fixtures/story.json +1 -1
  93. package/src/stories/views/components/page/story/fixtures/story_with_audio.json +1 -1
  94. package/src/stories/views/components/page/story/fixtures/story_with_label.json +1 -1
  95. package/src/stories/views/components/page/story/fixtures/story_with_livestream.json +1 -1
  96. package/src/stories/views/components/page/story/fixtures/story_with_square_image.json +1 -1
  97. package/src/stories/views/components/page/story/fixtures/story_with_video.json +1 -1
  98. package/src/stories/views/components/pagination/fixtures/page_pagination.json +1 -1
  99. package/src/stories/views/components/teaser/fixtures/teaser_alternative_av.json +1 -1
  100. package/src/stories/views/components/teaser/fixtures/teaser_cluster.json +1 -1
  101. package/src/stories/views/components/teaser/fixtures/teaser_group_100.json +1 -1
  102. package/src/stories/views/components/teaser/fixtures/teaser_group_100_highlight.json +1 -1
  103. package/src/stories/views/components/teaser/fixtures/teaser_group_100_highlight_2.json +1 -1
  104. package/src/stories/views/components/teaser/fixtures/teaser_group_related_content_100.json +1 -1
  105. package/src/stories/views/components/teaser/fixtures/teaser_index.json +1 -1
  106. package/src/stories/views/components/teaser/fixtures/teaser_podcast.json +1 -1
  107. package/src/stories/views/components/teaser/fixtures/teaser_podcast_50.json +1 -1
  108. package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist.json +1 -1
  109. package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist_50.json +1 -1
  110. package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist_filter.json +1 -1
  111. package/src/stories/views/components/teaser/fixtures/teaser_standard_av.json +1 -1
  112. package/src/stories/views/components/teaser/fixtures/teaser_tabbox.json +1 -1
  113. package/src/stories/views/components/teaser/fixtures/teaser_ticker_alternative.json +1 -1
  114. package/src/stories/views/components/teaser/fixtures/teaser_ticker_standard.json +1 -1
  115. package/src/stories/views/components/teaser/fixtures/teaser_vertical_video.json +1 -1
  116. package/src/stories/views/components/voting/fixtures/voting.json +1 -1
  117. package/src/stories/views/components/voting/fixtures/voting_media_audio_horizontal.json +1 -1
  118. package/src/stories/views/components/voting/fixtures/voting_media_audio_vertical.json +1 -1
  119. package/src/stories/views/components/voting/fixtures/voting_media_video_horizontal.json +1 -1
  120. package/src/stories/views/components/voting/fixtures/voting_media_video_vertical.json +1 -1
  121. package/dist/assets/vendor/ardplayer/ardplayer-hr-7.2.0.07145e1b.js +0 -1
  122. package/dist/assets/vendor/ardplayer/ardplayer-hr-7.2.0.bdf782df.css +0 -1
  123. package/dist/assets/vendor/ardplayer/ardplayer-libimsc.34d59351.chunk.js +0 -12
  124. package/dist/assets/vendor/ardplayer/ardplayer-pluginchromecast.017a470e.chunk.js +0 -1
  125. package/dist/assets/vendor/ardplayer/ardplayer-plugindash.6abc107d.chunk.js +0 -10
  126. package/dist/assets/vendor/ardplayer/ardplayer-pluginhls.e7b33d74.chunk.js +0 -1
  127. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmla.7a21b373.chunk.js +0 -1
  128. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmlv.8e08609e.chunk.js +0 -1
  129. package/dist/assets/vendor/ardplayer/assets/47bf64197ce0a282ef55-ardplayer-audio.woff +0 -0
  130. package/dist/assets/vendor/ardplayer/assets/553e21224d0386ee58f0-ardplayer.woff +0 -0
  131. package/dist/assets/vendor/ardplayer/assets/img/3sat-97c7c01a.svg +0 -1
  132. package/dist/assets/vendor/ardplayer/assets/img/alpha-29b57b3e.svg +0 -1
  133. package/dist/assets/vendor/ardplayer/assets/img/ard-b0376fe1.svg +0 -1
  134. package/dist/assets/vendor/ardplayer/assets/img/arte-8a174832.svg +0 -1
  135. package/dist/assets/vendor/ardplayer/assets/img/br-1a782a5d.svg +0 -1
  136. package/dist/assets/vendor/ardplayer/assets/img/daserste-d6363449.svg +0 -1
  137. package/dist/assets/vendor/ardplayer/assets/img/deutschlandradio-100cce3c.svg +0 -1
  138. package/dist/assets/vendor/ardplayer/assets/img/dw-00fab9c1.svg +0 -1
  139. package/dist/assets/vendor/ardplayer/assets/img/funk-605fd714.svg +0 -1
  140. package/dist/assets/vendor/ardplayer/assets/img/hr-f06b736c.svg +0 -1
  141. package/dist/assets/vendor/ardplayer/assets/img/kika-5a7ddc5f.svg +0 -1
  142. package/dist/assets/vendor/ardplayer/assets/img/mdr-147ffd56.svg +0 -1
  143. package/dist/assets/vendor/ardplayer/assets/img/ndr-af21bb92.svg +0 -1
  144. package/dist/assets/vendor/ardplayer/assets/img/one-7594520c.svg +0 -1
  145. package/dist/assets/vendor/ardplayer/assets/img/phoenix-49a512ab.svg +0 -1
  146. package/dist/assets/vendor/ardplayer/assets/img/radiobremen-6ffa63ff.svg +0 -1
  147. package/dist/assets/vendor/ardplayer/assets/img/rbb-6653f6ea.svg +0 -1
  148. package/dist/assets/vendor/ardplayer/assets/img/sportschau-eaa739f1.svg +0 -1
  149. package/dist/assets/vendor/ardplayer/assets/img/sr-f5ae5aae.svg +0 -1
  150. package/dist/assets/vendor/ardplayer/assets/img/swr-3573dc63.svg +0 -1
  151. package/dist/assets/vendor/ardplayer/assets/img/tagesschau24-51c2e8ef.svg +0 -1
  152. package/dist/assets/vendor/ardplayer/assets/img/wdr-db5a40ca.svg +0 -1
  153. package/dist/assets/vendor/ardplayer/assets/img/zdf-2d26a61f.svg +0 -1
  154. package/dist/assets/vendor/ardplayer/assets/img/zdfinfo-47a13356.svg +0 -1
  155. package/dist/assets/vendor/ardplayer/assets/img/zdfneo-41061594.svg +0 -1
  156. package/src/assets/vendor/ardplayer/ardplayer-hr-7.2.0.07145e1b.js +0 -1
  157. package/src/assets/vendor/ardplayer/ardplayer-hr-7.2.0.bdf782df.css +0 -1
  158. package/src/assets/vendor/ardplayer/ardplayer-libimsc.34d59351.chunk.js +0 -12
  159. package/src/assets/vendor/ardplayer/ardplayer-pluginchromecast.017a470e.chunk.js +0 -1
  160. package/src/assets/vendor/ardplayer/ardplayer-plugindash.6abc107d.chunk.js +0 -10
  161. package/src/assets/vendor/ardplayer/ardplayer-pluginhls.e7b33d74.chunk.js +0 -1
  162. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmla.7a21b373.chunk.js +0 -1
  163. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmlv.8e08609e.chunk.js +0 -1
  164. package/src/assets/vendor/ardplayer/assets/47bf64197ce0a282ef55-ardplayer-audio.woff +0 -0
  165. package/src/assets/vendor/ardplayer/assets/553e21224d0386ee58f0-ardplayer.woff +0 -0
  166. package/src/assets/vendor/ardplayer/assets/img/3sat-97c7c01a.svg +0 -1
  167. package/src/assets/vendor/ardplayer/assets/img/alpha-29b57b3e.svg +0 -1
  168. package/src/assets/vendor/ardplayer/assets/img/ard-b0376fe1.svg +0 -1
  169. package/src/assets/vendor/ardplayer/assets/img/arte-8a174832.svg +0 -1
  170. package/src/assets/vendor/ardplayer/assets/img/br-1a782a5d.svg +0 -1
  171. package/src/assets/vendor/ardplayer/assets/img/daserste-d6363449.svg +0 -1
  172. package/src/assets/vendor/ardplayer/assets/img/deutschlandradio-100cce3c.svg +0 -1
  173. package/src/assets/vendor/ardplayer/assets/img/dw-00fab9c1.svg +0 -1
  174. package/src/assets/vendor/ardplayer/assets/img/funk-605fd714.svg +0 -1
  175. package/src/assets/vendor/ardplayer/assets/img/hr-f06b736c.svg +0 -1
  176. package/src/assets/vendor/ardplayer/assets/img/kika-5a7ddc5f.svg +0 -1
  177. package/src/assets/vendor/ardplayer/assets/img/mdr-147ffd56.svg +0 -1
  178. package/src/assets/vendor/ardplayer/assets/img/ndr-af21bb92.svg +0 -1
  179. package/src/assets/vendor/ardplayer/assets/img/one-7594520c.svg +0 -1
  180. package/src/assets/vendor/ardplayer/assets/img/phoenix-49a512ab.svg +0 -1
  181. package/src/assets/vendor/ardplayer/assets/img/radiobremen-6ffa63ff.svg +0 -1
  182. package/src/assets/vendor/ardplayer/assets/img/rbb-6653f6ea.svg +0 -1
  183. package/src/assets/vendor/ardplayer/assets/img/sportschau-eaa739f1.svg +0 -1
  184. package/src/assets/vendor/ardplayer/assets/img/sr-f5ae5aae.svg +0 -1
  185. package/src/assets/vendor/ardplayer/assets/img/swr-3573dc63.svg +0 -1
  186. package/src/assets/vendor/ardplayer/assets/img/tagesschau24-51c2e8ef.svg +0 -1
  187. package/src/assets/vendor/ardplayer/assets/img/wdr-db5a40ca.svg +0 -1
  188. package/src/assets/vendor/ardplayer/assets/img/zdf-2d26a61f.svg +0 -1
  189. package/src/assets/vendor/ardplayer/assets/img/zdfinfo-47a13356.svg +0 -1
  190. package/src/assets/vendor/ardplayer/assets/img/zdfneo-41061594.svg +0 -1
@@ -0,0 +1 @@
1
+ (globalThis.webpackChunkardplayer=globalThis.webpackChunkardplayer||[]).push([[965],{24091:module=>{!function t(e){module.exports=function(){"use strict";function i(t,e,i){if(d())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var s=new(t.bind.apply(t,r));return i&&f(s,i.prototype),s}function r(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,m(r.key),r)}}function s(t,e,i){return e&&r(t.prototype,e),i&&r(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function n(t,e,i){return(e=m(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function a(){return a=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},a.apply(null,arguments)}function o(t){return o=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},o(t)}function l(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,f(t,e)}function h(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}function d(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(d=function(){return!!t})()}function u(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function c(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?u(Object(i),!0).forEach((function(e){n(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):u(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function f(t,e){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},f(t,e)}function g(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}function m(t){var e=g(t,"string");return"symbol"==typeof e?e:e+""}function p(t){var e="function"==typeof Map?new Map:void 0;return p=function(t){if(null===t||!h(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return i(t,arguments,o(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),f(r,t)},p(t)}function v(){try{return crypto.randomUUID()}catch(r){try{var t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=(i+16*Math.random())%16|0;return i=Math.floor(i/16),("x"==t?e:3&e|8).toString(16)}))}}}function y(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var E,T={exports:{}};function S(){return E||(E=1,function(module){var t=Object.prototype.hasOwnProperty,e="~";function i(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function s(t,i,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=e?e+i:i;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 n(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(e=!1)),a.prototype.eventNames=function(){var i,r,s=[];if(0===this._eventsCount)return s;for(r in i=this._events)t.call(i,r)&&s.push(e?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(i)):s},a.prototype.listeners=function(t){var i=e?e+t:t,r=this._events[i];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},a.prototype.listenerCount=function(t){var i=e?e+t:t,r=this._events[i];return r?r.fn?1:r.length:0},a.prototype.emit=function(t,i,r,s,n,a){var o=e?e+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,r),!0;case 4:return d.fn.call(d.context,i,r,s),!0;case 5:return d.fn.call(d.context,i,r,s,n),!0;case 6:return d.fn.call(d.context,i,r,s,n,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,i);break;case 3:d[h].fn.call(d[h].context,i,r);break;case 4:d[h].fn.call(d[h].context,i,r,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return s(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return s(this,t,e,i,!0)},a.prototype.removeListener=function(t,i,r,s){var a=e?e+t:t;if(!this._events[a])return this;if(!i)return n(this,a),this;var o=this._events[a];if(o.fn)o.fn!==i||s&&!o.once||r&&o.context!==r||n(this,a);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==i||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},a.prototype.removeAllListeners=function(t){var r;return t?(r=e?e+t:t,this._events[r]&&n(this,r)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,module.exports=a}(T)),T.exports}var A,L=y(S()),R={exports:{}};function I(){return A||(A=1,function(module,t){var e,i,r,s,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var s=n.parseURL(t);if(!s)throw new Error("Error trying to parse base URL.");return s.path=n.normalizePath(s.path),n.buildURLFromParts(s)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(u)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=r.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(r,"");t.length!==(t=t.replace(s,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},module.exports=n}(R)),R.exports}var b=I(),k=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},D=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=_},_=Number.MAX_SAFE_INTEGER||9007199254740991,P=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),C=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}({}),w=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}({}),O={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},x={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},M=function(){function t(t,e,i){void 0===e&&(e=0),void 0===i&&(i=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_=i}var e=t.prototype;return e.sample=function(t,e){var i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),F=function(){function t(t,e,i,r){void 0===r&&(r=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_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new M(t),this.fast_=new M(e),this.defaultTTFB_=r,this.ttfb_=new M(t)}var e=t.prototype;return e.update=function(t,e){var i=this.slow_,r=this.fast_,s=this.ttfb_;i.halfLife!==t&&(this.slow_=new M(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.fast_=new M(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new M(t,s.getEstimate(),s.getTotalWeight()))},e.sample=function(t,e){var i=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/i;this.fast_.sample(i,r),this.slow_.sample(i,r)},e.sampleTTFB=function(t){var e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))},e.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},e.destroy=function(){},s(t,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),N=function(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;var i="["+t+"]:";this.trace=U,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)},U=function(){},B={trace:U,debug:U,log:U,warn:U,info:U,error:U};function G(){return a({},B)}function $(t,e){var i=self.console[t];return i?i.bind(self.console,(e?"["+e+"] ":"")+"["+t+"] >"):U}function K(t,e,i){return e[t]?e[t].bind(e):$(t,i)}var V=G();function H(t,e,i){var r=G();if("object"==typeof console&&!0===t||"object"==typeof t){var s=["debug","log","info","warn","error"];s.forEach((function(e){r[e]=K(e,t,i)}));try{r.log('Debug logs enabled for "'+e+'" in hls.js version 1.6.9')}catch(t){return G()}s.forEach((function(e){V[e]=K(e,t)}))}else a(V,r);return r}var Y=V;function W(t){if(void 0===t&&(t=!0),"undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function j(t){return"undefined"!=typeof self&&t===self.ManagedMediaSource}function q(t,e){var i=Object.keys(t),r=Object.keys(e),s=i.length,n=r.length;return!s||!n||s===n&&!i.some((function(t){return-1===r.indexOf(t)}))}function X(t,e){if(void 0===e&&(e=!1),"undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(t);if(e){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.replace(/\0/g,"")}for(var s,n,a,o=t.length,l="",h=0;h<o;){if(0===(s=t[h++])&&e)return l;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(s);break;case 12:case 13:n=t[h++],l+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=t[h++],a=t[h++],l+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return l}var Q={hexDump:function(t){for(var e="",i=0;i<t.length;i++){var r=t[i].toString(16);r.length<2&&(r="0"+r),e+=r}return e}};function z(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var Z=function(){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}},J={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},tt=function(){function t(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,nt(this,"stats")}var e=t.prototype;return e.setByteRange=function(t,e){var i,r=t.split("@",2);i=1===r.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]},e.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[J.AUDIO]=null,t[J.VIDEO]=null,t[J.AUDIOVIDEO]=null},s(t,[{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){var t;return null===this._streams&&(this._streams=((t={})[J.AUDIO]=null,t[J.VIDEO]=null,t[J.AUDIOVIDEO]=null,t)),this._streams},set:function(t){this._streams=t}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new Z),this._stats},set:function(t){this._stats=t}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=b.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(t){this._url=t}}])}();function et(t){return"initSegment"!==t.sn}var it=function(t){function e(e,i){var r;return(r=t.call(this,i)||this)._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=e,r}l(e,t);var i=e.prototype;return i.addStart=function(t){this.setStart(this.start+t)},i.setStart=function(t){this.start=t,this._ref&&(this._ref.start=t)},i.setDuration=function(t){this.duration=t,this._ref&&(this._ref.duration=t)},i.setKeyFormat=function(t){if(this.levelkeys){var e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}},i.abortRequests=function(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()},i.setElementaryStreamInfo=function(t,e,i,r,s,n){void 0===n&&(n=!1);var a=this.elementaryStreams,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:i,startDTS:r,endDTS:s,partial:n}},s(e,[{key:"byteLength",get:function(){if(this.hasStats){var t=this.stats.total;if(t)return t}if(this.byteRange.length){var e=this.byteRange[0],i=this.byteRange[1];if(k(e)&&k(i))return i-e}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(t){this._bitrate=t}},{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{var e=Object.keys(this.levelkeys);if(1===e.length){var i=this._decryptdata=this.levelkeys[e[0]]||null;if(i)return i.getDecryptData(this.sn)}}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var t=k(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e,i=Object.keys(this.levelkeys),r=i.length;if(r>1||1===r&&null!=(e=this.levelkeys[i[0]])&&e.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(t){k(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(tt),rt=function(t){function e(e,i,r,s,n){var a;(a=t.call(this,r)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.duration=e.decimalFloatingPoint("DURATION"),a.gap=e.bool("GAP"),a.independent=e.bool("INDEPENDENT"),a.relurl=e.enumeratedString("URI"),a.fragment=i,a.index=s;var o=e.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,n),n&&(a.fragOffset=n.fragOffset+n.duration),a}return l(e,t),s(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}])}(tt);function st(t,e){var i=Object.getPrototypeOf(t);if(i){var r=Object.getOwnPropertyDescriptor(i,e);return r||st(i,e)}}function nt(t,e){var i=st(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}var at=Math.pow(2,32)-1,ot=[].push,lt={video:1,audio:2,id3:3,text:4};function ht(t){return String.fromCharCode.apply(null,t)}function dt(t,e){var i=t[e]<<8|t[e+1];return i<0?65536+i:i}function ut(t,e){var i=ft(t,e);return i<0?4294967296+i:i}function ct(t,e){var i=ut(t,e);return i*=Math.pow(2,32),i+=ut(t,e+4)}function ft(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function gt(t){for(var e=t.byteLength,i=0;i<e;){var r=ut(t,i);if(r>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=r>1?i+r:e}return!1}function mt(t,e){var i=[];if(!e.length)return i;for(var r=t.byteLength,s=0;s<r;){var n=ut(t,s),a=n>1?s+n:r;if(ht(t.subarray(s+4,s+8))===e[0])if(1===e.length)i.push(t.subarray(s+8,a));else{var o=mt(t.subarray(s+8,a),e.slice(1));o.length&&ot.apply(i,o)}s=a}return i}function pt(t){var e=[],i=t[0],r=8,s=ut(t,r);r+=4;var n=0,a=0;0===i?(n=ut(t,r),a=ut(t,r+4),r+=8):(n=ct(t,r),a=ct(t,r+8),r+=16),r+=2;var o=t.length+a,l=dt(t,r);r+=2;for(var h=0;h<l;h++){var d=r,u=ut(t,d);d+=4;var c=2147483647&u;if(1==(2147483648&u)>>>31)return Y.warn("SIDX has hierarchical references (not supported)"),null;var f=ut(t,d);d+=4,e.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,r=d+=4}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:e}}function vt(t){for(var e=[],i=mt(t,["moov","trak"]),r=0;r<i.length;r++){var s=i[r],n=mt(s,["tkhd"])[0];if(n){var a=n[0],o=ut(n,0===a?12:20),l=mt(s,["mdia","mdhd"])[0];if(l){var h=ut(l,0===(a=l[0])?12:20),d=mt(s,["mdia","hdlr"])[0];if(d){var u=ht(d.subarray(8,12)),f={soun:J.AUDIO,vide:J.VIDEO}[u],g=yt(mt(s,["mdia","minf","stbl","stsd"])[0]);f?(e[o]={timescale:h,type:f,stsd:g},e[f]=c({timescale:h,id:o},g)):e[o]={timescale:h,type:u,stsd:g}}}}}return mt(t,["moov","mvex","trex"]).forEach((function(t){var i=ut(t,4),r=e[i];r&&(r.default={duration:ut(t,12),flags:ut(t,20)})})),e}function yt(t){var e,i=t.subarray(8),r=i.subarray(86),s=ht(i.subarray(4,8)),n=s,a="enca"===s||"encv"===s;if(a){var o=mt(i,[s])[0];mt(o.subarray("enca"===s?28:78),["sinf"]).forEach((function(t){var e=mt(t,["schm"])[0];if(e){var i=ht(e.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=mt(t,["frma"])[0];r&&(n=ht(r))}}}))}var l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":var h=mt(r,["avcC"])[0];h&&h.length>3&&(n+="."+At(h[1])+At(h[2])+At(h[3]),e=Et("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var d=mt(i,[s])[0],u=mt(d.subarray(28),["esds"])[0];if(u&&u.length>7){var c=4;if(3!==u[c++])break;c=St(u,c),c+=2;var f=u[c++];if(128&f&&(c+=2),64&f&&(c+=u[c++]),4!==u[c++])break;c=St(u,c);var g=u[c++];if(64!==g)break;if(n+="."+At(g),c+=12,5!==u[c++])break;c=St(u,c);var m=u[c++],p=(248&m)>>3;31===p&&(p+=1+((7&m)<<3)+((224&u[c])>>5)),n+="."+p}break;case"hvc1":case"hev1":var v=mt(r,["hvcC"])[0];if(v&&v.length>12){var y=v[1],E=["","A","B","C"][y>>6],T=31&y,S=ut(v,2),A=(32&y)>>5?"H":"L",L=v[12],R=v.subarray(6,12);n+="."+E+T,n+="."+Tt(S).toString(16).toUpperCase(),n+="."+A+L;for(var I="",b=R.length;b--;){var k=R[b];(k||I)&&(I="."+k.toString(16).toUpperCase()+I)}n+=I}e=Et("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Et(n,r)||n;break;case"vp09":var D=mt(r,["vpcC"])[0];if(D&&D.length>6){var _=D[4],P=D[5],C=D[6]>>4&15;n+="."+Lt(_)+"."+Lt(P)+"."+Lt(C)}break;case"av01":var w=mt(r,["av1C"])[0];if(w&&w.length>2){var O=w[1]>>>5,x=31&w[1],M=w[2]>>>7?"H":"M",F=(64&w[2])>>6,N=(32&w[2])>>5,U=2===O&&F?N?12:10:F?10:8,B=(16&w[2])>>4,G=(8&w[2])>>3,$=(4&w[2])>>2,K=3&w[2],V=1,H=1,Y=1,W=0;n+="."+O+"."+Lt(x)+M+"."+Lt(U)+"."+B+"."+G+$+K+"."+Lt(V)+"."+Lt(H)+"."+Lt(Y)+"."+W,e=Et("dav1",r)}}return{codec:n,encrypted:a,supplemental:e}}function Et(t,e){var i=mt(e,["dvvC"]),r=i.length?i[0]:mt(e,["dvcC"])[0];if(r){var s=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return t+"."+Lt(s)+"."+Lt(n)}}function Tt(t){for(var e=0,i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}function St(t,e){for(var i=e+5;128&t[e++]&&e<i;);return e}function At(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Lt(t){return(t<10?"0":"")+t}function Rt(t,e){if(t&&e){var i=e.keyId;i&&e.isCommonEncryption&&mt(t,["moov","trak"]).forEach((function(t){var e=mt(t,["mdia","minf","stbl","stsd"])[0].subarray(8),r=mt(e,["enca"]),s=r.length>0;s||(r=mt(e,["encv"])),r.forEach((function(t){mt(s?t.subarray(28):t.subarray(78),["sinf"]).forEach((function(t){var e=It(t);if(e){var r=e.subarray(8,24);r.some((function(t){return 0!==t}))||(Y.log("[eme] Patching keyId in 'enc"+(s?"a":"v")+">sinf>>tenc' box: "+Q.hexDump(r)+" -> "+Q.hexDump(i)),e.set(i,8))}}))}))}))}}function It(t){var e=mt(t,["schm"])[0];if(e){var i=ht(e.subarray(4,8));if("cbcs"===i||"cenc"===i)return mt(t,["schi","tenc"])[0]}return null}function bt(t,e,i){for(var r={},s=mt(t,["moof","traf"]),n=0;n<s.length;n++){var a=s[n],o=mt(a,["tfhd"])[0],l=ut(o,4),h=e[l];if(h){r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:h.timescale,type:h.type});var d=r[l],u=mt(a,["tfdt"])[0];if(u){var c=u[0],f=ut(u,4);1===c&&(f===at?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=at+1,f+=ut(u,8))),k(f)&&(!k(d.start)||f<d.start)&&(d.start=f)}var g=h.default,m=ut(o,0)|(null==g?void 0:g.flags),p=(null==g?void 0:g.duration)||0;8&m&&(p=ut(o,2&m?12:8));for(var v=mt(a,["trun"]),y=d.start||0,E=0,T=p,S=0;S<v.length;S++){var A=v[S],L=ut(A,4),R=d.sampleCount;d.sampleCount+=L;var I=1&A[3],b=4&A[3],D=1&A[2],_=2&A[2],P=4&A[2],C=8&A[2],w=8,O=L;for(I&&(w+=4),b&&L&&(1&A[w+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=R),w+=4,D?(T=ut(A,w),w+=4):T=p,_&&(w+=4),C&&(w+=4),y+=T,E+=T,O--);O--;)D?(T=ut(A,w),w+=4):T=p,_&&(w+=4),P&&(1&A[w+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(O+1),d.keyFrameStart=y),w+=4),C&&(w+=4),y+=T,E+=T;!E&&p&&(E+=p*L)}d.duration+=E}}if(!Object.keys(r).some((function(t){return r[t].duration}))){for(var x=1/0,M=0,F=mt(t,["sidx"]),N=0;N<F.length;N++){var U=pt(F[N]);if(null!=U&&U.references){x=Math.min(x,U.earliestPresentationTime/U.timescale);var B=U.references.reduce((function(t,e){return t+e.info.duration||0}),0);M=Math.max(M,B+U.earliestPresentationTime/U.timescale)}}M&&k(M)&&Object.keys(r).forEach((function(t){r[t].duration||(r[t].duration=M*r[t].timescale-r[t].start)}))}return r}function kt(t){var e={valid:null,remainder:null},i=mt(t,["moof"]);if(i.length<2)return e.remainder=t,e;var r=i[i.length-1];return e.valid=t.slice(0,r.byteOffset-8),e.remainder=t.slice(r.byteOffset-8),e}function Dt(t,e){var i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function _t(t,e){var i=[],r=e.samples,s=e.timescale,n=e.id,a=!1;return mt(r,["moof"]).map((function(o){var l=o.byteOffset-8;mt(o,["traf"]).map((function(o){var h=mt(o,["tfdt"]).map((function(t){var e=t[0],i=ut(t,4);return 1===e&&(i*=Math.pow(2,32),i+=ut(t,8)),i/s}))[0];return void 0!==h&&(t=h),mt(o,["tfhd"]).map((function(h){var d=ut(h,4),u=16777215&ut(h,0),c=0,f=!!(16&u),g=0,m=!!(32&u),p=8;d===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=ut(h,p),p+=4),f&&(g=ut(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=Pt(e.codec)),mt(o,["trun"]).map((function(n){var o=n[0],h=16777215&ut(n,0),d=!!(1&h),u=0,f=!!(4&h),m=!!(256&h),p=0,v=!!(512&h),y=0,E=!!(1024&h),T=!!(2048&h),S=0,A=ut(n,4),L=8;d&&(u=ut(n,L),L+=4),f&&(L+=4);for(var R=u+l,I=0;I<A;I++){if(m?(p=ut(n,L),L+=4):p=c,v?(y=ut(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?ut(n,L):ft(n,L),L+=4),e.type===J.VIDEO)for(var b=0;b<y;){var k=ut(r,R);Ct(a,r[R+=4])&&wt(r.subarray(R,R+k),a?2:1,t+S/s,i),R+=k,b+=k+4}t+=p/s}})))}))}))})),i}function Pt(t){if(!t)return!1;var e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Ct(t,e){if(t){var i=e>>1&63;return 39===i||40===i}return 6==(31&e)}function wt(t,e,i,r){var s=Ot(t),n=0;n+=e;for(var a=0,o=0,l=0;n<s.length;){a=0;do{if(n>=s.length)break;a+=l=s[n++]}while(255===l);o=0;do{if(n>=s.length)break;o+=l=s[n++]}while(255===l);var h=s.length-n,d=n;if(o<h)n+=o;else if(o>h){Y.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===s[d++]){var u=dt(s,d);if(d+=2,49===u){var c=ut(s,d);if(d+=4,1195456820===c){var f=s[d++];if(3===f){var g=s[d++],m=64&g,p=m?2+3*(31&g):0,v=new Uint8Array(p);if(m){v[0]=g;for(var y=1;y<p;y++)v[y]=s[d++]}r.push({type:f,payloadType:a,pts:i,bytes:v})}}}}}else if(5===a&&o>16){for(var E=[],T=0;T<16;T++){var S=s[d++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var A=o-16,L=new Uint8Array(A),R=0;R<A;R++)L[R]=s[d++];r.push({payloadType:a,pts:i,uuid:E.join(""),userData:X(L),userDataBytes:L})}}}function Ot(t){for(var e=t.byteLength,i=[],r=1;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return t;var s=e-i.length,n=new Uint8Array(s),a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=t[a];return n}function xt(t){var e=t[0],i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==ht(t.subarray(h,h+1));)i+=ht(t.subarray(h,h+1)),h+=1;for(i+=ht(t.subarray(h,h+1)),h+=1;"\0"!==ht(t.subarray(h,h+1));)r+=ht(t.subarray(h,h+1)),h+=1;r+=ht(t.subarray(h,h+1)),h+=1,s=ut(t,12),n=ut(t,16),o=ut(t,20),l=ut(t,24),h=28}else if(1===e){s=ut(t,h+=4);var d=ut(t,h+=4),u=ut(t,h+=4);for(h+=4,a=Math.pow(2,32)*d+u,D(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=ut(t,h),l=ut(t,h+=4),h+=4;"\0"!==ht(t.subarray(h,h+1));)i+=ht(t.subarray(h,h+1)),h+=1;for(i+=ht(t.subarray(h,h+1)),h+=1;"\0"!==ht(t.subarray(h,h+1));)r+=ht(t.subarray(h,h+1)),h+=1;r+=ht(t.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}function Mt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];for(var s=i.length,n=8,a=s;a--;)n+=i[a].byteLength;var o=new Uint8Array(n);for(o[0]=n>>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=255&n,o.set(t,4),a=0,n=8;a<s;a++)o.set(i[a],n),n+=i[a].byteLength;return o}function Ft(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");var r,s,n;r=0,s=new Uint8Array,r>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;var a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),Mt([112,115,115,104],new Uint8Array([r,0,0,0]),t,n,s,a,i)}var Nt=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},Ut={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Bt(t,e){var i=Ut[e];return!!i&&!!i[t.slice(0,4)]}function Gt(t,e,i){return void 0===i&&(i=!0),!t.split(",").some((function(t){return!$t(t,e,i)}))}function $t(t,e,i){var r;void 0===i&&(i=!0);var s=W(i);return null!=(r=null==s?void 0:s.isTypeSupported(Kt(t,e)))&&r}function Kt(t,e){return e+"/mp4;codecs="+t}function Vt(t){if(t){var e=t.substring(0,4);return Ut.video[e]}return 2}function Ht(t){var e=Nt();return t.split(",").reduce((function(t,i){var r=e&&Pt(i)?9:Ut.video[i];return r?(2*r+t)/(t?3:2):(Ut.audio[i]+t)/(t?2:1)}),0)}var Yt={};function Wt(t,e){if(void 0===e&&(e=!0),Yt[t])return Yt[t];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t],r=0;r<i.length;r++){var s;if($t(i[r],"audio",e))return Yt[t]=i[r],i[r];if("mp3"===i[r]&&null!=(s=W(e))&&s.isTypeSupported("audio/mpeg"))return""}return t}var jt=/flac|opus|mp4a\.40\.34/i;function qt(t,e){return void 0===e&&(e=!0),t.replace(jt,(function(t){return Wt(t.toLowerCase(),e)}))}function Xt(t,e){var i=[];if(t)for(var r=t.split(","),s=0;s<r.length;s++)Bt(r[s],"video")||i.push(r[s]);return e&&i.push(e),i.join(",")}function Qt(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(zt(t,"audio")||zt(t,"video")))return t;if(e){var i=e.split(",");if(i.length>1){if(t)for(var r=i.length;r--;)if(i[r].substring(0,4)===t.substring(0,4))return i[r];return i[0]}}return e||t}function zt(t,e){return Bt(t,e)&&$t(t,e)}function Zt(t){for(var e=t.split(","),i=0;i<e.length;i++){var r=e[i].split(".");r.length>2&&"avc1"===r[0]&&(e[i]="avc1."+parseInt(r[1]).toString(16)+("000"+parseInt(r[2]).toString(16)).slice(-4))}return e.join(",")}function Jt(t){if(t.startsWith("av01.")){for(var e=t.split("."),i=["0","111","01","01","01","0"],r=e.length;r>4&&r<10;r++)e[r]=i[r-4];return e.join(".")}return t}function te(t){var e=W(t)||{isTypeSupported:function(){return!1}};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ee(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var ie={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function re(t,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:t}}function se(t,e,i,r,s,n){var a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):l?1/0:2,u=null;if(null!=o&&o.length)try{u=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((function(t,i){if(i){var r=e.groups[i];if(!r)throw new Error("Audio track group "+i+" not found");Object.keys(r.channels).forEach((function(e){t[e]=(t[e]||0)+r.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==a&&(a.split(",").some((function(t){return Pt(t)}))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(s,8e6))||!!u&&k(d)&&Object.keys(u).some((function(t){return parseInt(t)>d}))}function ne(t,e,i,r){void 0===r&&(r={});var s=t.videoCodec;if(!s&&!t.audioCodec||!i)return Promise.resolve(ie);for(var n=[],a=ae(t),o=a.length,l=oe(t,e,o>0),h=l.length,d=o||1*h||1;d--;){var u={type:"media-source"};if(o&&(u.video=a[d%o]),h){u.audio=l[d%h];var c=u.audio.bitrate;u.video&&c&&(u.video.bitrate-=c)}n.push(u)}if(s){var f=navigator.userAgent;if(s.split(",").some((function(t){return Pt(t)}))&&Nt())return Promise.resolve(re(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: ("+f+")"),n))}return Promise.all(n.map((function(t){var e=de(t);return r[e]||(r[e]=i.decodingInfo(t))}))).then((function(t){return{supported:!t.some((function(t){return!t.supported})),configurations:n,decodingInfoResults:t}})).catch((function(t){return{supported:!1,configurations:n,decodingInfoResults:[],error:t}}))}function ae(t){var e,i=null==(e=t.videoCodec)?void 0:e.split(","),r=he(t),s=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map((function(t){var e={contentType:Kt(Jt(t),"video"),width:s,height:n,bitrate:r,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e})):[]}function oe(t,e,i){var r,s=null==(r=t.audioCodec)?void 0:r.split(","),n=he(t);return s&&t.audioGroups?t.audioGroups.reduce((function(t,r){var a,o=r?null==(a=e.groups[r])?void 0:a.tracks:null;return o?o.reduce((function(t,e){if(e.groupId===r){var a=parseFloat(e.channels||"");s.forEach((function(e){var r={contentType:Kt(e,"audio"),bitrate:i?le(e,n):n};a&&(r.channels=""+a),t.push(r)}))}return t}),t):t}),[]):[]}function le(t,e){if(e<=1)return 1;var i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function he(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function de(t){var e="",i=t.audio,r=t.video;return r&&(e+=ee(r.contentType)+"_r"+r.height+"x"+r.width+"f"+Math.ceil(r.framerate)+(r.transferFunction||"sd")+"_"+Math.ceil(r.bitrate/1e5)),i&&(e+=(r?"_":"")+ee(i.contentType)+"_c"+i.channels),e}var ue=["NONE","TYPE-0","TYPE-1",null];function ce(t){return ue.indexOf(t)>-1}var fe=["SDR","PQ","HLG"];function ge(t){return!!t&&fe.indexOf(t)>-1}var me={No:"",Yes:"YES",v2:"v2"};function pe(t){var e=t.canSkipUntil,i=t.canSkipDateRanges,r=t.age;return e&&r<e/2?i?me.v2:me.Yes:me.No}var ve=function(){function t(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}return t.prototype.addDirectives=function(t){var 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},t}(),ye=function(){function t(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((function(t){return!!t})).map((function(t){return t.substring(0,4)})).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;var i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=","+i.substring(0,4))}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}var e=t.prototype;return e.hasAudioGroup=function(t){return Ee(this._audioGroups,t)},e.hasSubtitleGroup=function(t){return Ee(this._subtitleGroups,t)},e.addGroupId=function(t,e){if(e)if("audio"===t){var i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(e)&&i.push(e)}else if("text"===t){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(e)&&r.push(e)}},e.addFallback=function(){},s(t,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(t){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var t;return null==(t=this.audioGroups)?void 0:t[0]}},{key:"textGroupId",get:function(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}}])}();function Ee(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Te(){if("function"==typeof matchMedia){var t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}function Se(t,e){var i=!1,r=[];if(t&&(i="SDR"!==t,r=[t]),e){var s="SDR"!==(r=e.allowedVideoRanges||fe.slice(0)).join("")&&!e.videoCodec;(i=void 0!==e.preferHDR?e.preferHDR:s&&Te())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}var Ae=function(t){var e=new WeakSet;return function(i,r){if(t&&(r=t(i,r)),"object"==typeof r&&null!==r){if(e.has(r))return;e.add(r)}return r}},Le=function(t,e){return JSON.stringify(t,Ae(e))};function Re(t,e,i,r,s){for(var n=Object.keys(t),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==s?void 0:s.videoCodec,h=a&&2===parseInt(a),d=!1,u=!1,c=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[],y=Se(e,s),E=y.preferHDR,T=y.allowedVideoRanges,S=function(){var e=t[n[A]];d||(d=e.channels[2]>0),c=Math.min(c,e.minHeight),f=Math.min(f,e.minFramerate),g=Math.min(g,e.minBitrate),T.filter((function(t){return e.videoRanges[t]>0})).length>0&&(u=!0)},A=n.length;A--;)S();c=k(c)?c:0,f=k(f)?f:0;var L=Math.max(1080,c),R=Math.max(30,f);g=k(g)?g:i,i=Math.max(g,i),u||(e=void 0);var I=n.length>1;return{codecSet:n.reduce((function(e,r){var s=t[r];if(r===e)return e;if(v=u?T.filter((function(t){return s.videoRanges[t]>0})):[],I){if(s.minBitrate>i)return Ie(r,"min bitrate of "+s.minBitrate+" > current estimate of "+i),e;if(!s.hasDefaultAudio)return Ie(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return Ie(r,'audio codec preference "'+o+'" not found'),e;if(a&&!h){if(!s.channels[a])return Ie(r,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(s.channels)+")"),e}else if((!o||h)&&d&&0===s.channels[2])return Ie(r,"no renditions with stereo sound found"),e;if(s.minHeight>L)return Ie(r,"min resolution of "+s.minHeight+" > maximum of "+L),e;if(s.minFramerate>R)return Ie(r,"min framerate of "+s.minFramerate+" > maximum of "+R),e;if(!v.some((function(t){return s.videoRanges[t]>0})))return Ie(r,"no variants with VIDEO-RANGE of "+Le(v)+" found"),e;if(l&&r.indexOf(l.substring(0,4))%5!=0)return Ie(r,'video codec preference "'+l+'" not found'),e;if(s.maxScore<p)return Ie(r,"max score of "+s.maxScore+" < selected max of "+p),e}return e&&(Ht(r)>=Ht(e)||s.fragmentError>t[e].fragmentError)?e:(m=s.minIndex,p=s.maxScore,r)}),void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:m}}function Ie(t,e){Y.log('[abr] start candidates with "'+t+'" ignored because '+e)}function be(t){return t.reduce((function(t,e){var i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);var r=e.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ke(t,e,i,r){return t.slice(i,r+1).reduce((function(t,i,r){if(!i.codecSet)return t;var s=i.audioGroups,n=t[i.codecSet];n||(t[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);var a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,s&&s.forEach((function(t){if(t){var i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach((function(t){n.channels[t]=(n.channels[t]||0)+i.channels[t]})))}})),t}),{})}function De(t){if(!t)return t;var e=t;return{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}}function _e(t,e,i){if("attrs"in t){var r=e.indexOf(t);if(-1!==r)return r}for(var s=0;s<e.length;s++)if(Pe(t,e[s],i))return s;return-1}function Pe(t,e,i){var r=t.groupId,s=t.name,n=t.lang,a=t.assocLang,o=t.default,l=t.forced;return(void 0===r||e.groupId===r)&&(void 0===s||e.name===s)&&(void 0===n||Ce(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||we(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function Ce(t,e){return void 0===e&&(e="--"),t.length===e.length?t===e:t.startsWith(e)||e.startsWith(t)}function we(t,e){void 0===e&&(e="");var i=t.split(","),r=e.split(",");return i.length===r.length&&!i.some((function(t){return-1===r.indexOf(t)}))}function Oe(t,e){var i=t.audioCodec,r=t.channels;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function xe(t,e,i,r,s){var n=e[r],a=e.reduce((function(t,e,i){var r=e.uri;return(t[r]||(t[r]=[])).push(i),t}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));var o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Me(e,r,(function(e){if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;var r=e.audioGroups,n=i.filter((function(t){return!r||-1!==r.indexOf(t.groupId)}));return _e(t,n,s)>-1}));return d>-1?d:Me(e,r,(function(e){var r=e.audioGroups,n=i.filter((function(t){return!r||-1!==r.indexOf(t.groupId)}));return _e(t,n,s)>-1}))}function Me(t,e,i){for(var r=e;r>-1;r--)if(i(t[r]))return r;for(var s=e+1;s<t.length;s++)if(i(t[s]))return s;return-1}function Fe(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}var Ne=function(t){function e(e){var i;return(i=t.call(this,"abr",e.logger)||this).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.supportedCache={},i.bwEstimator=void 0,i._abandonRulesCheck=function(t){var e,r=i,s=r.fragCurrent,n=r.partCurrent,a=r.hls,o=a.autoLevelEnabled,l=a.media;if(s&&l){var h=performance.now(),d=n?n.stats:s.stats,u=n?n.duration:s.duration,c=h-d.loading.start,f=a.minAutoLevel,g=s.level,m=i._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var p=m>-1&&m!==g,v=!!t||p;if(v||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(v||null!==y){var E=i.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(!(c<=Math.max(E,u/(2*T)*1e3))){var S=y?y.len/T:0,A=d.loading.first?d.loading.first-d.loading.start:-1,L=d.loaded&&A>-1,R=i.getBwEstimate(),I=a.levels,b=I[g],D=Math.max(d.loaded,Math.round(u*(s.bitrate||b.averageBitrate)/8)),_=L?c-A:c;_<1&&L&&(_=Math.min(c,8*d.loaded/R));var P=L?1e3*d.loaded/_:0,C=E/1e3,O=P?(D-d.loaded)/P:8*D/R+C;if(!(O<=S)){var x,M=P?8*P:R,F=!0===(null==(e=(null==t?void 0:t.details)||i.hls.latestLevelDetails)?void 0:e.live),N=i.hls.config.abrBandWidthUpFactor,U=Number.POSITIVE_INFINITY;for(x=g-1;x>f;x--){var B=I[x].maxBitrate,G=!I[x].details||F;if((U=i.getTimeToLoadFrag(C,M,u*B,G))<Math.min(S,u+C))break}if(!(U>=O||U>10*u)){L?i.bwEstimator.sample(c-Math.min(E,A),d.loaded):i.bwEstimator.sampleTTFB(c);var $=I[x].maxBitrate;i.getBwEstimate()*N>$&&i.resetEstimator($);var K=i.findBestLevel($,f,x,0,S,1,1);K>-1&&(x=K),i.warn("Fragment "+s.sn+(n?" part "+n.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+s.duration.toFixed(3)+"\n Time to underbuffer: "+S.toFixed(3)+" s\n Estimated load time for current fragment: "+O.toFixed(3)+" s\n Estimated load time for down switch fragment: "+U.toFixed(3)+" s\n TTFB estimate: "+(0|A)+" ms\n Current BW estimate: "+(k(R)?0|R:"Unknown")+" bps\n New BW estimate: "+(0|i.getBwEstimate())+" bps\n Switching to level "+x+" @ "+(0|$)+" bps"),a.nextLoadLevel=a.nextAutoLevel=x,i.clearTimer();var V=function(){if(i.clearTimer(),i.fragCurrent===s&&i.hls.loadLevel===x&&x>0){var t=i.getStarvationDelay();if(i.warn("Aborting inflight request "+(x>0?"and switching down":"")+"\n Fragment duration: "+s.duration.toFixed(3)+" s\n Time to underbuffer: "+t.toFixed(3)+" s"),s.abortRequests(),i.fragCurrent=i.partCurrent=null,x>f){var e=i.findBestLevel(i.hls.levels[f].bitrate,f,x,0,t,1,1);-1===e&&(e=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=e,i.resetEstimator(i.hls.levels[e].bitrate)}}};p||O>2*U?V():i.timer=self.setInterval(V,1e3*U),a.trigger(w.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:d})}}}}}}}},i.hls=e,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}l(e,t);var i=e.prototype;return i.resetEstimator=function(t){t&&(this.log("setting initial bwe to "+t),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},i.initEstimator=function(){var t=this.hls.config;return new F(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)},i.registerListeners=function(){var t=this.hls;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.FRAG_LOADING,this.onFragLoading,this),t.on(w.FRAG_LOADED,this.onFragLoaded,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this),t.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(w.LEVEL_LOADED,this.onLevelLoaded,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(w.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t&&(t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.FRAG_LOADING,this.onFragLoading,this),t.off(w.FRAG_LOADED,this.onFragLoaded,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this),t.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(w.LEVEL_LOADED,this.onLevelLoaded,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(w.ERROR,this.onError,this))},i.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null},i.onManifestLoading=function(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},i.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},i.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},i.onFragLoading=function(t,e){var i,r=e.frag;this.ignoreFragment(r)||(r.bitrateTest||(this.fragCurrent=r,this.partCurrent=null!=(i=e.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},i.onLevelSwitching=function(t,e){this.clearTimer()},i.onError=function(t,e){if(!e.fatal)switch(e.details){case C.BUFFER_ADD_CODEC_ERROR:case C.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case C.FRAG_LOAD_TIMEOUT:var i=e.frag,r=this.fragCurrent,s=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var n=performance.now(),a=s?s.stats:i.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},i.getTimeToLoadFrag=function(t,e,i,r){return t+i/e+(r?t+this.lastLevelLoadSec:0)},i.onLevelLoaded=function(t,e){var i=this.hls.config,r=e.stats.loading,s=r.end-r.first;k(s)&&(this.lastLevelLoadSec=s/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)},i.onFragLoaded=function(t,e){var i=e.frag,r=e.part,s=r?r.stats:i.stats;if(i.type===x.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=r?r.duration:i.duration,a=this.hls.levels[i.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(i.bitrateTest){var h={stats:s,frag:i,part:r,id:i.type};this.onFragBuffered(w.FRAG_BUFFERED,h),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},i.onFragBuffered=function(t,e){var i=e.frag,r=e.part,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(!s.aborted&&!this.ignoreFragment(i)){var n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},i.ignoreFragment=function(t){return t.type!==x.MAIN||"initSegment"===t.sn},i.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},i.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},i.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,s=i.config,n=i.minAutoLevel,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(l){var u=this.findBestLevel(o,n,r,l,0,h,d);if(u>=0)return this.rebufferNotice=-1,u}var c=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-f,this.info("bitrate test took "+Math.round(1e3*f)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*c)+" ms"),h=d=1)}var g=this.findBestLevel(o,n,r,l,c,h,d);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var m=i.levels[n],p=i.loadLevelObj;return p&&(null==m?void 0:m.bitrate)<p.bitrate?n:i.loadLevel},i.getStarvationDelay=function(){var t=this.hls,e=t.media;if(!e)return 1/0;var i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/i},i.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},i.findBestLevel=function(t,e,i,r,s,n,a){var o,l=this,h=r+s,d=this.lastLoadedFragLevel,u=-1===d?this.hls.firstLevel:d,c=this.fragCurrent,f=this.partCurrent,g=this.hls,m=g.levels,p=g.allAudioTracks,v=g.loadLevel,y=g.config;if(1===m.length)return 0;var E,T=m[u],S=!(null==(o=this.hls.latestLevelDetails)||!o.live),A=-1===v||-1===d,L="SDR",R=(null==T?void 0:T.frameRate)||0,I=y.audioPreference,b=y.videoPreference,D=this.audioTracksByGroup||(this.audioTracksByGroup=be(p)),_=-1;if(A){if(-1!==this.firstSelection)return this.firstSelection;var P=Re(this.codecTiers||(this.codecTiers=ke(m,D,e,i)),L,t,I,b),C=P.codecSet,w=P.videoRanges,O=P.minFramerate,x=P.minBitrate,M=P.minIndex,F=P.preferHDR;_=M,E=C,L=F?w[w.length-1]:w[0],R=O,t=Math.max(t,x),this.log("picked start tier "+Le(P))}else E=null==T?void 0:T.codecSet,L=null==T?void 0:T.videoRange;for(var N,U=f?f.duration:c?c.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,G=[],$=function(){var e,o=m[K],c=K>u;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&se(o,D,L,R,t,I)?(o.supportedPromise=ne(o,D,g,l.supportedCache),o.supportedPromise.then((function(t){if(l.hls){o.supportedResult=t;var e=l.hls.levels,i=e.indexOf(o);t.error?l.warn('MediaCapabilities decodingInfo error: "'+t.error+'" for level '+i+" "+Le(t)):t.supported?t.decodingInfoResults.some((function(t){return!1===t.smooth||!1===t.powerEfficient}))&&l.log("MediaCapabilities decodingInfo for level "+i+" not smooth or powerEfficient: "+Le(t)):(l.warn("Unsupported MediaCapabilities decodingInfo result for level "+i+" "+Le(t)),i>-1&&e.length>1&&(l.log("Removing unsupported level "+i),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}}))):o.supportedResult=ie}if((E&&o.codecSet!==E||L&&o.videoRange!==L||c&&R>o.frameRate||!c&&R>0&&R<o.frameRate||null!=(e=o.supportedResult)&&null!=(e=e.decodingInfoResults)&&e.some((function(t){return!1===t.smooth})))&&(!A||K!==_))return G.push(K),0;var p,T=o.details,b=(f?null==T?void 0:T.partTarget:null==T?void 0:T.averagetargetduration)||U;p=c?a*t:n*t;var P=U&&r>=2*U&&0===s?o.averageBitrate:o.maxBitrate,C=l.getTimeToLoadFrag(B,p,P*b,void 0===T);if(p>=P&&(K===d||0===o.loadError&&0===o.fragmentError)&&(C<=B||!k(C)||S&&!l.bitrateTestDelay||C<h)){var w=l.forcedAutoLevel;return K===v||-1!==w&&w===v||(G.length&&l.trace("Skipped level(s) "+G.join(",")+" of "+i+' max with CODECS and VIDEO-RANGE:"'+m[G[0]].codecs+'" '+m[G[0]].videoRange+'; not compatible with "'+E+'" '+L),l.info("switch candidate:"+u+"->"+K+" adjustedbw("+Math.round(p)+")-bitrate="+Math.round(p-P)+" ttfb:"+B.toFixed(1)+" avgDuration:"+b.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+C.toFixed(1)+" firstSelection:"+A+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+v)),A&&(l.firstSelection=K),{v:K}}},K=i;K>=e;K--)if(0!==(N=$())&&N)return N.v;return-1},i.deriveNextAutoLevel=function(t){var e=this.hls,i=e.maxAutoLevel,r=e.minAutoLevel;return Math.min(Math.max(t,r),i)},s(e,[{key:"firstAutoLevel",get:function(){var t=this.hls,e=t.maxAutoLevel,i=t.minAutoLevel,r=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(r,i,e,0,s,1,1);if(n>-1)return n;var a=this.hls.firstLevel,o=Math.min(Math.max(a,i),e);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;var r=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){var s=this.hls.levels;if(s.length>Math.max(t,r)&&s[t].loadError<=s[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},set:function(t){var e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}}])}(N),Ue={search:function(t,e){for(var i=0,r=t.length-1,s=null,n=null;i<=r;){var a=e(n=t[s=(i+r)/2|0]);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null}};function Be(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!k(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(var r=0;r<t.length;++r){var s=t[r];if(Ve(e,i,s))return s}return null}function Ge(t,e,i,r,s){void 0===i&&(i=0),void 0===r&&(r=0),void 0===s&&(s=.005);var n=null;if(t){n=e[1+t.sn-e[0].sn]||null;var a=t.endDTS-i;a>0&&a<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Ke(i,r,n)||$e(n,t,Math.min(s,r))))return n;var o=Ue.search(e,Ke.bind(null,i,r));return!o||o===t&&n?n:o}function $e(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){var r=e.tagList.reduce((function(t,e){return"INF"===e[0]&&(t+=parseFloat(e[1])),t}),i);return t.start<=r}return!1}function Ke(t,e,i){if(void 0===t&&(t=0),void 0===e&&(e=0),i.start<=t&&i.start+i.duration>t)return 0;var r=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=t?1:i.start-r>t&&i.start?-1:0}function Ve(t,e,i){var r=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>t}function He(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){var r,s=t.fragments,n=t.fragmentHint;return n&&(s=s.concat(n)),Ue.search(s,(function(t){return t.cc<e?1:t.cc>e?-1:(r=t,t.end<=i?1:t.start>i?-1:0)})),r||null}return null}function Ye(t){switch(t.details){case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_TIMEOUT:case C.LEVEL_LOAD_TIMEOUT:case C.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function We(t,e){var i=Ye(e);return t.default[(i?"timeout":"error")+"Retry"]}function je(t,e){var i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function qe(t){return c(c({},t),{errorRetry:null,timeoutRetry:null})}function Xe(t,e,i,r){if(!t)return!1;var s=null==r?void 0:r.code,n=e<t.maxNumRetry&&(Qe(s)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,r,n):n}function Qe(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}var ze={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ze={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2},Je=function(t){function e(e){var i;return(i=t.call(this,"error-controller",e.logger)||this).hls=void 0,i.playlistError=0,i.penalizedRenditions={},i.hls=e,i.registerListeners(),i}l(e,t);var i=e.prototype;return i.registerListeners=function(){var t=this.hls;t.on(w.ERROR,this.onError,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)},i.unregisterListeners=function(){var t=this.hls;t&&(t.off(w.ERROR,this.onError,this),t.off(w.ERROR,this.onErrorOut,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this))},i.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},i.startLoad=function(t){},i.stopLoad=function(){this.playlistError=0},i.getVariantLevelIndex=function(t){return(null==t?void 0:t.type)===x.MAIN?t.level:this.hls.loadLevel},i.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},i.onLevelUpdated=function(){this.playlistError=0},i.onError=function(t,e){var i;if(!e.fatal){var r=this.hls,s=e.context;switch(e.details){case C.FRAG_LOAD_ERROR:case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_ERROR:case C.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case C.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=ti());case C.FRAG_GAP:case C.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=ze.SendAlternateToPenaltyBox);case C.LEVEL_EMPTY_ERROR:case C.LEVEL_PARSING_ERROR:var n,a=e.parent===x.MAIN?e.level:r.loadLevel;return void(e.details===C.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,a)));case C.LEVEL_LOAD_ERROR:case C.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.level)));case C.AUDIO_TRACK_LOAD_ERROR:case C.AUDIO_TRACK_LOAD_TIMEOUT:case C.SUBTITLE_LOAD_ERROR:case C.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){var o=r.loadLevelObj;if(o&&(s.type===O.AUDIO_TRACK&&o.hasAudioGroup(s.groupId)||s.type===O.SUBTITLE_TRACK&&o.hasSubtitleGroup(s.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=ze.SendAlternateToPenaltyBox,void(e.errorAction.flags=Ze.MoveAllAlternatesMatchingHost)}return;case C.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var l=r.loadLevelObj,h=null==l?void 0:l.attrs["HDCP-LEVEL"];return void(h?e.errorAction={action:ze.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingHDCP,hdcpLevel:h}:this.keySystemError(e));case C.BUFFER_ADD_CODEC_ERROR:case C.REMUX_ALLOC_ERROR:case C.BUFFER_APPEND_ERROR:var d;return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,null!=(d=e.level)?d:r.loadLevel)));case C.INTERNAL_EXCEPTION:case C.BUFFER_APPENDING_ERROR:case C.BUFFER_FULL_ERROR:case C.LEVEL_SWITCH_ERROR:case C.BUFFER_STALLED_ERROR:case C.BUFFER_SEEK_OVER_HOLE:case C.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=ti())}e.type===P.KEY_SYSTEM_ERROR&&this.keySystemError(e)}},i.keySystemError=function(t){var e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)},i.getPlaylistRetryOrSwitchAction=function(t,e){var i=We(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(Xe(i,r,Ye(t),t.response))return{action:ze.RetryRequest,flags:Ze.None,retryConfig:i,retryCount:r};var s=this.getLevelSwitchAction(t,e);return i&&(s.retryConfig=i,s.retryCount=r),s},i.getFragRetryOrSwitchAction=function(t){var e=this.hls,i=this.getVariantLevelIndex(t.frag),r=e.levels[i],s=e.config,n=s.fragLoadPolicy,a=s.keyLoadPolicy,o=We(t.details.startsWith("key")?a:n,t),l=e.levels.reduce((function(t,e){return t+e.fragmentError}),0);if(r&&(t.details!==C.FRAG_GAP&&r.fragmentError++,Xe(o,l,Ye(t),t.response)))return{action:ze.RetryRequest,flags:Ze.None,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(t,i);return o&&(h.retryConfig=o,h.retryCount=l),h},i.getLevelSwitchAction=function(t,e){var i=this.hls;null==e&&(e=i.loadLevel);var r=this.hls.levels[e];if(r){var s,n,a=t.details;r.loadError++,a===C.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,h=i.loadLevel,d=i.minAutoLevel,u=i.maxAutoLevel;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);for(var c,f=null==(s=t.frag)?void 0:s.type,g=(f===x.AUDIO&&a===C.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(a===C.BUFFER_ADD_CODEC_ERROR||a===C.BUFFER_APPEND_ERROR))&&l.some((function(t){var e=t.audioCodec;return r.audioCodec!==e})),m="video"===t.sourceBufferName&&(a===C.BUFFER_ADD_CODEC_ERROR||a===C.BUFFER_APPEND_ERROR)&&l.some((function(t){var e=t.codecSet,i=t.audioCodec;return r.codecSet!==e&&r.audioCodec===i})),p=null!=(n=t.context)?n:{},v=p.type,y=p.groupId,E=function(){var e=(T+h)%l.length;if(e!==h&&e>=d&&e<=u&&0===l[e].loadError){var i,s,n=l[e];if(a===C.FRAG_GAP&&f===x.MAIN&&t.frag){var c=l[e].details;if(c){var p=Ge(t.frag,c.fragments,t.frag.start);if(null!=p&&p.gap)return 0}}else{if(v===O.AUDIO_TRACK&&n.hasAudioGroup(y)||v===O.SUBTITLE_TRACK&&n.hasSubtitleGroup(y))return 0;if(f===x.AUDIO&&null!=(i=r.audioGroups)&&i.some((function(t){return n.hasAudioGroup(t)}))||f===x.SUBTITLE&&null!=(s=r.subtitleGroups)&&s.some((function(t){return n.hasSubtitleGroup(t)}))||g&&r.audioCodec===n.audioCodec||m&&r.codecSet===n.codecSet||!g&&r.codecSet!==n.codecSet)return 0}return o=e,1}},T=l.length;T--&&(0===(c=E())||1!==c););if(o>-1&&i.loadLevel!==o)return t.levelRetry=!0,this.playlistError=0,{action:ze.SendAlternateToPenaltyBox,flags:Ze.None,nextAutoLevel:o}}return{action:ze.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingHost}},i.onErrorOut=function(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case ze.DoNothing:break;case ze.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===C.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}e.fatal&&this.hls.stopLoad()},i.sendAlternateToPenaltyBox=function(t){var e=this.hls,i=t.errorAction;if(i){var r=i.flags,s=i.hdcpLevel,n=i.nextAutoLevel;switch(r){case Ze.None:this.switchLevel(t,n);break;case Ze.MoveAllAlternatesMatchingHDCP:s&&(e.maxHdcpLevel=ue[ue.indexOf(s)-1],i.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+e.maxHdcpLevel+'" or lower')}i.resolved||this.switchLevel(t,n)}},i.switchLevel=function(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===C.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName))for(var i=ee(t.mimeType),r=this.hls.levels,s=r.length;s--;)r[s][t.sourceBufferName+"Codec"]===i&&this.hls.removeLevel(s)},e}(N);function ti(t){var e={action:ze.DoNothing,flags:Ze.None};return t&&(e.resolved=!0),e}var ei={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},ii=function(){function t(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()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t&&(t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.BUFFER_APPENDED,this.onBufferAppended,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this),t.on(w.FRAG_LOADED,this.onFragLoaded,this))},e._unregisterListeners=function(){var t=this.hls;t&&(t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.BUFFER_APPENDED,this.onBufferAppended,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this),t.off(w.FRAG_LOADED,this.onFragLoaded,this))},e.destroy=function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){var i=this.activePartLists[e];if(i)for(var r=i.length;r--;){var s=i[r];if(!s)break;if(s.start<=t&&t<=s.end&&s.loaded)return s}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){return this.getFragAtPos(t,e,!0)},e.getFragAtPos=function(t,e,i){for(var r=this.fragments,s=Object.keys(r),n=s.length;n--;){var a=r[s[n]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){var o=a.body;if(o.start<=t&&t<=o.end)return o}}return null},e.detectEvictedFragments=function(t,e,i,r,s){var n=this;this.timeRanges&&(this.timeRanges[t]=e);var a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(r){var o=n.fragments[r];if(o&&!(a>=o.body.sn))if(o.buffered||o.loaded&&!s){var l=o.range[t];l&&(0!==l.time.length?l.time.some((function(t){var i=!n.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&n.removeFragment(o.body),i})):n.removeFragment(o.body))}else o.body.type===i&&n.removeFragment(o.body)}))},e.detectPartialFragments=function(t){var e=this,i=this.timeRanges;if(i&&"initSegment"!==t.frag.sn){var r=t.frag,s=si(r),n=this.fragments[s];if(!(!n||n.buffered&&r.gap)){var a=!r.relurl;Object.keys(i).forEach((function(s){var o=r.elementaryStreams[s];if(o){var l=i[s],h=a||!0===o.partial;n.range[s]=e.getBufferedTimes(r,t.part,h,l)}})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=r.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ri(n)||this.removeParts(r.sn-1,r.type)):this.removeFragment(n.body)}}},e.removeParts=function(t,e){var i=this.activePartLists[e];i&&(this.activePartLists[e]=ni(i,(function(e){return e.fragment.sn>=t})))},e.fragBuffered=function(t,e){var i=si(t),r=this.fragments[i];!r&&e&&(r=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,i,r){for(var s={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n,h=0;h<r.length;h++){var d=r.start(h)-this.bufferPadding,u=r.end(h)+this.bufferPadding;if(l>=d&&o<=u){s.time.push({startPTS:Math.max(n,r.start(h)),endPTS:Math.min(a,r.end(h))});break}if(n<u&&a>d){var c=Math.max(n,r.start(h)),f=Math.min(a,r.end(h));f>c&&(s.partial=!0,s.time.push({startPTS:c,endPTS:f}))}else if(a<=d)break}return s},e.getPartialFragment=function(t){var e,i,r,s=null,n=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&ri(h)&&(i=h.body.start-a,r=h.body.end+a,t>=i&&t<=r&&(e=Math.min(t-i,r-t),n<=e&&(s=h.body,n=e)))})),s},e.isEndListAppended=function(t){var e=this.endListFragments[t];return void 0!==e&&(e.buffered||ri(e))},e.getState=function(t){var e=si(t),i=this.fragments[e];return i?i.buffered?ri(i)?ei.PARTIAL:ei.OK:ei.APPENDING:ei.NOT_LOADED},e.isTimeBuffered=function(t,e,i){for(var r,s,n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,t>=r&&e<=s)return!0;if(e<=r)return!1}return!1},e.onManifestLoading=function(){this.removeAllFragments()},e.onFragLoaded=function(t,e){if("initSegment"!==e.frag.sn&&!e.frag.bitrateTest){var i=e.frag,r=e.part?null:e,s=si(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var i=e.frag,r=e.part,s=e.timeRanges,n=e.type;if("initSegment"!==i.sn){var a=i.type;if(r){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=s;var l=s[n];this.detectEvictedFragments(n,l,a,r)}},e.onFragBuffered=function(t,e){this.detectPartialFragments(e)},e.hasFragment=function(t){var e=si(t);return!!this.fragments[e]},e.hasFragments=function(t){var e=this.fragments,i=Object.keys(e);if(!t)return i.length>0;for(var r=i.length;r--;){var s=e[i[r]];if((null==s?void 0:s.body.type)===t)return!0}return!1},e.hasParts=function(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)},e.removeFragmentsInRange=function(t,e,i,r,s){var n=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=n.fragments[a];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<e&&l.end>t&&(o.buffered||s)&&n.removeFragment(l)}}))},e.removeFragment=function(t){var e=si(t);t.clearElementaryStreamInfo();var i=this.activePartLists[t.type];if(i){var r=t.sn;this.activePartLists[t.type]=ni(i,(function(t){return t.fragment.sn!==r}))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]},e.removeAllFragments=function(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach((function(t){return t.clearElementaryStreamInfo()}))},t}();function ri(t){var e,i,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(r=t.range.audiovideo)&&r.partial)}function si(t){return t.type+"_"+t.level+"_"+t.sn}function ni(t,e){return t.filter((function(t){var i=e(t);return i||t.clearElementaryStreamInfo(),i}))}var ai={cbc:0,ctr:1},oi=function(){function t(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}return t.prototype.decrypt=function(t,e){switch(this.aesMode){case ai.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case ai.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)}},t}();function li(t){var e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}var hi=function(){function t(){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()}var e=t.prototype;return e.uint8ArrayToUint32Array_=function(t){for(var e=new DataView(t),i=new Uint32Array(4),r=0;r<4;r++)i[r]=e.getUint32(4*r);return i},e.initTable=function(){var t=this.sBox,e=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256),f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){var p=g^g<<1^g<<2^g<<3^g<<4;p=p>>>8^255&p^99,t[f]=p,e[p]=f;var v=c[f],y=c[v],E=c[y],T=257*c[p]^16843008*p;r[f]=T<<24|T>>>8,s[f]=T<<16|T>>>16,n[f]=T<<8|T>>>24,a[f]=T,T=16843009*E^65537*y^257*v^16843008*f,l[p]=T<<24|T>>>8,h[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,u[p]=T,f?(f=v^c[c[c[E^v]]],g^=c[c[g]]):f=g=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),i=!0,r=0;r<e.length&&i;)i=e[r]===this.key[r],r++;if(!i){this.key=e;var s=this.keySize=e.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);var n,a,o,l,h=this.ksRows=4*(s+6+1),d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,m=g[0],p=g[1],v=g[2],y=g[3];for(n=0;n<h;n++)n<s?o=d[n]=e[n]:(l=o,n%s==0?(l=c[(l=l<<8|l>>>24)>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[n/s|0]<<24):s>6&&n%s==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),d[n]=o=(d[n-s]^l)>>>0);for(a=0;a<h;a++)n=h-a,l=3&a?d[n]:d[n-4],u[a]=a<4||n<=4?l:m[c[l>>>24]]^p[c[l>>>16&255]]^v[c[l>>>8&255]]^y[c[255&l]],u[a]=u[a]>>>0}},e.networkToHostOrderSwap=function(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24},e.decrypt=function(t,e,i){for(var r,s,n,a,o,l,h,d,u,c,f,g,m,p,v=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,S=T[0],A=T[1],L=T[2],R=T[3],I=this.uint8ArrayToUint32Array_(i),b=I[0],k=I[1],D=I[2],_=I[3],P=new Int32Array(t),C=new Int32Array(P.length),w=this.networkToHostOrderSwap;e<P.length;){for(u=w(P[e]),c=w(P[e+1]),f=w(P[e+2]),g=w(P[e+3]),o=u^y[0],l=g^y[1],h=f^y[2],d=c^y[3],m=4,p=1;p<v;p++)r=S[o>>>24]^A[l>>16&255]^L[h>>8&255]^R[255&d]^y[m],s=S[l>>>24]^A[h>>16&255]^L[d>>8&255]^R[255&o]^y[m+1],n=S[h>>>24]^A[d>>16&255]^L[o>>8&255]^R[255&l]^y[m+2],a=S[d>>>24]^A[o>>16&255]^L[l>>8&255]^R[255&h]^y[m+3],o=r,l=s,h=n,d=a,m+=4;r=E[o>>>24]<<24^E[l>>16&255]<<16^E[h>>8&255]<<8^E[255&d]^y[m],s=E[l>>>24]<<24^E[h>>16&255]<<16^E[d>>8&255]<<8^E[255&o]^y[m+1],n=E[h>>>24]<<24^E[d>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[m+2],a=E[d>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&h]^y[m+3],C[e]=w(r^b),C[e+1]=w(a^k),C[e+2]=w(n^D),C[e+3]=w(s^_),b=u,k=c,D=f,_=g,e+=4}return C.buffer},t}(),di=function(){function t(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}return t.prototype.expandKey=function(){var t=ui(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])},t}();function ui(t){switch(t){case ai.cbc:return"AES-CBC";case ai.ctr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+t)}}var ci=16,fi=function(){function t(t,e){var i=(void 0===e?{}:e).removePKCS7Padding,r=void 0===i||i;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=r,r)try{var s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}var e=t.prototype;return e.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},e.isSync=function(){return this.useSoftware},e.flush=function(){var t=this.currentResult,e=this.remainderData;if(!t||e)return this.reset(),null;var i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?li(i):i},e.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},e.decrypt=function(t,e,i,r){var s=this;return this.useSoftware?new Promise((function(n,a){var o=ArrayBuffer.isView(t)?t:new Uint8Array(t);s.softwareDecrypt(o,e,i,r);var l=s.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,i,r)},e.softwareDecrypt=function(t,e,i,r){var s=this.currentIV,n=this.currentResult,a=this.remainderData;if(r!==ai.cbc||16!==e.byteLength)return Y.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Dt(a,t),this.remainderData=null);var o=this.getValidChunk(t);if(!o.length)return null;s&&(i=s);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new hi),l.expandKey(e);var h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null},e.webCryptoDecrypt=function(t,e,i,r){var s=this;if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,r));this.key=e,this.fastAesKey=new di(this.subtle,e,r)}return this.fastAesKey.expandKey().then((function(e){return s.subtle?(s.logOnce("WebCrypto AES decrypt"),new oi(s.subtle,new Uint8Array(i),r).decrypt(t.buffer,e)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(n){return Y.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+n.name+": "+n.message),s.onWebCryptoError(t,e,i,r)}))},e.onWebCryptoError=function(t,e,i,r){var s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,r);var n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")},e.getValidChunk=function(t){var e=t,i=t.length-t.length%ci;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e},e.logOnce=function(t){this.logEnabled&&(Y.log("[decrypter]: "+t),this.logEnabled=!1)},t}(),gi=Math.pow(2,17),mi=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var i=this,r=t.url;if(!r)return Promise.reject(new Ei({type:P.NETWORK_ERROR,details:C.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),t.gap){if(t.tagList.some((function(t){return"GAP"===t[0]})))return void l(vi(t));t.gap=!1}var h=i.loader=n?new n(s):new a(s),d=pi(t);t.loader=h;var u=qe(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:gi};t.stats=h.stats;var g={onSuccess:function(e,r,s,n){i.resetLoader(t,h);var a=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:t,part:null,payload:a,networkDetails:n})},onError:function(e,s,n,a){i.resetLoader(t,h),l(new Ei({type:P.NETWORK_ERROR,details:C.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:c({url:r,data:void 0},e),error:new Error("HTTP Error "+e.code+" "+e.text),networkDetails:n,stats:a}))},onAbort:function(e,r,s){i.resetLoader(t,h),l(new Ei({type:P.NETWORK_ERROR,details:C.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:function(e,r,s){i.resetLoader(t,h),l(new Ei({type:P.NETWORK_ERROR,details:C.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:s,stats:e}))}};e&&(g.onProgress=function(i,r,s,n){return e({frag:t,part:null,payload:s,networkDetails:n})}),h.load(d,f,g)}))},e.loadPart=function(t,e,i){var r=this;this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(r.loader&&r.loader.destroy(),t.gap||e.gap)l(vi(t,e));else{var h=r.loader=n?new n(s):new a(s),d=pi(t,e);t.loader=h;var u=qe(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gi};e.stats=h.stats,h.load(d,f,{onSuccess:function(s,n,a,l){r.resetLoader(t,h),r.updateStatsFromPart(t,e);var d={frag:t,part:e,payload:s.data,networkDetails:l};i(d),o(d)},onError:function(i,s,n,a){r.resetLoader(t,h),l(new Ei({type:P.NETWORK_ERROR,details:C.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:c({url:d.url,data:void 0},i),error:new Error("HTTP Error "+i.code+" "+i.text),networkDetails:n,stats:a}))},onAbort:function(i,s,n){t.stats.aborted=e.stats.aborted,r.resetLoader(t,h),l(new Ei({type:P.NETWORK_ERROR,details:C.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:n,stats:i}))},onTimeout:function(i,s,n){r.resetLoader(t,h),l(new Ei({type:P.NETWORK_ERROR,details:C.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:i}))}})}}))},e.updateStatsFromPart=function(t,e){var i=t.stats,r=e.stats,s=r.total;if(i.loaded+=r.loaded,s){var n=Math.round(t.duration/e.duration),a=Math.min(Math.round(i.loaded/s),n),o=(n-a)*Math.round(i.loaded/a);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,h=r.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function pi(t,e){void 0===e&&(e=null);var i=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(k(s)&&k(n)){var a,o=s,l=n;if("initSegment"===t.sn&&yi(null==(a=t.decryptdata)?void 0:a.method)){var h=n-s;h%16&&(l=n+(16-h%16)),0!==s&&(r.resetIV=!0,o=s-16)}r.rangeStart=o,r.rangeEnd=l}return r}function vi(t,e){var i=new Error("GAP "+(t.gap?"tag":"attribute")+" found"),r={type:P.MEDIA_ERROR,details:C.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new Ei(r)}function yi(t){return"AES-128"===t||"AES-256"===t}var Ei=function(t){function e(e){var i;return(i=t.call(this,e.error.message)||this).data=void 0,i.data=e,i}return l(e,t),e}(p(Error)),Ti=function(t){function e(e,i){var r;return(r=t.call(this,e,i)||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}l(e,t);var i=e.prototype;return i.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},i.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},i.onHandlerDestroyed=function(){},i.hasInterval=function(){return!!this._tickInterval},i.hasNextTick=function(){return!!this._tickTimer},i.setInterval=function(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)},i.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},i.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},i.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},i.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},i.doTick=function(){},e}(N),Si=function(t,e,i,r,s,n){void 0===r&&(r=0),void 0===s&&(s=-1),void 0===n&&(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=Ai(),this.buffering={audio:Ai(),video:Ai(),audiovideo:Ai()},this.level=t,this.sn=e,this.id=i,this.size=r,this.part=s,this.partial=n};function Ai(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Li={length:0,start:function(){return 0},end:function(){return 0}},Ri=function(){function t(){}return t.isBuffered=function(e,i){if(e)for(var r=t.getBuffered(e),s=r.length;s--;)if(i>=r.start(s)&&i<=r.end(s))return!0;return!1},t.bufferedRanges=function(e){if(e){var i=t.getBuffered(e);return t.timeRangesToArray(i)}return[]},t.timeRangesToArray=function(t){for(var e=[],i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e},t.bufferInfo=function(e,i,r){if(e){var s=t.bufferedRanges(e);if(s.length)return t.bufferedInfo(s,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}},t.bufferedInfo=function(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((function(t,e){return t.start-e.start||e.end-t.end}));var r=-1,s=[];if(i)for(var n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(r=n);var a=s.length;if(a){var o=s[a-1].end;t[n].start-o<i?t[n].end>o&&(s[a-1].end=t[n].end):s.push(t[n])}else s.push(t[n])}else s=t;for(var l,h=0,d=e,u=e,c=0;c<s.length;c++){var f=s[c].start,g=s[c].end;if(-1===r&&e>=f&&e<=g&&(r=c),e+i>=f&&e<g)d=f,h=(u=g)-e;else if(e+i<f){l=f;break}}return{len:h,start:d||0,end:u||0,nextStart:l,buffered:t,bufferedIndex:r}},t.getBuffered=function(t){try{return t.buffered||Li}catch(t){return Y.log("failed to get media.buffered",t),Li}},t}(),Ii=/\{\$([a-zA-Z0-9-_]+)\}/g;function bi(t){return Ii.test(t)}function ki(t,e){if(null!==t.variableList||t.hasVariableRefs){var i=t.variableList;return e.replace(Ii,(function(e){var r=e.substring(2,e.length-1),s=null==i?void 0:i[r];return void 0===s?(t.playlistParsingError||(t.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+r+'"')),e):s}))}return e}function Di(t,e,i){var r,s,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{var a=new self.URL(i).searchParams;if(!a.has(r))throw new Error('"'+r+'" does not match any query parameter in URI: "'+i+'"');s=a.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+e.message))}}else r=e.NAME,s=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+r+'"')):n[r]=s||""}function _i(t,e,i){var r=e.IMPORT;if(i&&r in i){var s=t.variableList;s||(t.variableList=s={}),s[r]=i[r]}else t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+r+'"'))}var Pi=/^(\d+)x(\d+)$/,Ci=/(.+?)=(".*?"|.*?)(?:,|$)/g,wi=function(){function t(e,i){"string"==typeof e&&(e=t.parseAttrList(e,i)),a(this,e)}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var i=new Uint8Array(e.length/2),r=0;r<e.length/2;r++)i[r]=parseInt(e.slice(2*r,2*r+2),16);return i}return null},e.hexadecimalIntegerAsNumber=function(t){var e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var i=this[t];return i?parseFloat(i):e},e.enumeratedString=function(t){return this[t]},e.enumeratedStringList=function(t,e){var i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((function(t,e){return t[e.toLowerCase()]=!0,t}),e)},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=Pi.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t,e){var i,r={},s='"';for(Ci.lastIndex=0;null!==(i=Ci.exec(t));){var n=i[1].trim(),a=i[2],o=0===a.indexOf(s)&&a.lastIndexOf(s)===a.length-1,l=!1;if(o)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(e&&(o||l))a=ki(e,a);else if(!l&&!o)switch(n){case"CLOSED-CAPTIONS":if("NONE"===a)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 "+n+" is missing quotes")}r[n]=a}return r},s(t,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(t){return"X-"===t.substring(0,2)}))}}])}(),Oi="com.apple.hls.interstitial";function xi(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function Mi(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}var Fi=function(){function t(t,e,i){var r;if(void 0===i&&(i=0),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!=(r=null==e?void 0:e.tagOrder)?r:i,e){var s=e.attr;for(var n in s)if(Object.prototype.hasOwnProperty.call(t,n)&&t[n]!==s[n]){Y.warn('DATERANGE tag attribute: "'+n+'" does not match for tags with ID: "'+t.ID+'"'),this._badValueForSameId=n;break}t=a(new wi({}),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){var o=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);k(o.getTime())&&(this._endDate=o)}}return s(t,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var 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}},{key:"startTime",get:function(){var t=this.tagAnchor;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}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var t=this._endDate||this._dateAtEnd;if(t)return t;var e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var t=this.attr.decimalFloatingPoint("DURATION");if(k(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return this.class===Oi}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&k(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)}}])}(),Ni=10,Ui=function(){function t(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}return t.prototype.reloaded=function(t){if(!t)return this.advanced=!0,void(this.updated=!0);var e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1},s(t,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&k(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||Ni}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var t=this.partList;if(t){var e=this.lastPartIndex;if(-1!==e){for(var i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}},{key:"lastPartSn",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}])}();function Bi(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Gi(t){switch(t){case"AES-128":case"AES-256":return ai.cbc;case"AES-256-CTR":return ai.ctr;default:throw new Error("invalid full segment method "+t)}}function $i(t){return Uint8Array.from(atob(t),(function(t){return t.charCodeAt(0)}))}function Ki(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(function(t){return t.charCodeAt(0)}))}function Vi(t){var e=Ki(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}function Hi(t){var e=function(t,e,i){var r=t[e];t[e]=t[i],t[i]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function Yi(t){var e=t.split(":"),i=null;if("data"===e[0]&&2===e.length){var r=e[1].split(";"),s=r[r.length-1].split(",");if(2===s.length){var n="base64"===s[0],a=s[1];n?(r.splice(-1,1),i=$i(a)):i=Vi(a)}}return i}var Wi="undefined"!=typeof self?self:void 0,ji={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},qi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Xi(t){switch(t){case qi.FAIRPLAY:return ji.FAIRPLAY;case qi.PLAYREADY:return ji.PLAYREADY;case qi.WIDEVINE:return ji.WIDEVINE;case qi.CLEARKEY:return ji.CLEARKEY}}function Qi(t){switch(t){case ji.FAIRPLAY:return qi.FAIRPLAY;case ji.PLAYREADY:return qi.PLAYREADY;case ji.WIDEVINE:return qi.WIDEVINE;case ji.CLEARKEY:return qi.CLEARKEY}}function zi(t){var e=t.drmSystems,i=t.widevineLicenseUrl,r=e?[ji.FAIRPLAY,ji.WIDEVINE,ji.PLAYREADY,ji.CLEARKEY].filter((function(t){return!!e[t]})):[];return!r[ji.WIDEVINE]&&i&&r.push(ji.WIDEVINE),r}var Zi,Ji=null!=Wi&&null!=(Zi=Wi.navigator)&&Zi.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function tr(t,e,i,r){var s;switch(t){case ji.FAIRPLAY:s=["cenc","sinf"];break;case ji.WIDEVINE:case ji.PLAYREADY:s=["cenc"];break;case ji.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+t)}return er(s,e,i,r)}function er(t,e,i,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map((function(t){return{contentType:"audio/mp4; codecs="+t,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}})),videoCapabilities:i.map((function(t){return{contentType:"video/mp4; codecs="+t,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}}))}]}function ir(t){var e;return"persistent-license"===t.sessionType||!(null==(e=t.sessionTypes)||!e.some((function(t){return"persistent-license"===t})))}function rr(t){var e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),r=i.substring(i.indexOf("<"),i.length),s=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){var n=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(n){var a=$i(n).subarray(0,16);return Hi(a),a}}return null}var sr={},nr=function(){function t(t,e,i,r,s,n){void 0===r&&(r=[1]),void 0===s&&(s=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Bi(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(z(n)))}t.clearKeyUriToKeyIdMap=function(){sr={}};var e=t.prototype;return e.matches=function(t){var e,i;return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&t.keyFormatVersions.join(",")===this.keyFormatVersions.join(",")&&(null==(e=t.iv)?void 0:e.join(","))===(null==(i=this.iv)?void 0:i.join(","))},e.isSupported=function(){if(this.method){if(Bi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case qi.FAIRPLAY:case qi.WIDEVINE:case qi.PLAYREADY:case qi.CLEARKEY:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},e.getDecryptData=function(e){if(!this.encrypted||!this.uri)return null;if(Bi(this.method)&&this.uri&&!this.iv){"number"!=typeof e&&(Y.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),e=0);var i=ar(e);return new t(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.pssh&&this.keyId)return this;var r=Yi(this.uri);if(r)switch(this.keyFormat){case qi.WIDEVINE:if(this.pssh=r,!this.keyId&&r.length>=22){var s=r.length-22;this.keyId=r.subarray(s,s+16)}break;case qi.PLAYREADY:var n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ft(n,null,r),this.keyId=rr(r);break;default:var a=r.subarray(0,16);if(16!==a.length){var o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a}if(!this.keyId||16!==this.keyId.byteLength){var l=sr[this.uri];if(!l){var h=Object.keys(sr).length%Number.MAX_SAFE_INTEGER;l=new Uint8Array(16),new DataView(l.buffer,12,4).setUint32(0,h),sr[this.uri]=l}this.keyId=l}return this},t}();function ar(t){for(var e=new Uint8Array(16),i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}var or=/#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,lr=/#EXT-X-MEDIA:(.*)/g,hr=/^#EXT(?:INF|-X-TARGETDURATION):/m,dr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ur=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("|")),cr=function(){function t(){}return t.findGroup=function(t,e){for(var i=0;i<t.length;i++){var r=t[i];if(r.id===e)return r}},t.resolve=function(t,e){return b.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.isMediaPlaylist=function(t){return hr.test(t)},t.parseMasterPlaylist=function(e,i){var r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:bi(e)},n=[];for(or.lastIndex=0;null!=(r=or.exec(e));)if(r[1]){var a,o=new wi(r[1],s),l=ki(s,r[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:t.resolve(l,i)},d=o.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),vr(o.CODECS,h);var u=o["SUPPLEMENTAL-CODECS"];u&&(h.supplemental={},vr(u,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||n.push(h),s.levels.push(h)}else if(r[3]){var c=r[3],f=r[4];switch(c){case"SESSION-DATA":var g=new wi(f,s),m=g["DATA-ID"];m&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[m]=g);break;case"SESSION-KEY":var p=mr(f,i,s);p.encrypted&&p.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(p)):Y.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":Di(s,new wi(f,s),i);break;case"CONTENT-STEERING":var v=new wi(f,s);s.contentSteering={uri:t.resolve(v["SERVER-URI"],i),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":s.startTimeOffset=pr(f)}}var y=n.length>0&&n.length<s.levels.length;return s.levels=y?n:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s},t.parseMasterPlaylistMedia=function(e,i,r){var s,n={},a=r.levels,o={AUDIO:a.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),SUBTITLES:a.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(lr.lastIndex=0;null!==(s=lr.exec(e));){var h=new wi(s[1],r),d=h.TYPE;if(d){var u=o[d],c=n[d]||[];n[d]=c;var f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],m=h.CHANNELS,p=h.CHARACTERISTICS,v=h["INSTREAM-ID"],y={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:d,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?t.resolve(h.URI,i):""};if(g&&(y.assocLang=g),m&&(y.channels=m),p&&(y.characteristics=p),v&&(y.instreamId=v),null!=u&&u.length){var E=t.findGroup(u,y.groupId)||u[0];yr(y,E,"audioCodec"),yr(y,E,"textCodec")}c.push(y)}}return n},t.parseLevelPlaylist=function(t,e,i,r,s,n){var o,l,h,d,u,c={url:e},f=new Ui(e),g=f.fragments,m=[],p=null,v=0,y=0,E=0,T=0,S=0,A=null,L=new it(r,c),R=-1,I=!1,b=null;if(dr.lastIndex=0,f.m3u8=t,f.hasVariableRefs=bi(t),"#EXTM3U"!==(null==(o=dr.exec(t))?void 0:o[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(l=dr.exec(t));){I&&(I=!1,(L=new it(r,c)).playlistOffset=E,L.setStart(E),L.sn=v,L.cc=T,S&&(L.bitrate=S),L.level=i,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),b&&(L.setByteRange(b),b=null)));var D=l[1];if(D){L.duration=parseFloat(D);var _=(" "+l[2]).slice(1);L.title=_||null,L.tagList.push(_?["INF",D,_]:["INF",D])}else if(l[3]){if(k(L.duration)){L.playlistOffset=E,L.setStart(E),d&&Ar(L,d,f),L.sn=v,L.level=i,L.cc=T,g.push(L);var P=(" "+l[3]).slice(1);L.relurl=ki(f,P),Tr(L,A,m),A=L,E+=L.duration,v++,y=0,I=!0}}else{if(!(l=l[0].match(ur))){Y.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);var C=(" "+l[h]).slice(1),w=(" "+l[h+1]).slice(1),O=l[h+2]?(" "+l[h+2]).slice(1):null;switch(C){case"BYTERANGE":A?L.setByteRange(w,A):L.setByteRange(w);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=w,L.tagList.push(["PROGRAM-DATE-TIME",w]),-1===R&&(R=g.length);break;case"PLAYLIST-TYPE":f.type&&Lr(f,C,l),f.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?Lr(f,C,l):g.length>0&&Rr(f,C,l),v=f.startSN=parseInt(w);break;case"SKIP":f.skippedSegments&&Lr(f,C,l);var x=new wi(w,f),M=x.decimalInteger("SKIPPED-SEGMENTS");if(k(M)){f.skippedSegments+=M;for(var F=M;F--;)g.push(null);v+=M}var N=x.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(N.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&Lr(f,C,l),f.targetduration=Math.max(parseInt(w),1);break;case"VERSION":null!==f.version&&Lr(f,C,l),f.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||Lr(f,C,l),f.live=!1;break;case"#":(w||O)&&L.tagList.push(O?[w,O]:[w]);break;case"DISCONTINUITY":T++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([C]);break;case"BITRATE":L.tagList.push([C,w]),S=1e3*parseInt(w),k(S)?L.bitrate=S:S=0;break;case"DATERANGE":var U=new wi(w,f),B=new Fi(U,f.dateRanges[U.ID],f.dateRangeTagCount);f.dateRangeTagCount++,B.isValid||f.skippedSegments?f.dateRanges[B.id]=B:Y.warn('Ignoring invalid DATERANGE tag: "'+w+'"'),L.tagList.push(["EXT-X-DATERANGE",w]);break;case"DEFINE":var G=new wi(w,f);"IMPORT"in G?_i(f,G,n):Di(f,G,e);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?Lr(f,C,l):g.length>0&&Rr(f,C,l),f.startCC=T=parseInt(w);break;case"KEY":var $=mr(w,e,f);if($.isSupported()){if("NONE"===$.method){d=void 0;break}d||(d={});var K=d[$.keyFormat];null!=K&&K.matches($)||(K&&(d=a({},d)),d[$.keyFormat]=$)}else Y.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+w+'"');break;case"START":f.startTimeOffset=pr(w);break;case"MAP":var V=new wi(w,f);if(L.duration){var H=new it(r,c);Sr(H,V,i,d),p=H,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{var W=L.byteRangeEndOffset;if(W){var j=L.byteRangeStartOffset;b=W-j+"@"+j}else b=null;Sr(L,V,i,d),p=L,I=!0}p.cc=T;break;case"SERVER-CONTROL":u&&Lr(f,C,l),u=new wi(w),f.canBlockReload=u.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=u.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&u.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=u.optionalFloat("PART-HOLD-BACK",0),f.holdBack=u.optionalFloat("HOLD-BACK",0);break;case"PART-INF":f.partTarget&&Lr(f,C,l);var q=new wi(w);f.partTarget=q.decimalFloatingPoint("PART-TARGET");break;case"PART":var X=f.partList;X||(X=f.partList=[]);var Q=y>0?X[X.length-1]:void 0,z=y++,Z=new wi(w,f),J=new rt(Z,L,c,z,Q);X.push(J),L.duration+=J.duration;break;case"PRELOAD-HINT":var tt=new wi(w,f);f.preloadHint=tt;break;case"RENDITION-REPORT":var et=new wi(w,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(et);break;default:Y.warn("line parsed but not handled: "+l)}}}A&&!A.relurl?(g.pop(),E-=A.duration,f.partList&&(f.fragmentHint=A)):f.partList&&(Tr(L,A,m),L.cc=T,f.fragmentHint=L,d&&Ar(L,d,f)),f.targetduration||(f.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));var st=g.length,nt=g[0],at=g[st-1];if((E+=f.skippedSegments*f.targetduration)>0&&st&&at){f.averagetargetduration=E/st;var ot=at.sn;f.endSN="initSegment"!==ot?ot:0,f.live||(at.endList=!0),R>0&&(Er(g,R),nt&&m.unshift(nt))}return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,m.length&&f.dateRangeTagCount&&nt&&fr(m,f),f.endCC=T,f},t}();function fr(t,e){var i=t.length;if(i)for(var r=t[i-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges),a=n.length;a--;){var o=e.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=r.ref;for(var h=i;h--;){var d;if((null==(d=t[h])?void 0:d.sn)<e.startSN)break;var u=gr(e,l,t,h,s);if(-1!==u){o.tagAnchor=e.fragments[u].ref;break}}}}function gr(t,e,i,r,s){var n=i[r];if(n){var a,o=n.programDateTime;if((e>=o||0===r)&&e<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||s)-n.start)){var l=i[r].sn-t.startSN;if(l<0)return-1;var h=t.fragments;if(h.length>i.length)for(var d=(i[r+1]||h[h.length-1]).sn-t.startSN;d>l;d--){var u=h[d].programDateTime;if(e>=u&&e<u+1e3*h[d].duration)return d}return l}}return-1}function mr(t,e,i){var r,s,n=new wi(t,i),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&Y.error("Invalid IV: "+n.IV);var u=o?cr.resolve(o,e):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new nr(a,u,d,c,l,n.KEYID)}function pr(t){var e=new wi(t).decimalFloatingPoint("TIME-OFFSET");return k(e)?e:null}function vr(t,e){var i=(t||"").split(/[ ,]+/).filter((function(t){return t}));["video","audio","text"].forEach((function(t){var r=i.filter((function(e){return Bt(e,t)}));r.length&&(e[t+"Codec"]=r.map((function(t){return t.split("/")[0]})).join(","),i=i.filter((function(t){return-1===r.indexOf(t)})))})),e.unknownCodecs=i}function yr(t,e,i){var r=e[i];r&&(t[i]=r)}function Er(t,e){for(var i=t[e],r=e;r--;){var s=t[r];if(!s)return;s.programDateTime=i.programDateTime-1e3*s.duration,i=s}}function Tr(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Sr(t,e,i,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function Ar(t,e,i){t.levelkeys=e;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some((function(t){return e[t].isCommonEncryption}))||r.push(t)}function Lr(t,e,i){t.playlistParsingError=new Error("#EXT-X-"+e+" must not appear more than once ("+i[0]+")")}function Rr(t,e,i){t.playlistParsingError=new Error("#EXT-X-"+e+" must appear before the first Media Segment ("+i[0]+")")}function Ir(t,e){var i=e.startPTS;if(k(i)){var r,s=0;e.sn>t.sn?(s=i-t.start,r=t):(s=t.start-i,r=e),r.duration!==s&&r.setDuration(s)}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 br(t,e,i,r,s,n,a){r-i<=0&&(a.warn("Fragment should have a positive duration",e),r=i+e.duration,n=s+e.duration);var o=i,l=r,h=e.startPTS,d=e.endPTS;if(k(h)){var u=Math.abs(h-i);t&&u>t.totalduration?a.warn("media timestamps and playlist times differ by "+u+"s for level "+e.level+" "+t.url):k(e.deltaPTS)?e.deltaPTS=Math.max(u,e.deltaPTS):e.deltaPTS=u,o=Math.max(i,h),i=Math.min(i,h),s=void 0!==e.startDTS?Math.min(s,e.startDTS):s,l=Math.min(r,d),r=Math.max(r,d),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}var c=i-e.start;0!==e.start&&e.setStart(i),e.setDuration(r-e.start),e.startPTS=i,e.maxStartPTS=o,e.startDTS=s,e.endPTS=r,e.minEndPTS=l,e.endDTS=n;var f,g=e.sn;if(!t||g<t.startSN||g>t.endSN)return 0;var m=g-t.startSN,p=t.fragments;for(p[m]=e,f=m;f>0;f--)Ir(p[f],p[f-1]);for(f=m;f<p.length-1;f++)Ir(p[f],p[f+1]);return t.fragmentHint&&Ir(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function kr(t,e,i){if(t!==e){for(var r,s=null,n=t.fragments,a=n.length-1;a>=0;a--){var o=n[a].initSegment;if(o){s=o;break}}t.fragmentHint&&delete t.fragmentHint.endPTS,Pr(t,e,(function(t,i,n,a){if((!e.startCC||e.skippedSegments)&&i.cc!==t.cc){for(var o=t.cc-i.cc,l=n;l<a.length;l++)a[l].cc+=o;e.endCC=a[a.length-1].cc}k(t.startPTS)&&k(t.endPTS)&&(i.setStart(i.startPTS=t.startPTS),i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.setDuration(t.endPTS-t.startPTS),i.duration&&(r=i),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(i.elementaryStreams=t.elementaryStreams),i.loader=t.loader,t.hasStats&&(i.stats=t.stats),t.initSegment&&(i.initSegment=t.initSegment,s=t.initSegment)}));var l=e.fragments,h=e.fragmentHint?l.concat(e.fragmentHint):l;if(s&&h.forEach((function(t){var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})),e.skippedSegments){if(e.deltaUpdateFailed=l.some((function(t){return!t})),e.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var d=e.skippedSegments;d--;)l.shift();e.startSN=l[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Dr(t.dateRanges,e,i));var u=t.fragments.filter((function(t){return t.rawProgramDateTime}));if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(var c=1;c<h.length;c++)null===h[c].programDateTime&&Tr(h[c],h[c-1],u);fr(u,e)}e.endCC=l[l.length-1].cc}if(!e.startCC){var f,g=Mr(t,e.startSN-1);e.startCC=null!=(f=null==g?void 0:g.cc)?f:l[0].cc}_r(t.partList,e.partList,(function(t,e){e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),r?br(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):wr(t,e),l.length&&(e.totalduration=e.edge-l[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;var m=e.advancedDateTime;if(e.advanced&&m){var p=e.edge;e.driftStart||(e.driftStartTime=m,e.driftStart=p),e.driftEndTime=m,e.driftEnd=p}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}}function Dr(t,e,i){var r=e.dateRanges,s=e.recentlyRemovedDateranges,n=a({},t);s&&s.forEach((function(t){delete n[t]}));var o=Object.keys(n).length;return o&&Object.keys(r).forEach((function(t){var e=n[t],s=new Fi(r[t].attr,e);s.isValid?(n[t]=s,e||(s.tagOrder+=o)):i.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+Le(r[t].attr)+'"')})),n}function _r(t,e,i){if(t&&e)for(var r=0,s=0,n=t.length;s<=n;s++){var a=t[s],o=e[s+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):r--}}function Pr(t,e,i){for(var r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?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,h=s;h<=n;h++){var d=l[a+h],u=o[h];if(r&&!u&&d&&(u=e.fragments[h]=d),d&&u){if(i(d,u,h,o),d.url&&d.url!==u.url)return void(e.playlistParsingError=Cr("media sequence mismatch "+u.sn+":",t,e,d,u));if(d.cc!==u.cc)return void(e.playlistParsingError=Cr("discontinuity sequence mismatch ("+d.cc+"!="+u.cc+")",t,e,d,u))}}}function Cr(t,e,i,r,s){return new Error(t+" "+s.url+"\nPlaylist starting @"+e.startSN+"\n"+e.m3u8+"\n\nPlaylist starting @"+i.startSN+"\n"+i.m3u8)}function wr(t,e,i){void 0===i&&(i=!0);var r=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,n=r>=0,a=0;if(n&&r<s.length)a=s[r].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&i)a=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}Or(e,a)}function Or(t,e){if(e){for(var i=t.fragments,r=t.skippedSegments;r<i.length;r++)i[r].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function xr(t,e){void 0===e&&(e=1/0);var i=1e3*t.targetduration;if(t.updated){var r=t.fragments,s=4;if(r.length&&i*s>e){var n=1e3*r[r.length-1].duration;n<i&&(i=n)}}else i/=2;return Math.round(i)}function Mr(t,e,i){if(!t)return null;var r=t.fragments[e-t.startSN];return r||((r=t.fragmentHint)&&r.sn===e?r:e<t.startSN&&i&&i.sn===e?i:null)}function Fr(t,e,i){return t?Nr(t.partList,e,i):null}function Nr(t,e,i){if(t)for(var r=t.length;r--;){var s=t[r];if(s.index===i&&s.fragment.sn===e)return s}return null}function Ur(t){t.forEach((function(t,e){var i;null==(i=t.details)||i.fragments.forEach((function(t){t.level=e,t.initSegment&&(t.initSegment.level=e)}))}))}function Br(t,e){for(var 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 Gr(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}function $r(t,e){var i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function Kr(t,e){for(var i=e.fragments,r=0,s=i.length;r<s;r++)$r(i[r],t);e.fragmentHint&&$r(e.fragmentHint,t),e.alignedSliding=!0}function Vr(t,e){t&&(Hr(e,t),e.alignedSliding||Yr(e,t),e.alignedSliding||e.skippedSegments||wr(t,e,!1))}function Hr(t,e){if(Gr(e,t)){var i=Math.min(e.endCC,t.endCC),r=Br(e.fragments,i),s=Br(t.fragments,i);r&&s&&(Y.log("Aligning playlist at start of dicontinuity sequence "+i),Kr(r.start-s.start,t))}}function Yr(t,e){if(t.hasProgramDateTime&&e.hasProgramDateTime){var i=t.fragments,r=e.fragments;if(i.length&&r.length){var s,n,a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=Br(r,a),n=Br(i,a)),s&&n||(n=Br(i,(s=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.length/2)]);var o=s.programDateTime,l=n.programDateTime;o&&l&&Kr((l-o)/1e3-(n.start-s.start),t)}}}var Wr={toString:function(t){for(var e="",i=t.length,r=0;r<i;r++)e+="["+t.start(r).toFixed(3)+"-"+t.end(r).toFixed(3)+"]";return e}},jr={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"},qr=function(t){function e(e,i,r,s,n){var a;return(a=t.call(this,s,e.logger)||this).hls=void 0,a.fragPrevious=null,a.fragCurrent=null,a.fragmentTracker=void 0,a.transmuxer=null,a._state=jr.STOPPED,a.playlistType=void 0,a.media=null,a.mediaBuffer=null,a.config=void 0,a.bitrateTest=!1,a.lastCurrentTime=0,a.nextLoadPosition=0,a.startPosition=0,a.startTimeOffset=null,a.retryDate=0,a.levels=null,a.fragmentLoader=void 0,a.keyLoader=void 0,a.levelLastLoaded=null,a.startFragRequested=!1,a.decrypter=void 0,a.initPTS=[],a.buffering=!0,a.loadingParts=!1,a.loopSn=void 0,a.onMediaSeeking=function(){var t=a,e=t.config,i=t.fragCurrent,r=t.media,s=t.mediaBuffer,n=t.state,o=r?r.currentTime:0,l=Ri.bufferInfo(s||r,o,e.maxBufferHole),h=!l.len;if(a.log("Media seeking to "+(k(o)?o.toFixed(3):o)+", state: "+n+", "+(h?"out of":"in")+" buffer"),a.state===jr.ENDED)a.resetLoadingState();else if(i){var d=e.maxFragLookUpTolerance,u=i.start-d,c=i.start+i.duration+d;if(h||c<l.start||u>l.end){var f=o>c;(o<u||f)&&(f&&i.loader&&(a.log("Cancelling fragment load for seek (sn: "+i.sn+")"),i.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(r&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var g=Math.max(l.end,o),m=a.shouldLoadParts(a.getLevelDetails(),g);m&&(a.log("LL-Part loading ON after seeking to "+o.toFixed(2)+" with buffer @"+g.toFixed(2)),a.loadingParts=m)}a.hls.hasEnoughToStart||(a.log("Setting "+(h?"startPosition":"nextLoadPosition")+" to "+o+" for seek without enough to start"),a.nextLoadPosition=o,h&&(a.startPosition=o)),a.tickImmediate()},a.onMediaEnded=function(){a.log("setting startPosition to 0 because media ended"),a.startPosition=a.lastCurrentTime=0},a.playlistType=n,a.hls=e,a.fragmentLoader=new mi(e.config),a.keyLoader=r,a.fragmentTracker=i,a.config=e.config,a.decrypter=new fi(e.config),a}l(e,t);var i=e.prototype;return i.registerListeners=function(){var t=this.hls;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(w.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(w.ERROR,this.onError,this)},i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(t){},i.stopLoad=function(){if(this.state!==jr.STOPPED){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var 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=jr.STOPPED}},i.pauseBuffering=function(){this.buffering=!1},i.resumeBuffering=function(){this.buffering=!0},i._streamEnded=function(t,e){if(e.live||!this.media)return!1;var i=t.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var s=t.buffered;this.config.maxBufferHole&&s&&s.length>1&&(t=Ri.bufferedInfo(s,t.start,0));var n=t.nextStart;if(n&&n>r&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;var a=e.partList;if(null!=a&&a.length){var o=a[a.length-1];return Ri.isBuffered(this.media,o.start+o.duration/2)}var l=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)},i.getLevelDetails=function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details},i.onMediaAttached=function(t,e){var i=this.media=this.mediaBuffer=e.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===jr.STOPPED&&this.startLoad(r.startPosition)},i.onMediaDetaching=function(t,e){var i=!!e.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},i.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},i.onError=function(t,e){},i.onManifestLoaded=function(t,e){this.startTimeOffset=e.startTimeOffset},i.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),t.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},i.onHandlerDestroyed=function(){this.state=jr.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,t.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)},i._loadFragForPlayback=function(t,e,i){var r=this,s=function(t){var e=t.frag;if(r.fragContextChanged(e))return r.warn(e.type+" sn: "+e.sn+(t.part?" part: "+t.part.index:"")+" of "+r.fragInfo(e,!1,t.part)+") was dropped during download."),void r.fragmentTracker.removeFragment(e);e.stats.chunkCount++,r._handleFragmentLoadProgress(t)};this._doFragLoad(t,e,i,s).then((function(t){if(t){var e=r.state,i=t.frag;r.fragContextChanged(i)?(e===jr.FRAG_LOADING||!r.fragCurrent&&e===jr.PARSING)&&(r.fragmentTracker.removeFragment(i),r.state=jr.IDLE):("payload"in t&&(r.log("Loaded "+i.type+" sn: "+i.sn+" of "+r.playlistLabel()+" "+i.level),r.hls.trigger(w.FRAG_LOADED,t)),r._handleFragmentLoadComplete(t))}})).catch((function(e){r.state!==jr.STOPPED&&r.state!==jr.ERROR&&(r.warn("Frag error: "+((null==e?void 0:e.message)||e)),r.resetFragmentLoading(t))}))},i.clearTrackerIfNeeded=function(t){var e,i=this.fragmentTracker;if(i.getState(t)===ei.APPENDING){var r=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,r),n=Math.max(t.duration,s?s.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?t.sn-a.sn:0)||this.reduceMaxBufferLength(n,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===ei.PARTIAL&&i.removeFragment(t))},i.checkLiveUpdate=function(t){if(t.updated&&!t.live){var 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)},i.waitForLive=function(t){var e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)},i.flushMainBuffer=function(t,e,i){if(void 0===i&&(i=null),t-e){var r={startOffset:t,endOffset:e,type:i};this.hls.trigger(w.BUFFER_FLUSHING,r)}},i._loadInitSegment=function(t,e){var i=this;this._doFragLoad(t,e).then((function(t){var e=null==t?void 0:t.frag;if(!e||i.fragContextChanged(e)||!i.levels)throw new Error("init load aborted");return t})).then((function(t){var e=i.hls,r=t.frag,s=t.payload,n=r.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&Bi(n.method)){var a=self.performance.now();return i.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,Gi(n.method)).catch((function(t){throw e.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:r}),t})).then((function(s){var n=self.performance.now();return e.trigger(w.FRAG_DECRYPTED,{frag:r,payload:s,stats:{tstart:a,tdecrypt:n}}),t.payload=s,i.completeInitSegmentLoad(t)}))}return i.completeInitSegmentLoad(t)})).catch((function(e){i.state!==jr.STOPPED&&i.state!==jr.ERROR&&(i.warn(e),i.resetFragmentLoading(t))}))},i.completeInitSegmentLoad=function(t){if(!this.levels)throw new Error("init load aborted, missing levels");var e=t.frag.stats;this.state!==jr.STOPPED&&(this.state=jr.IDLE),t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now(),this.tick()},i.unhandledEncryptionError=function(t,e){var i,r,s=t.tracks;if(s&&!e.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var n=this.media,a=new Error("Encrypted track with no key in "+this.fragInfo(e)+" (media "+(n?"attached mediaKeys: "+n.mediaKeys:"detached")+")");return this.warn(a.message),!(!n||n.mediaKeys)&&(this.hls.trigger(w.ERROR,{type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:e}),this.resetTransmuxer(),!0)}return!1},i.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.sn!==e.sn||t.level!==e.level},i.fragBufferedComplete=function(t,e){var i=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:"+(i?Wr.toString(Ri.getBuffered(i)):"(detached)")+")"),et(t)){var r;if(t.type!==x.SUBTITLE){var s=t.elementaryStreams;if(!Object.keys(s).some((function(t){return!!s[t]})))return void(this.state=jr.IDLE)}var n=null==(r=this.levels)?void 0:r[t.level];null!=n&&n.fragmentError&&(this.log("Resetting level fragment error count of "+n.fragmentError+" on frag buffered"),n.fragmentError=0)}this.state=jr.IDLE},i._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var i=t.frag,r=t.part,s=t.partsLoaded,n=!s||0===s.length||s.some((function(t){return!t})),a=new Si(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}},i._handleFragmentLoadProgress=function(t){},i._doFragLoad=function(t,e,i,r){var s,n=this;void 0===i&&(i=null),this.fragCurrent=t;var a=e.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var o=null;!t.encrypted||null!=(s=t.decryptdata)&&s.key?t.encrypted||(o=this.keyLoader.loadClear(t,a.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired"):(this.log("Loading key for "+t.sn+" of ["+a.startSN+"-"+a.endSN+"], "+this.playlistLabel()+" "+t.level),this.state=jr.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then((function(t){if(!n.fragContextChanged(t.frag))return n.hls.trigger(w.KEY_LOADED,t),n.state===jr.KEY_LOADING&&(n.state=jr.IDLE),t})),this.hls.trigger(w.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));var l,h=this.fragPrevious;if(et(t)&&(!h||t.sn!==h.sn)){var d=this.shouldLoadParts(e.details,t.end);d!==this.loadingParts&&(this.log("LL-Part loading "+(d?"ON":"OFF")+" loading sn "+(null==h?void 0:h.sn)+"->"+t.sn),this.loadingParts=d)}if(i=Math.max(t.start,i||0),this.loadingParts&&et(t)){var u=a.partList;if(u&&r){i>t.end&&a.fragmentHint&&(t=a.fragmentHint);var c=this.getNextPart(u,t,i);if(c>-1){var f,g=u[c];return t=this.fragCurrent=g.fragment,this.log("Loading "+t.type+" sn: "+t.sn+" part: "+g.index+" ("+c+"/"+(u.length-1)+") of "+this.fragInfo(t,!1,g)+") cc: "+t.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(i.toFixed(3))),this.nextLoadPosition=g.start+g.duration,this.state=jr.FRAG_LOADING,f=o?o.then((function(i){return!i||n.fragContextChanged(i.frag)?null:n.doFragPartsLoad(t,g,e,r)})).catch((function(t){return n.handleFragLoadError(t)})):this.doFragPartsLoad(t,g,e,r).catch((function(t){return n.handleFragLoadError(t)})),this.hls.trigger(w.FRAG_LOADING,{frag:t,part:g,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!t.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(et(t)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+i.toFixed(2)+" Check buffer at sn: "+t.sn+" loaded parts: "+(null==(l=a.partList)?void 0:l.filter((function(t){return t.loaded})).map((function(t){return"["+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+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(i.toFixed(3))),k(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=jr.FRAG_LOADING;var m,p=this.config.progressive;return m=p&&o?o.then((function(e){return!e||n.fragContextChanged(e.frag)?null:n.fragmentLoader.load(t,r)})).catch((function(t){return n.handleFragLoadError(t)})):Promise.all([this.fragmentLoader.load(t,p?r:void 0),o]).then((function(t){var e=t[0];return!p&&r&&r(e),e})).catch((function(t){return n.handleFragLoadError(t)})),this.hls.trigger(w.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):m},i.doFragPartsLoad=function(t,e,i,r){var s=this;return new Promise((function(n,a){var o,l=[],h=null==(o=i.details)?void 0:o.partList,d=function(e){s.fragmentLoader.loadPart(t,e,r).then((function(r){l[e.index]=r;var a=r.part;s.hls.trigger(w.FRAG_LOADED,r);var o=Fr(i.details,t.sn,e.index+1)||Nr(h,t.sn,e.index+1);if(!o)return n({frag:t,part:a,partsLoaded:l});d(o)})).catch(a)};d(e)}))},i.handleFragLoadError=function(t){if("data"in t){var e=t.data;e&&e.details===C.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(w.ERROR,e)}else this.hls.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null},i._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===jr.PARSING){var i=e.frag,r=e.part,s=e.level,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n);var a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+i.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(i,r,s,t.partial)}else this.fragCurrent||this.state===jr.STOPPED||this.state===jr.ERROR||(this.state=jr.IDLE)},i.shouldLoadParts=function(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i,r,s=t.partList[0];if(e>=s.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1},i.getCurrentContext=function(t){var e=this.levels,i=this.fragCurrent,r=t.level,s=t.sn,n=t.part;if(null==e||!e[r])return this.warn("Levels object was unset while buffering fragment "+s+" of "+this.playlistLabel()+" "+r+". The current chunk will not be buffered."),null;var a=e[r],o=a.details,l=n>-1?Fr(o,s,n):null,h=l?l.fragment:Mr(o,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null},i.bufferFragmentData=function(t,e,i,r,s){if(this.state===jr.PARSING){var n=t.data1,a=t.data2,o=n;if(a&&(o=Dt(n,a)),o.length){var l=this.initPTS[e.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:t.type,frag:e,part:i,chunkMeta:r,offset:h,parent:e.type,data:o};if(this.hls.trigger(w.BUFFER_APPENDING,d),t.dropped&&t.independent&&!i){if(s)return;this.flushBufferGap(e)}}}},i.flushBufferGap=function(t){var e=this.media;if(e)if(Ri.isBuffered(e,e.currentTime)){var i=e.currentTime,r=Ri.bufferInfo(e,i,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,r.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}else this.flushMainBuffer(0,t.start)},i.getFwdBufferInfo=function(t,e){var i,r=this.getLoadPosition();if(!k(r))return null;var s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,r,e,s)},i.getFwdBufferInfoAtPos=function(t,e,i,r){var s=Ri.bufferInfo(t,e,r);if(0===s.len&&void 0!==s.nextStart){var n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(s.nextStart<=n.end||n.gap)){var a=Math.max(Math.min(s.nextStart,n.end)-e,r);return Ri.bufferInfo(t,e,a)}}return s},i.getMaxBufferLength=function(t){var e,i=this.config;return e=t?Math.max(8*i.maxBufferSize/t,i.maxBufferLength):i.maxBufferLength,Math.min(e,i.maxMaxBufferLength)},i.reduceMaxBufferLength=function(t,e){var i=this.config,r=Math.max(Math.min(t-e,i.maxBufferLength),e),s=Math.max(t-3*e,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn("Reduce max buffer length to "+s+"s"),!0)},i.getAppendedFrag=function(t,e){void 0===e&&(e=x.MAIN);var i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i},i.getNextFragment=function(t,e){var i=e.fragments,r=i.length;if(!r)return null;var s=this.config,n=i[0].start,a=s.lowLatencyMode&&!!e.partList,o=null;if(e.live){var l=s.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: "+r+", need: "+l+")"),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var h;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);var d=this.hls.startPosition,u=this.hls.liveSyncPosition,c=o?(-1!==d&&d>=n?d:u)||o.start:t;this.log("Setting startPosition to "+c+" to match start frag at live edge. mainStart: "+d+" liveSyncPosition: "+u+" frag.start: "+(null==(h=o)?void 0:h.start)),this.startPosition=this.nextLoadPosition=c}}else t<=n&&(o=i[0]);if(!o){var f=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,f,e)}var g=this.filterReplacedPrimary(o,e);if(!g&&o){var m=o.sn-e.startSN;g=this.filterReplacedPrimary(i[m+1]||null,e)}return this.mapToInitFragWhenRequired(g)},i.isLoopLoading=function(t,e){var i=this.fragmentTracker.getState(t);return(i===ei.OK||i===ei.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e},i.getNextFragmentLoopLoading=function(t,e,i,r,s){var n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e))&&!n.gap&&i.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==a&&i.len+a.len>=s){var o=n.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+r+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,n},i.filterReplacedPrimary=function(t,e){if(!t)return t;if(Xr(this.config)&&t.type!==x.SUBTITLE){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var s=r.event;if(s){if(s.appendInPlace||Math.abs(t.start-r.start)>1||0===r.start)return null}else{if(t.end<=r.start&&!1===(null==e?void 0:e.live))return null;if(t.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||t.start-r.end>1))return null}}var n=null==i?void 0:i.playerQueue;if(n)for(var a=n.length;a--;){var o=n[a].interstitial;if(o.appendInPlace&&t.start>=o.startTime&&t.end<=o.resumeTime)return null}}return t},i.mapToInitFragWhenRequired=function(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment},i.getNextPart=function(t,e,i){for(var r=-1,s=!1,n=!0,a=0,o=t.length;a<o;a++){var l=t[a];if(n=n&&!l.independent,r>-1&&i<l.start)break;var h=l.loaded;h?r=-1:(s||(l.independent||n)&&l.fragment===e)&&(l.fragment!==e&&this.warn("Need buffer at "+i+" but next unloaded part starts at "+l.start),r=a),s=h}return r},i.loadedEndOfParts=function(t,e){for(var i,r=t.length;r--;){if(!(i=t[r]).loaded)return!1;if(e>i.start)return!0}return!1},i.getInitialLiveFragment=function(t){var e=t.fragments,i=this.fragPrevious,r=null;if(i){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+i.programDateTime),r=Be(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var s=i.sn+1;if(s>=t.startSN&&s<=t.endSN){var n=e[s-t.startSN];i.cc===n.cc&&(r=n,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=He(t,i.cc,i.end))&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(r=this.getFragmentAtPosition(a,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r},i.getFragmentAtPosition=function(t,e,i){var r,s,n=this.config,a=this.fragPrevious,o=i.fragments,l=i.endSN,h=i.fragmentHint,d=n.maxFragLookUpTolerance,u=i.partList,c=!!(this.loadingParts&&null!=u&&u.length&&h);if(c&&!this.bitrateTest&&u[u.length-1].fragment.sn===h.sn&&(o=o.concat(h),l=h.sn),r=t<e?Ge(a,o,t,t<this.lastCurrentTime||t>e-d||null!=(s=this.media)&&s.paused||!this.startFragRequested?0:d):o[o.length-1]){var f=r.sn-i.startSN,g=this.fragmentTracker.getState(r);if((g===ei.OK||g===ei.PARTIAL&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||u[0].fragment.sn>r.sn||!i.live)&&r.level===a.level){var m=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(m)!==ei.OK?m:null}}return r},i.alignPlaylists=function(t,e,i){var r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;var s=t.fragmentStart,n=!e,a=t.alignedSliding&&k(s);if(n||!a&&!s){Vr(i,t);var o=t.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(e?e.startSN:"na")+"->"+t.startSN+" fragments: "+r),o}return s},i.waitForCdnTuneIn=function(t){var e=3;return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*e)},i.setStartPosition=function(t,e){var i=this.startPosition;i<e&&(i=-1);var r=this.timelineOffset;if(-1===i){var s=null!==this.startTimeOffset,n=s?this.startTimeOffset:t.startTimeOffset;null!==n&&k(n)?(i=e+n,n<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log("Setting startPosition to "+i+" for start time offset "+n+" found in "+(s?"multivariant":"media")+" playlist"),this.startPosition=i):t.live?(i=this.hls.liveSyncPosition||e,this.log("Setting startPosition to -1 to start at live edge "+i),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r},i.getLoadPosition=function(){var t,e=this.media,i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i},i.handleFragLoadAborted=function(t,e){this.transmuxer&&t.type===this.playlistType&&et(t)&&t.stats.aborted&&(this.log("Fragment "+t.sn+(e?" part "+e.index:"")+" of "+this.playlistLabel()+" "+t.level+" was aborted"),this.resetFragmentLoading(t))},i.resetFragmentLoading=function(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===jr.FRAG_LOADING_WAITING_RETRY)||(this.state=jr.IDLE)},i.onFragmentOrKeyLoadError=function(t,e){if(e.chunkMeta&&!e.frag){var i=this.getCurrentContext(e.chunkMeta);i&&(e.frag=i.frag)}var r=e.frag;if(r&&r.type===t&&this.levels)if(this.fragContextChanged(r)){var s;this.warn("Frag load error must match current frag to retry "+r.url+" > "+(null==(s=this.fragCurrent)?void 0:s.url))}else{var n=e.details===C.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(r,!0);var a=e.errorAction,o=a||{},l=o.action,h=o.flags,d=o.retryCount,u=void 0===d?0:d,c=o.retryConfig,f=!!a&&!!c,g=f&&l===ze.RetryRequest,m=f&&!a.resolved&&h===Ze.MoveAllAlternatesMatchingHost;if(!g&&m&&et(r)&&!r.endList)this.resetFragmentErrors(t),this.treatAsGap(r),a.resolved=!0;else if((g||m)&&u<c.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);var p=je(c,u);this.warn("Fragment "+r.sn+" of "+t+" "+r.level+" errored with "+e.details+", retrying loading "+(u+1)+"/"+c.maxNumRetry+" in "+p+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+p,this.state=jr.FRAG_LOADING_WAITING_RETRY}else if(c&&a){if(this.resetFragmentErrors(t),!(u<c.maxNumRetry))return void this.warn(e.details+" reached or exceeded max retry ("+u+")");n||l===ze.RemoveAlternatePermanently||(a.resolved=!0)}else l===ze.SendAlternateToPenaltyBox?this.state=jr.WAITING_LEVEL:this.state=jr.ERROR;this.tickImmediate()}},i.reduceLengthAndFlushBuffer=function(t){if(this.state===jr.PARSING||this.state===jr.PARSED){var e=t.frag,i=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==e?void 0:e.duration)||10);var n=!s;return n&&this.warn("Buffer full error while media.currentTime ("+this.getLoadPosition()+") is not buffered, flush "+i+" buffer"),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1},i.resetFragmentErrors=function(t){t===x.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==jr.STOPPED&&(this.state=jr.IDLE)},i.afterBufferFlushed=function(t,e,i){if(t){var r=Ri.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,i),this.state===jr.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==jr.STOPPED&&(this.state=jr.IDLE)},i.resetStartWhenNotLoaded=function(t){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var 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}},i.resetWhenMissingContext=function(t){this.warn("The loading context changed while buffering fragment "+t.sn+" of "+this.playlistLabel()+" "+t.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},i.removeUnbufferedFrags=function(t){void 0===t&&(t=0),this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(t,e,i,r){var s=this,n=i.details;if(n){var a;if(!Object.keys(t.elementaryStreams).reduce((function(e,a){var o=t.elementaryStreams[a];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return s.warn("Could not parse fragment "+t.sn+" "+a+" duration reliably ("+l+")"),e||!1;var h=r?0:br(n,t,o.startPTS,o.endPTS,o.startDTS,o.endDTS,s);return s.hls.trigger(w.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:a,frag:t,start:o.startPTS,end:o.endPTS}),!0}return e}),!1)&&(0===i.fragmentError&&this.treatAsGap(t,i),null===(null==(a=this.transmuxer)?void 0:a.error))){var o=new Error("Found no media in fragment "+t.sn+" of "+this.playlistLabel()+" "+t.level+" resetting transmuxer to fallback to playlist timing");if(this.warn(o.message),this.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:t,reason:"Found no media in msn "+t.sn+" of "+this.playlistLabel()+' "'+i.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=jr.PARSED,this.log("Parsed "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+this.fragInfo(t,!1,e)+")"),this.hls.trigger(w.FRAG_PARSED,{frag:t,part:e})}else this.warn("level.details undefined")},i.playlistLabel=function(){return this.playlistType===x.MAIN?"level":"track"},i.fragInfo=function(t,e,i){var r,s;return void 0===e&&(e=!0),this.playlistLabel()+" "+t.level+" ("+(i?"part":"frag")+":["+(null!=(r=e&&!i?t.startPTS:(i||t).start)?r:NaN).toFixed(3)+"-"+(null!=(s=e&&!i?t.endPTS:(i||t).end)?s:NaN).toFixed(3)+"]"+(i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"")},i.treatAsGap=function(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)},i.resetTransmuxer=function(){var t;null==(t=this.transmuxer)||t.reset()},i.recoverWorkerError=function(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},s(e,[{key:"startPositionValue",get:function(){var t=this.nextLoadPosition,e=this.startPosition;return-1===e&&t?t:e}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var t,e=this.config.timelineOffset;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}},{key:"primaryPrefetch",get:function(){var t;return!(!Xr(this.config)||!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event))}},{key:"state",get:function(){return this._state},set:function(t){var e=this._state;e!==t&&(this._state=t,this.log(e+"->"+t))}}])}(Ti);function Xr(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}var Qr=function(){function t(){this.chunks=[],this.dataLength=0}var e=t.prototype;return e.push=function(t){this.chunks.push(t),this.dataLength+=t.length},e.flush=function(){var t,e=this.chunks,i=this.dataLength;return e.length?(t=1===e.length?e[0]:zr(e,i),this.reset(),t):new Uint8Array(0)},e.reset=function(){this.chunks.length=0,this.dataLength=0},t}();function zr(t,e){for(var i=new Uint8Array(e),r=0,s=0;s<t.length;s++){var n=t[s];i.set(n,r),r+=n.length}return i}function Zr(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 Jr(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 ts(t,e){var i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3]}function es(t,e){for(var i=e,r=0;Jr(t,e);)r+=10,r+=ts(t,e+6),Zr(t,e+10)&&(r+=10),e+=r;if(r>0)return t.subarray(i,i+r)}function is(t,e,i,r){var s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[i+2],a=n>>2&15;if(!(a>12)){var o=1+(n>>6&3),l=e[i+3]>>6&3|(1&n)<<2,h="mp4a.40."+o,d=s[a],u=a;5!==o&&29!==o||(u-=3);var c=[o<<3|(14&u)>>1,(1&u)<<7|l<<3];return Y.log("manifest codec:"+r+", parsed codec:"+h+", channels:"+l+", rate:"+d+" (ADTS object type:"+o+" sampling index:"+a+")"),{config:c,samplerate:d,channelCount:l,codec:h,parsedCodec:h,manifestCodec:r}}var f=new Error("invalid ADTS sampling index:"+a);t.emit(w.ERROR,w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message})}function rs(t,e){return 255===t[e]&&240==(246&t[e+1])}function ss(t,e){return 1&t[e+1]?7:9}function ns(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function as(t,e){return e+5<t.length}function os(t,e){return e+1<t.length&&rs(t,e)}function ls(t,e){return as(t,e)&&rs(t,e)&&ns(t,e)<=t.length-e}function hs(t,e){if(os(t,e)){var i=ss(t,e);if(e+i>=t.length)return!1;var r=ns(t,e);if(r<=i)return!1;var s=e+r;return s===t.length||os(t,s)}return!1}function ds(t,e,i,r,s){if(!t.samplerate){var n=is(e,i,r,s);if(!n)return;a(t,n)}}function us(t){return 9216e4/t}function cs(t,e){var i=ss(t,e);if(e+i<=t.length){var r=ns(t,e)-i;if(r>0)return{headerLength:i,frameLength:r}}}function fs(t,e,i,r,s){var n,a=r+s*us(t.samplerate),o=cs(e,i);if(o){var l=o.frameLength,h=o.headerLength,d=h+l,u=Math.max(0,i+d-e.length);u?(n=new Uint8Array(d-h)).set(e.subarray(i+h,e.length),0):n=e.subarray(i+h,i+d);var c={unit:n,pts:a};return u||t.samples.push(c),{sample:c,length:d,missing:u}}var f=e.length-i;return(n=new Uint8Array(f)).set(e.subarray(i,e.length),0),{sample:{unit:n,pts:a},length:f,missing:-1}}function gs(t,e){return Jr(t,e)&&ts(t,e+6)+10<=t.length-e}function ms(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function ps(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1/0),vs(t,e,i,Uint8Array)}function vs(t,e,i,r){var s=ys(t),n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);var a=Es(t)?t.byteOffset:0,o=(a+t.byteLength)/n,l=(a+e)/n,h=Math.floor(Math.max(0,Math.min(l,o)));return new r(s,h,Math.floor(Math.min(h+Math.max(i,0),o))-h)}function ys(t){return t instanceof ArrayBuffer?t:t.buffer}function Es(t){return t&&t.buffer instanceof ArrayBuffer&&void 0!==t.byteLength&&void 0!==t.byteOffset}function Ts(t){var e={key:t.type,description:"",data:"",mimeType:null,pictureType:null},i=3;if(!(t.size<2))if(t.data[0]===i){var r=t.data.subarray(1).indexOf(0);if(-1!==r){var s=X(ps(t.data,1,r)),n=t.data[2+r],a=t.data.subarray(3+r).indexOf(0);if(-1!==a){var o,l=X(ps(t.data,3+r,a));return o="--\x3e"===s?X(ps(t.data,4+r+a)):ms(t.data.subarray(4+r+a)),e.mimeType=s,e.pictureType=n,e.description=l,e.data=o,e}}}else console.log("Ignore frame with unrecognized character encoding")}function Ss(t){if(!(t.size<2)){var e=X(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}}function As(t){if(!(t.size<2)){if("TXXX"===t.type){var e=1,i=X(t.data.subarray(e),!0);e+=i.length+1;var r=X(t.data.subarray(e));return{key:t.type,info:i,data:r}}var s=X(t.data.subarray(1));return{key:t.type,info:"",data:s}}}function Ls(t){if("WXXX"===t.type){if(t.size<2)return;var e=1,i=X(t.data.subarray(e),!0);e+=i.length+1;var r=X(t.data.subarray(e));return{key:t.type,info:i,data:r}}var s=X(t.data);return{key:t.type,info:"",data:s}}function Rs(t){return"PRIV"===t.type?Ss(t):"W"===t.type[0]?Ls(t):"APIC"===t.type?Ts(t):As(t)}function Is(t){var e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=ts(t,4),r=10;return{type:e,size:i,data:t.subarray(r,r+i)}}var bs=10,ks=10;function Ds(t){for(var e=0,i=[];Jr(t,e);){var r=ts(t,e+6);t[e+5]>>6&1&&(e+=bs);for(var s=(e+=bs)+r;e+ks<s;){var n=Is(t.subarray(e)),a=Rs(n);a&&i.push(a),e+=n.size+bs}Zr(t,e)&&(e+=bs)}return i}function _s(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Ps(t){if(8===t.data.byteLength){var e=new Uint8Array(t.data),i=1&e[3],r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Cs(t){for(var e=Ds(t),i=0;i<e.length;i++){var r=e[i];if(_s(r))return Ps(r)}}var ws=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Os(t,e){return void 0===t&&(t=""),void 0===e&&(e=9e4),{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var xs=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(t){this.initPTS=t,this.resetContiguity()},e.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,i){},e.demux=function(t,e){this.cachedData&&(t=Dt(this.cachedData,t),this.cachedData=null);var i,r=es(t,0),s=r?r.length:0,n=this._audioTrack,a=this._id3Track,o=r?Cs(r):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&k(o))&&(this.basePTS=Ms(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:ws.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(t,s)){var h=this.appendFrame(n,t,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i=s+=h.length):s=l}else gs(t,s)?(r=es(t,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:ws.audioId3,duration:Number.POSITIVE_INFINITY}),i=s+=r.length):s++;if(s===l&&i!==l){var d=t.slice(i);this.cachedData?this.cachedData=Dt(this.cachedData,d):this.cachedData=d}}return{audioTrack:n,videoTrack:Os(),id3Track:a,textTrack:Os()}},e.demuxSampleAes=function(t,e,i){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},e.flush=function(t){var e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Os(),id3Track:this._id3Track,textTrack:Os()}},e.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},t}(),Ms=function(t,e,i){return k(t)?90*t:9e4*e+(i?9e4*i.baseTime/i.timescale:0)},Fs=null,Ns=[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],Us=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Bs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Gs=[0,1,1,4];function $s(t,e,i,r,s){if(!(i+24>e.length)){var n=Ks(e,i);if(n&&i+n.frameLength<=e.length){var a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+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 Ks(t,e){var i=t[e+1]>>3&3,r=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){var a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Ns[14*(3===i?3-r:3===r?3:4)+s-1],h=Us[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,u=Bs[i][r],c=Gs[r],f=8*u*c,g=Math.floor(u*l/h+a)*c;if(null===Fs){var m=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fs=m?parseInt(m[1]):0}return!!Fs&&Fs<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function Vs(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Hs(t,e){return e+1<t.length&&Vs(t,e)}function Ys(t,e){var i=4;return Vs(t,e)&&i<=t.length-e}function Ws(t,e){if(e+1<t.length&&Vs(t,e)){var i=4,r=Ks(t,e),s=i;null!=r&&r.frameLength&&(s=r.frameLength);var n=e+s;return n===t.length||Hs(t,n)}return!1}var js=function(t){function e(e,i){var r;return(r=t.call(this)||this).observer=void 0,r.config=void 0,r.observer=e,r.config=i,r}l(e,t);var i=e.prototype;return i.resetInitSegment=function(e,i,r,s){t.prototype.resetInitSegment.call(this,e,i,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},e.probe=function(t,e){if(!t)return!1;var i=es(t,0),r=(null==i?void 0:i.length)||0;if(Ws(t,r))return!1;for(var s=t.length;r<s;r++)if(hs(t,r))return e.log("ADTS sync word found !"),!0;return!1},i.canParse=function(t,e){return ls(t,e)},i.appendFrame=function(t,e,i){ds(t,this.observer,e,i,t.manifestCodec);var r=fs(t,e,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r},e}(xs),qs=function(t,e){var i=0,r=5;e+=r;for(var s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);r>0;){a[0]=t[e];var o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],e+=1,r-=o}return i},Xs=function(t){function e(e){var i;return(i=t.call(this)||this).observer=void 0,i.observer=e,i}l(e,t);var i=e.prototype;return i.resetInitSegment=function(e,i,r,s){t.prototype.resetInitSegment.call(this,e,i,r,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},i.canParse=function(t,e){return e+64<t.length},i.appendFrame=function(t,e,i){var r=Qs(t,e,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:t.samples[t.samples.length-1],length:r,missing:0}},e.probe=function(t){if(!t)return!1;var e=es(t,0);if(!e)return!1;var i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==Cs(e)&&qs(t,i)<16},e}(xs);function Qs(t,e,i,r,s){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;var n=e[i+4]>>6;if(n>=3)return-1;var a=[48e3,44100,32e3][n],o=63&e[i+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(i+l>e.length)return-1;var h=e[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));var u=(e[i+6]<<8|e[i+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][h]+u,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=c,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}var zs=function(t){function e(){return t.apply(this,arguments)||this}l(e,t);var i=e.prototype;return i.resetInitSegment=function(e,i,r,s){t.prototype.resetInitSegment.call(this,e,i,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},e.probe=function(t){if(!t)return!1;var e=es(t,0),i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==Cs(e)&&qs(t,i)<=16)return!1;for(var r=t.length;i<r;i++)if(Ws(t,i))return Y.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(t,e){return Ys(t,e)},i.appendFrame=function(t,e,i){if(null!==this.basePTS)return $s(t,e,i,this.basePTS,this.frameIndex)},e}(xs),Zs=/\/emsg[-/]ID3/i,Js=function(){function t(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}var e=t.prototype;return e.resetTimeStamp=function(){},e.resetInitSegment=function(t,e,i,r){var s=this.videoTrack=Os("video",1),n=this.audioTrack=Os("audio",1),a=this.txtTrack=Os("text",1);if(this.id3Track=Os("id3",1),this.timeOffset=0,null!=t&&t.byteLength){var o=vt(t);if(o.video){var l=o.video,h=l.id,d=l.timescale,u=l.codec,c=l.supplemental;s.id=h,s.timescale=a.timescale=d,s.codec=u,s.supplemental=c}if(o.audio){var f=o.audio,g=f.id,m=f.timescale,p=f.codec;n.id=g,n.timescale=m,n.codec=p}a.id=lt.text,s.sampleDuration=0,s.duration=n.duration=r}},e.resetContiguity=function(){this.remainderData=null},t.probe=function(t){return gt(t)},e.demux=function(t,e){this.timeOffset=e;var i=t,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Dt(this.remainderData,t));var n=kt(i);this.remainderData=n.remainder,r.samples=n.valid||new Uint8Array}else r.samples=i;var a=this.extractID3Track(r,e);return s.samples=_t(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},e.flush=function(){var t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(e,this.timeOffset);return i.samples=_t(t,e),{videoTrack:e,audioTrack:Os(),id3Track:r,textTrack:Os()}},e.extractID3Track=function(t,e){var i=this,r=this.id3Track;if(t.samples.length){var s=mt(t.samples,["emsg"]);s&&s.forEach((function(t){var s=xt(t);if(Zs.test(s.schemeIdUri)){var n=tn(s,e),a=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=s.payload;r.samples.push({data:o,len:o.byteLength,dts:n,pts:n,type:ws.emsg,duration:a})}else if(i.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=tn(s,e);r.samples.push({data:s.payload,len:s.payload.byteLength,dts:l,pts:l,type:ws.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return r},e.demuxSampleAes=function(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},t}();function tn(t,e){return k(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}var en=function(){function t(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new fi(e,{removePKCS7Padding:!1})}var e=t.prototype;return e.decryptBuffer=function(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,ai.cbc)},e.decryptAacSample=function(t,e,i){var r=this,s=t[e].unit;if(!(s.length<=16)){var n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then((function(n){var a=new Uint8Array(n);s.set(a,16),r.decrypter.isSync()||r.decryptAacSamples(t,e+1,i)}))}},e.decryptAacSamples=function(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32||(this.decryptAacSample(t,e,i),this.decrypter.isSync())))return}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e),r=0,s=32;s<t.length-16;s+=160,r+=16)i.set(t.subarray(s,s+16),r);return i},e.getAvcDecryptedUnit=function(t,e){for(var i=new Uint8Array(e),r=0,s=32;s<t.length-16;s+=160,r+=16)t.set(i.subarray(r,r+16),s);return t},e.decryptAvcSample=function(t,e,i,r,s){var n=this,a=Ot(s.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then((function(o){s.data=n.getAvcDecryptedUnit(a,o),n.decrypter.isSync()||n.decryptAvcSamples(t,e,i+1,r)}))},e.decryptAvcSamples=function(t,e,i,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void r();for(var s=t[e].units;!(i>=s.length);i++){var n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,r,n),this.decrypter.isSync())))return}}},t}(),rn=function(){function t(){this.VideoSample=null}var e=t.prototype;return e.createVideoSample=function(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}},e.getLastNalUnit=function(t){var e,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){var s=r.units;i=s[s.length-1]}return i},e.pushAccessUnit=function(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var i=e.samples,r=i.length;if(!r)return void e.dropped++;var s=i[r-1];t.pts=s.pts,t.dts=s.dts}e.samples.push(t)}},e.parseNALu=function(t,e,i){var r,s,n=e.byteLength,a=t.naluState||0,o=a,l=[],h=0,d=-1,u=0;for(-1===a&&(d=0,u=this.getNALuType(e,0),a=0,h=1);h<n;)if(r=e[h++],a)if(1!==a)if(r)if(1===r){if(s=h-a-1,d>=0){var c={data:e.subarray(d,s),type:u};l.push(c)}else{var f=this.getLastNalUnit(t.samples);f&&(o&&h<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),s>0&&(f.data=Dt(f.data,e.subarray(0,s)),f.state=0))}h<n?(d=h,u=this.getNALuType(e,h),a=0):a=-1}else a=0;else a=3;else a=r?0:2;else a=r?0:1;if(d>=0&&a>=0){var g={data:e.subarray(d,n),type:u,state:a};l.push(g)}if(0===l.length){var m=this.getLastNalUnit(t.samples);m&&(m.data=Dt(m.data,e))}return t.naluState=a,l},t}(),sn=function(){function t(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}var e=t.prototype;return e.loadWord=function(){var t=this.data,e=this.bytesAvailable,i=t.byteLength-e,r=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");r.set(t.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s},e.skipBits=function(t){var e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),i=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)>0&&this.bitsAvailable?i<<e|this.readBits(e):i},e.skipLZ=function(){var 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()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},t}(),nn=function(t){function e(){return t.apply(this,arguments)||this}l(e,t);var i=e.prototype;return i.parsePES=function(t,e,i,r){var s,n=this,a=this.parseNALu(t,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&a.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,h;switch(r.type){case 1:var d=!1;s=!0;var u,c=r.data;if(l&&c.length>4){var f=n.readSliceType(c);2!==f&&4!==f&&7!==f&&9!==f||(d=!0)}d&&null!=(u=o)&&u.frame&&!o.key&&(n.pushAccessUnit(o,t),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=d;break;case 5:s=!0,null!=(a=o)&&a.frame&&!o.key&&(n.pushAccessUnit(o,t),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:s=!0,wt(r.data,1,i.pts,e.samples);break;case 7:var g,m;s=!0,l=!0;var p=r.data,v=n.readSPS(p);if(!t.sps||t.width!==v.width||t.height!==v.height||(null==(g=t.pixelRatio)?void 0:g[0])!==v.pixelRatio[0]||(null==(m=t.pixelRatio)?void 0:m[1])!==v.pixelRatio[1]){t.width=v.width,t.height=v.height,t.pixelRatio=v.pixelRatio,t.sps=[p];for(var y=p.subarray(1,4),E="avc1.",T=0;T<3;T++){var S=y[T].toString(16);S.length<2&&(S="0"+S),E+=S}t.codec=E}break;case 8:s=!0,t.pps=[r.data];break;case 9:s=!0,t.audFound=!0,null!=(h=o)&&h.frame&&(n.pushAccessUnit(o,t),o=null),o||(o=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts));break;case 12:s=!0;break;default:s=!1}o&&s&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)},i.getNALuType=function(t,e){return 31&t[e]},i.readSliceType=function(t){var e=new sn(t);return e.readUByte(),e.readUEG(),e.readUEG()},i.skipScalingList=function(t,e){for(var i=8,r=8,s=0;s<t;s++)0!==r&&(r=(i+e.readEG()+256)%256),i=0===r?i:r},i.readSPS=function(t){var e,i,r,s=new sn(t),n=0,a=0,o=0,l=0,h=s.readUByte.bind(s),d=s.readBits.bind(s),u=s.readUEG.bind(s),c=s.readBoolean.bind(s),f=s.skipBits.bind(s),g=s.skipEG.bind(s),m=s.skipUEG.bind(s),p=this.skipScalingList.bind(this);h();var v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){var y=u();if(3===y&&f(1),m(),m(),f(1),c())for(i=3!==y?8:12,r=0;r<i;r++)c()&&p(r<6?16:64,s)}m();var E=u();if(0===E)u();else if(1===E)for(f(1),g(),g(),e=u(),r=0;r<e;r++)g();m(),f(1);var T=u(),S=u(),A=d(1);0===A&&f(1),f(1),c()&&(n=u(),a=u(),o=u(),l=u());var L=[1,1];if(c()&&c())switch(h()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(T+1)-2*n-2*a),height:(2-A)*(S+1)*16-(A?2:4)*(o+l),pixelRatio:L}},e}(rn),an=function(t){function e(){for(var e,i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return(e=t.call.apply(t,[this].concat(r))||this).initVPS=null,e}l(e,t);var i=e.prototype;return i.parsePES=function(t,e,i,r){var s,n=this,o=this.parseNALu(t,i.data,r),l=this.VideoSample,h=!1;i.data=null,l&&o.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach((function(r){var o,d;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts)),l.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:var u;s=!0,h&&null!=(u=l)&&u.frame&&!l.key&&(n.pushAccessUnit(l,t),l=n.VideoSample=null),l||(l=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:s=!0,null!=(o=l)&&o.frame&&!l.key&&(n.pushAccessUnit(l,t),l=n.VideoSample=null),l||(l=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 39:s=!0,wt(r.data,2,i.pts,e.samples);break;case 32:s=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=a(t.params,n.readVPS(r.data)),n.initVPS=r.data),t.vps=[r.data];break;case 33:if(s=!0,h=!0,void 0===t.vps||t.vps[0]===n.initVPS||void 0===t.sps||n.matchSPS(t.sps[0],r.data)||(n.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){var c=n.readSPS(r.data);for(var f in t.width=c.width,t.height=c.height,t.pixelRatio=c.pixelRatio,t.codec=c.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={}),c.params)t.params[f]=c.params[f]}n.pushParameterSet(t.sps,r.data,t.vps),l||(l=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),l.key=!0;break;case 34:if(s=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];var g=n.readPPS(r.data);for(var m in g)t.params[m]=g[m]}n.pushParameterSet(t.pps,r.data,t.vps)}break;case 35:s=!0,t.audFound=!0,null!=(d=l)&&d.frame&&(n.pushAccessUnit(l,t),l=null),l||(l=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts));break;default:s=!1}l&&s&&l.units.push(r)})),r&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)},i.pushParameterSet=function(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)},i.getNALuType=function(t,e){return(126&t[e])>>>1},i.ebsp2rbsp=function(t){for(var e=new Uint8Array(t.byteLength),i=0,r=0;r<t.byteLength;r++)r>=2&&3===t[r]&&0===t[r-1]&&0===t[r-2]||(e[i]=t[r],i++);return new Uint8Array(e.buffer,0,i)},i.pushAccessUnit=function(e,i){t.prototype.pushAccessUnit.call(this,e,i),this.initVPS&&(this.initVPS=null)},i.readVPS=function(t){var e=new sn(t);return e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6),{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}},i.readSPS=function(t){var e=new sn(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);var i=e.readBits(3);e.readBoolean();for(var r=e.readBits(2),s=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),d=e.readUByte(),u=e.readUByte(),c=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[],E=0;E<i;E++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(var T=i;T<8;T++)e.readBits(2);for(var S=0;S<i;S++)v[S]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[S]&&e.readUByte();e.readUEG();var A=e.readUEG();3==A&&e.skipBits(1);var L=e.readUEG(),R=e.readUEG(),I=e.readBoolean(),b=0,k=0,D=0,_=0;I&&(b+=e.readUEG(),k+=e.readUEG(),D+=e.readUEG(),_+=e.readUEG());for(var P=e.readUEG(),C=e.readUEG(),w=e.readUEG(),O=e.readBoolean()?0:i;O<=i;O++)e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.readBoolean()&&e.readBoolean())for(var x=0;x<4;x++)for(var M=0;M<(3===x?2:6);M++)if(e.readBoolean()){var F=Math.min(64,1<<4+(x<<1));x>1&&e.readEG();for(var N=0;N<F;N++)e.readEG()}else e.readUEG();e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());for(var U=e.readUEG(),B=0,G=0;G<U;G++){var $=!1;if(0!==G&&($=e.readBoolean()),$){G===U&&e.readUEG(),e.readBoolean(),e.readUEG();for(var K=0,V=0;V<=B;V++){var H=e.readBoolean(),Y=!1;H||(Y=e.readBoolean()),(H||Y)&&K++}B=K}else{var W=e.readUEG(),j=e.readUEG();B=W+j;for(var q=0;q<W;q++)e.readUEG(),e.readBoolean();for(var X=0;X<j;X++)e.readUEG(),e.readBoolean()}}if(e.readBoolean())for(var Q=e.readUEG(),z=0;z<Q;z++){for(var Z=0;Z<w+4;Z++)e.readBits(1);e.readBits(1)}var J=0,tt=1,et=1,it=!0,rt=1,st=0;if(e.readBoolean(),e.readBoolean(),e.readBoolean()){if(e.readBoolean()){var nt=e.readUByte();nt>0&&nt<16?(tt=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][nt-1],et=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][nt-1]):255===nt&&(tt=e.readBits(16),et=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(),e.readBoolean()&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG()),e.readBoolean()&&(rt=e.readBits(32),st=e.readBits(32),e.readBoolean()&&e.readUEG(),e.readBoolean())){var at=e.readBoolean(),ot=e.readBoolean(),lt=!1;(at||ot)&&((lt=e.readBoolean())&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),lt&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(var ht=0;ht<=i;ht++){var dt=!1;(it=e.readBoolean())||e.readBoolean()?e.readEG():dt=e.readBoolean();var ut=dt?1:e.readUEG()+1;if(at)for(var ct=0;ct<ut;ct++)e.readUEG(),e.readUEG(),lt&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(ot)for(var ft=0;ft<ut;ft++)e.readUEG(),e.readUEG(),lt&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),J=e.readUEG())}var gt=L,mt=R;if(I){var pt=1,vt=1;1===A?pt=vt=2:2==A&&(pt=2),gt=L-pt*k-pt*b,mt=R-vt*_-vt*D}for(var yt=r?["A","B","C"][r]:"",Et=a<<24|o<<16|l<<8|h,Tt=0,St=0;St<32;St++)Tt=(Tt|(Et>>St&1)<<31-St)>>>0;var At=Tt.toString(16);return 1===n&&"2"===At&&(At="6"),{codecString:"hvc1."+yt+n+"."+At+"."+(s?"H":"L")+p+".B0",params:{general_tier_flag:s,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,u,c,f,g,m],general_level_idc:p,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:C,min_spatial_segmentation_idc:J,chroma_format_idc:A,frame_rate:{fixed:it,fps:st/rt}},width:gt,height:mt,pixelRatio:[tt,et]}},i.readPPS=function(t){var e=new sn(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);var i=e.readBoolean(),r=e.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}},i.matchSPS=function(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)},e}(rn),on=188,ln=function(){function t(t,e,i,r){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=i,this.logger=r,this.videoParser=null}t.probe=function(e,i){var r=t.syncOffset(e);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},t.syncOffset=function(t){for(var e=t.length,i=Math.min(5*on,e-on)+1,r=0;r<i;){for(var s=!1,n=-1,a=0,o=r;o<e;o+=on){if(71!==t[o]||e-o!==on&&71!==t[o+on]){if(a)return-1;break}if(a++,-1===n&&0!==(n=o)&&(i=Math.min(n+99*on,t.length-on)+1),s||(s=0===hn(t,o)),s&&a>1&&(0===n&&a>2||o+on>i))return n}r++}return-1},t.createTrack=function(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:lt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}};var e=t.prototype;return e.resetInitSegment=function(e,i,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=t.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=t.createTrack("audio",s),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=i,this.videoCodec=r},e.resetTimeStamp=function(){},e.resetContiguity=function(){var t=this._audioTrack,e=this._videoTrack,i=this._id3Track;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null},e.demux=function(e,i,r,s){var n;void 0===r&&(r=!1),void 0===s&&(s=!1),r||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,d=a.pid,u=a.pesData,c=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=Dt(this.remainderData,e)).length,this.remainderData=null),E<on&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var T=Math.max(0,t.syncOffset(e));(E-=(E-T)%on)<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));for(var S=0,A=T;A<E;A+=on)if(71===e[A]){var L=!!(64&e[A+1]),R=hn(e,A),I=void 0;if((48&e[A+3])>>4>1){if((I=A+5+e[A+4])===A+on)continue}else I=A+4;switch(R){case d:L&&(u&&(n=gn(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,h,n,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(I,A+on)),u.size+=A+on-I);break;case c:if(L){if(g&&(n=gn(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(I,A+on)),g.size+=A+on-I);break;case f:L&&(m&&(n=gn(m,this.logger))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(e.subarray(I,A+on)),m.size+=A+on-I);break;case 0:L&&(I+=e[I]+1),y=this._pmtId=dn(e,I);break;case y:L&&(I+=e[I]+1);var b=un(e,I,this.typeSupported,r,this.observer,this.logger);(d=b.videoPid)>0&&(a.pid=d,a.segmentCodec=b.segmentVideoCodec),(c=b.audioPid)>0&&(o.pid=c,o.segmentCodec=b.segmentAudioCodec),(f=b.id3Pid)>0&&(l.pid=f),null===p||v||(this.logger.warn("MPEG-TS PMT found at "+A+" after unknown PID '"+p+"'. Backtracking to sync byte @"+T+" to parse all TS packets."),p=null,A=T-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=R}}else S++;S>0&&cn(this.observer,new Error("Found "+S+" TS packet/s that do not start with 0x47"),void 0,this.logger),a.pesData=u,o.pesData=g,l.pesData=m;var k={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(k),k},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,i=t.audioTrack,r=t.videoTrack,s=t.id3Track,n=t.textTrack,a=r.pesData,o=i.pesData,l=s.pesData;if(a&&(e=gn(a,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,n,e,!0),r.pesData=null)):r.pesData=a,o&&(e=gn(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,e);break;case"mp3":this.parseMPEGPES(i,e);break;case"ac3":this.parseAC3PES(i,e)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(e=gn(l,this.logger))?(this.parseID3PES(s,e),s.pesData=null):s.pesData=l},e.demuxSampleAes=function(t,e,i){var r=this.demux(t,i,!0,!this.config.progressive),s=this.sampleAes=new en(this.observer,this.config,e);return this.decrypt(r,s)},e.readyVideoParser=function(t){null===this.videoParser&&("avc"===t?this.videoParser=new nn:"hevc"===t&&(this.videoParser=new an))},e.decrypt=function(t,e){return new Promise((function(i){var r=t.audioTrack,s=t.videoTrack;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,(function(){s.samples?e.decryptAvcSamples(s.samples,0,0,(function(){i(t)})):i(t)})):s.samples&&e.decryptAvcSamples(s.samples,0,0,(function(){i(t)}))}))},e.destroy=function(){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},e.parseAACPES=function(t,e){var i,r,s,n=0,a=this.aacOverFlow,o=e.data;if(a){this.aacOverFlow=null;var l=a.missing,h=a.sample.unit.byteLength;if(-1===l)o=Dt(a.sample.unit,o);else{var d=h-l;a.sample.unit.set(o.subarray(0,l),d),t.samples.push(a.sample),n=a.missing}}for(i=n,r=o.length;i<r-1&&!os(o,i);i++);if(i!==n){var u,c=i<r-1;if(u=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",cn(this.observer,new Error(u),c,this.logger),!c)return}if(ds(t,this.observer,o,i,this.audioCodec),void 0!==e.pts)s=e.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=us(t.samplerate);s=a.sample.pts+f}for(var g,m=0;i<r;){if(i+=(g=fs(t,o,i,s,m)).length,g.missing){this.aacOverFlow=g;break}for(m++;i<r-1&&!os(o,i);i++);}},e.parseMPEGPES=function(t,e){var i=e.data,r=i.length,s=0,n=0,a=e.pts;if(void 0!==a)for(;n<r;)if(Hs(i,n)){var o=$s(t,i,n,a,s);if(!o)break;n+=o.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},e.parseAC3PES=function(t,e){var i=e.data,r=e.pts;if(void 0!==r)for(var s,n=i.length,a=0,o=0;o<n&&(s=Qs(t,i,o,r,a++))>0;)o+=s;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},e.parseID3PES=function(t,e){if(void 0!==e.pts){var i=a({},e,{type:this._videoTrack?ws.emsg:ws.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},t}();function hn(t,e){return((31&t[e+1])<<8)+t[e+2]}function dn(t,e){return(31&t[e+10])<<8|t[e+11]}function un(t,e,i,r,s,n){var 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;){var l=hn(t,e),h=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){fn("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=l);break;case 21:-1===a.id3Pid&&(a.id3Pid=l);break;case 219:if(!r){fn("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){fn("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&h>0)for(var d=e+5,u=h;u>2;){106===t[d]&&(!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=l,a.segmentAudioCodec="ac3"));var c=t[d+1]+2;d+=c,u-=c}break;case 194:case 135:return cn(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=l,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=h+5}return a}function cn(t,e,i,r){r.warn("parsing error: "+e.message),t.emit(w.ERROR,w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function fn(t,e){e.log(t+" with AES-128-CBC encryption found in unencrypted stream")}function gn(t,e){var i,r,s,n,a,o=0,l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Dt(l[0],l[1]),l.splice(1,1);if(1===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>t.size-6)return null;var h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?n-(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2)>54e5&&(e.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var d=(s=i[8])+9;if(t.size<=d)return null;t.size-=d;for(var u=new Uint8Array(t.size),c=0,f=l.length;c<f;c++){var g=(i=l[c]).byteLength;if(d){if(d>g){d-=g;continue}i=i.subarray(d),g-=d,d=0}u.set(i,o),o+=g}return r&&(r-=s+3),{data:u,pts:n,dts:a,len:r}}return null}var mn=function(){function t(){}return t.getSilentFrame=function(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])}},t}(),pn=Math.pow(2,32)-1,vn=function(){function t(){}return t.init=function(){var 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)]);var i=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=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]);t.HDLR_TYPES={video:i,audio:r};var s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);t.STTS=t.STSC=t.STCO=n,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]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);t.FTYP=t.box(t.types.ftyp,a,l,a,o),t.DINF=t.box(t.types.dinf,t.box(t.types.dref,s))},t.box=function(t){for(var e=8,i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];for(var n=r.length,a=n;n--;)e+=r[n].byteLength;var o=new Uint8Array(e);for(o[0]=e>>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),n=0,e=8;n<a;n++)o.set(r[n],e),e+=r[n].byteLength;return o},t.hdlr=function(e){return t.box(t.types.hdlr,t.HDLR_TYPES[e])},t.mdat=function(e){return t.box(t.types.mdat,e)},t.mdhd=function(e,i){i*=e;var r=Math.floor(i/(pn+1)),s=Math.floor(i%(pn+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,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale||0,e.duration||0),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(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))},t.moof=function(e,i,r){return t.box(t.types.moof,t.mfhd(e),t.traf(r,i))},t.moov=function(e){for(var i=e.length,r=[];i--;)r[i]=t.trak(e[i]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(t.mvex(e)))},t.mvex=function(e){for(var i=e.length,r=[];i--;)r[i]=t.trex(e[i]);return t.box.apply(null,[t.types.mvex].concat(r))},t.mvhd=function(e,i){i*=e;var r=Math.floor(i/(pn+1)),s=Math.floor(i%(pn+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,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,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)},t.sdtp=function(e){var i,r,s=e.samples||[],n=new Uint8Array(4+s.length);for(i=0;i<s.length;i++)r=s[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return t.box(t.types.sdtp,n)},t.stbl=function(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))},t.avc1=function(e){var i,r,s,n=[],a=[];for(i=0;i<e.sps.length;i++)s=(r=e.sps[i]).byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)s=(r=e.pps[i]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(r));var 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,h=e.height,d=e.pixelRatio[0],u=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,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]),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([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))},t.esds=function(t){var 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].concat(e,[6,1,2]))},t.audioStsd=function(t){var 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])},t.mp4a=function(e){return t.box(t.types.mp4a,t.audioStsd(e),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){return t.box(t.types[".mp3"],t.audioStsd(e))},t.ac3=function(e){return t.box(t.types["ac-3"],t.audioStsd(e),t.box(t.types.dac3,e.config))},t.stsd=function(e){var i=e.segmentCodec;if("audio"===e.type){if("aac"===i)return t.box(t.types.stsd,t.STSD,t.mp4a(e));if("ac3"===i&&e.config)return t.box(t.types.stsd,t.STSD,t.ac3(e));if("mp3"===i&&"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"===i)return t.box(t.types.stsd,t.STSD,t.avc1(e));if("hevc"===i&&e.vps)return t.box(t.types.stsd,t.STSD,t.hvc1(e))}throw new Error("unsupported "+e.type+" segment codec ("+i+"/"+e.codec+")")},t.tkhd=function(e){var i=e.id,r=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,a=Math.floor(r/(pn+1)),o=Math.floor(r%(pn+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,i>>24&255,i>>16&255,i>>8&255,255&i,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,s>>8&255,255&s,0,0,n>>8&255,255&n,0,0]))},t.traf=function(e,i){var r=t.sdtp(e),s=e.id,n=Math.floor(i/(pn+1)),a=Math.floor(i%(pn+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),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,r.length+16+20+8+16+8+8),r)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var i=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,i){var r,s,n,a,o,l,h=e.samples||[],d=h.length,u=12+16*d,c=new Uint8Array(u);for(i+=8+u,c.set(["video"===e.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<d;r++)n=(s=h[r]).duration,a=s.size,o=s.flags,l=s.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var i=t.moov(e);return Dt(t.FTYP,i)},t.hvc1=function(e){for(var i=e.params,r=[e.vps,e.sps,e.pps],s=4,n=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),s-1|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),a=n.length,o=0;o<r.length;o+=1){a+=3;for(var l=0;l<r[o].length;l+=1)a+=2+r[o][l].length}var h=new Uint8Array(a);h.set(n,0),a=n.length;for(var d=r.length-1,u=0;u<r.length;u+=1){h.set(new Uint8Array([32+u|(u===d?128:0),0,r[u].length]),a),a+=3;for(var c=0;c<r[u].length;c+=1)h.set(new Uint8Array([r[u][c].length>>8,255&r[u][c].length]),a),a+=2,h.set(r[u][c],a),a+=r[u][c].length}var f=t.box(t.types.hvcC,h),g=e.width,m=e.height,p=e.pixelRatio[0],v=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,g>>8&255,255&g,m>>8&255,255&m,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]),f,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([p>>24,p>>16&255,p>>8&255,255&p,v>>24,v>>16&255,v>>8&255,255&v])))},t}();vn.types=void 0,vn.HDLR_TYPES=void 0,vn.STTS=void 0,vn.STSC=void 0,vn.STCO=void 0,vn.STSZ=void 0,vn.VMHD=void 0,vn.SMHD=void 0,vn.STSD=void 0,vn.FTYP=void 0,vn.DINF=void 0;var yn=9e4;function En(t,e,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var s=t*e*i;return r?Math.round(s):s}function Tn(t,e,i,r){return void 0===i&&(i=1),void 0===r&&(r=!1),En(t,e,1/i,r)}function Sn(t,e){return En(t,1e3,1/yn,e)}function An(t,e){return void 0===e&&(e=1),En(t,yn,1/e)}var Ln=1e4,Rn=1024,In=1152,bn=1536,kn=null,Dn=null;function _n(t,e,i,r){return{duration:e,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}var Pn=function(t){function e(e,i,r,s){var n;if((n=t.call(this,"mp4-remuxer",s)||this).observer=void 0,n.config=void 0,n.typeSupported=void 0,n.ISGenerated=!1,n._initPTS=null,n._initDTS=null,n.nextVideoTs=null,n.nextAudioTs=null,n.videoSampleDuration=null,n.isAudioContiguous=!1,n.isVideoContiguous=!1,n.videoTrackConfig=void 0,n.observer=e,n.config=i,n.typeSupported=r,n.ISGenerated=!1,null===kn){var a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);kn=a?parseInt(a[1]):0}if(null===Dn){var o=navigator.userAgent.match(/Safari\/(\d+)/i);Dn=o?parseInt(o[1]):0}return n}l(e,t);var i=e.prototype;return i.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},i.resetTimeStamp=function(t){this.log("initPTS & initDTS reset"),this._initPTS=this._initDTS=t},i.resetNextTimestamp=function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},i.resetInitSegment=function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},i.getVideoStartPts=function(t){var e=!1,i=t[0].pts,r=t.reduce((function(t,r){var s=r.pts,n=s-t;return n<-4294967296&&(e=!0,n=(s=Cn(s,i))-t),n>0?t:s}),i);return e&&this.debug("PTS rollover detected"),r},i.remux=function(t,e,i,r,s,n,a,o){var l,h,d,u,c,f,g=s,m=s,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,R,I=this.videoTrackConfig;(I&&(e.width!==I.width||e.height!==I.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(A=I.pixelRatio)?void 0:A[0])||(null==(L=e.pixelRatio)?void 0:L[1])!==(null==(R=I.pixelRatio)?void 0:R[1]))||!I&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(t,e,s,n));var b,k=this.isVideoContiguous,D=-1;if(T&&(D=wn(e.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,D>0){this.warn("Dropped "+D+" out of "+y+" video samples due to a missing keyframe");var _=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(D),e.dropped+=D,b=m+=(e.samples[0].pts-_)/e.inputTimeScale}else-1===D&&(this.warn("No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&T){var P=this.getVideoStartPts(e.samples),C=(Cn(t.samples[0].pts,P)-P)/e.inputTimeScale;g+=Math.max(0,C),m+=Math.max(0,-C)}if(E){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(t,e,s,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===x.AUDIO?m:void 0),T){var w=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(t,e,s,n)),l=this.remuxVideo(e,m,k,w)}}else T&&(l=this.remuxVideo(e,m,k,0));l&&(l.firstKeyFrame=D,l.independent=-1!==D,l.firstKeyFramePTS=b)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=On(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=xn(r,s,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:u,id3:c}},i.generateIS=function(t,e,i,r){var s,n,a,o=t.samples,l=e.samples,h=this.typeSupported,d={},u=this._initPTS,c=!u||r,f="audio/mp4",g=-1;if(c&&(s=n=1/0),t.config&&o.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}d.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):vn.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(g=t.id,a=t.inputTimeScale,u&&a===u.timescale?c=!1:s=n=o[0].pts-Math.round(a*i))}if(e.sps&&e.pps&&l.length){if(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:vn.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(g=e.id,a=e.inputTimeScale,u&&a===u.timescale)c=!1;else{var m=this.getVideoStartPts(l),p=Math.round(a*i);n=Math.min(n,Cn(l[0].dts,m)-p),s=Math.min(s,m-p)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,c?(u&&this.warn("Timestamps at playlist time: "+(r?"":"~")+i+" "+s/a+" != initPTS: "+u.baseTime/u.timescale+" ("+u.baseTime+"/"+u.timescale+") trackId: "+u.trackId),this.log("Found initPTS at playlist time: "+i+" offset: "+s/a+" ("+s+"/"+a+") trackId: "+g),this._initPTS={baseTime:s,timescale:a,trackId:g},this._initDTS={baseTime:n,timescale:a,trackId:g}):s=a=void 0,{tracks:d,initPTS:s,timescale:a,trackId:g}},i.remuxVideo=function(t,e,i,r){var s,n,o=t.inputTimeScale,l=t.samples,h=[],d=l.length,u=this._initPTS,c=u.baseTime*o/u.timescale,f=this.nextVideoTs,g=8,m=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!i||null===f){var E=c+e*o,T=l[0].pts-Cn(l[0].dts,l[0].pts);kn&&null!==f&&Math.abs(E-T-(f+c))<15e3?i=!0:f=E-T-c}for(var S=f+c,A=0;A<d;A++){var L=l[A];L.pts=Cn(L.pts,S),L.dts=Cn(L.dts,S),L.dts<l[A>0?A-1:A].dts&&(y=!0)}y&&l.sort((function(t,e){var i=t.dts-e.dts,r=t.pts-e.pts;return i||r})),s=l[0].dts;var R=(n=l[l.length-1].dts)-s,I=R?Math.round(R/(d-1)):m||t.inputTimeScale/30;if(i){var b=s-S,k=b>I,D=b<-1;if((k||D)&&(k?this.warn((t.segmentCodec||"").toUpperCase()+": "+Sn(b,!0)+" ms ("+b+"dts) hole between fragments detected at "+e.toFixed(3)):this.warn((t.segmentCodec||"").toUpperCase()+": "+Sn(-b,!0)+" ms ("+b+"dts) overlapping between fragments detected at "+e.toFixed(3)),!D||S>=l[0].pts||kn)){s=S;var _=l[0].pts-b;if(k)l[0].dts=s,l[0].pts=_;else for(var O=!0,x=0;x<l.length&&!(l[x].dts>_&&O);x++){var M=l[x].pts;if(l[x].dts-=b,l[x].pts-=b,x<l.length-1){var F=l[x+1].pts;O=F<=l[x].pts==F<=M}}this.log("Video: Initial PTS/DTS adjusted: "+Sn(_,!0)+"/"+Sn(s,!0)+", delta: "+Sn(b,!0)+" ms")}}for(var N=0,U=0,B=s=Math.max(0,s),G=0;G<d;G++){for(var $=l[G],K=$.units,V=K.length,H=0,Y=0;Y<V;Y++)H+=K[Y].data.length;U+=H,N+=V,$.length=H,$.dts<B?($.dts=B,B+=I/4|0||1):B=$.dts,p=Math.min($.pts,p),v=Math.max($.pts,v)}n=l[d-1].dts;var W,j=U+4*N+8;try{W=new Uint8Array(j)}catch(t){return void this.observer.emit(w.ERROR,w.ERROR,{type:P.MUX_ERROR,details:C.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:j,reason:"fail allocating video mdat "+j})}var q=new DataView(W.buffer);q.setUint32(0,j),W.set(vn.types.mdat,4);for(var X=!1,Q=Number.POSITIVE_INFINITY,z=Number.POSITIVE_INFINITY,Z=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY,tt=0;tt<d;tt++){for(var et=l[tt],it=et.units,rt=0,st=0,nt=it.length;st<nt;st++){var at=it[st],ot=at.data,lt=at.data.byteLength;q.setUint32(g,lt),g+=4,W.set(ot,g),g+=lt,rt+=4+lt}var ht=void 0;if(tt<d-1)m=l[tt+1].dts-et.dts,ht=l[tt+1].pts-et.pts;else{var dt=this.config,ut=tt>0?et.dts-l[tt-1].dts:I;if(ht=tt>0?et.pts-l[tt-1].pts:I,dt.stretchShortVideoTrack&&null!==this.nextAudioTs){var ct=Math.floor(dt.maxBufferHole*o),ft=(r?p+r*o:this.nextAudioTs+c)-et.pts;ft>ct?((m=ft-ut)<0?m=ut:X=!0,this.log("It is approximately "+ft/90+" ms to the next segment; using duration "+m/90+" ms for the last video frame.")):m=ut}else m=ut}var gt=Math.round(et.pts-et.dts);Q=Math.min(Q,m),Z=Math.max(Z,m),z=Math.min(z,ht),J=Math.max(J,ht),h.push(_n(et.key,m,rt,gt))}if(h.length)if(kn){if(kn<70){var mt=h[0].flags;mt.dependsOn=2,mt.isNonSync=0}}else if(Dn&&J-z<Z-Q&&I/Z<.025&&0===h[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var pt=s,vt=0,yt=h.length;vt<yt;vt++){var Et=pt+h[vt].duration,Tt=pt+h[vt].cts;if(vt<yt-1){var St=Et+h[vt+1].cts;h[vt].duration=St-Tt}else h[vt].duration=vt?h[vt-1].duration:I;h[vt].cts=0,pt=Et}}var At=n+(m=X||!m?I:m);this.nextVideoTs=f=At-c,this.videoSampleDuration=m,this.isVideoContiguous=!0;var Lt={data1:vn.moof(t.sequenceNumber++,s,a(t,{samples:h})),data2:W,startPTS:(p-c)/o,endPTS:(v+m-c)/o,startDTS:(s-c)/o,endDTS:f/o,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:t.dropped};return t.samples=[],t.dropped=0,Lt},i.getSamplesPerFrame=function(t){switch(t.segmentCodec){case"mp3":return In;case"ac3":return bn;default:return Rn}},i.remuxAudio=function(t,e,i,r,s){var n=t.inputTimeScale,o=n/(t.samplerate?t.samplerate:n),l=this.getSamplesPerFrame(t),h=l*o,d=this._initPTS,u="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],f=void 0!==s,g=t.samples,m=u?0:8,p=this.nextAudioTs||-1,v=d.baseTime*n/d.timescale,y=v+e*n;if(this.isAudioContiguous=i=i||g.length&&p>0&&(r&&Math.abs(y-(p+v))<9e3||Math.abs(Cn(g[0].pts,y)-(p+v))<20*h),g.forEach((function(t){t.pts=Cn(t.pts,y)})),!i||p<0){if(g=g.filter((function(t){return t.pts>=0})),!g.length)return;p=0===s?0:r&&!f?Math.max(0,y-v):g[0].pts-v}if("aac"===t.segmentCodec)for(var E=this.config.maxAudioFramesDrift,T=0,S=p+v;T<g.length;T++){var A=g[T],L=A.pts,R=L-S,I=Math.abs(1e3*R/n);if(R<=-E*h&&f)0===T&&(this.warn("Audio frame @ "+(L/n).toFixed(3)+"s overlaps marker by "+Math.round(1e3*R/n)+" ms."),this.nextAudioTs=p=L-v,S=L);else if(R>=E*h&&I<Ln&&f){var b=Math.round(R/h);for(S=L-b*h;S<0&&b&&h;)b--,S+=h;0===T&&(this.nextAudioTs=p=S-v),this.warn("Injecting "+b+" audio frames @ "+((S-v)/n).toFixed(3)+"s due to "+Math.round(1e3*R/n)+" ms gap.");for(var k=0;k<b;k++){var D=mn.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);D||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),D=A.unit.subarray()),g.splice(T,0,{unit:D,pts:S}),S+=h,T++}}A.pts=S,S+=h}for(var _,O=null,x=null,M=0,F=g.length;F--;)M+=g[F].unit.byteLength;for(var N=0,U=g.length;N<U;N++){var B=g[N],G=B.unit,$=B.pts;if(null!==x)c[N-1].duration=Math.round(($-x)/o);else{if(i&&"aac"===t.segmentCodec&&($=p+v),O=$,!(M>0))return;M+=m;try{_=new Uint8Array(M)}catch(t){return void this.observer.emit(w.ERROR,w.ERROR,{type:P.MUX_ERROR,details:C.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:M,reason:"fail allocating audio mdat "+M})}u||(new DataView(_.buffer).setUint32(0,M),_.set(vn.types.mdat,4))}_.set(G,m);var K=G.byteLength;m+=K,c.push(_n(!0,l,K,0)),x=$}var V=c.length;if(V){var H=c[c.length-1];p=x-v,this.nextAudioTs=p+o*H.duration;var Y=u?new Uint8Array(0):vn.moof(t.sequenceNumber++,O/o,a({},t,{samples:c}));t.samples=[];var W=(O-v)/n,j=p/n,q={data1:Y,data2:_,startPTS:W,endPTS:j,startDTS:W,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,q}},e}(N);function Cn(t,e){var i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function wn(t){for(var e=0;e<t.length;e++)if(t[e].key)return e;return-1}function On(t,e,i,r){var s=t.samples.length;if(s){for(var n=t.inputTimeScale,a=0;a<s;a++){var o=t.samples[a];o.pts=Cn(o.pts-i.baseTime*n/i.timescale,e*n)/n,o.dts=Cn(o.dts-r.baseTime*n/r.timescale,e*n)/n}var l=t.samples;return t.samples=[],{samples:l}}}function xn(t,e,i){var r=t.samples.length;if(r){for(var s=t.inputTimeScale,n=0;n<r;n++){var a=t.samples[n];a.pts=Cn(a.pts-i.baseTime*s/i.timescale,e*s)/s}t.samples.sort((function(t,e){return t.pts-e.pts}));var o=t.samples;return t.samples=[],{samples:o}}}var Mn,Fn=function(t){function e(e,i,r,s){var n;return(n=t.call(this,"passthrough-remuxer",s)||this).emitInitSegment=!1,n.audioCodec=void 0,n.videoCodec=void 0,n.initData=void 0,n.initPTS=null,n.initTracks=void 0,n.lastEndTime=null,n.isVideoContiguous=!1,n}l(e,t);var i=e.prototype;return i.destroy=function(){},i.resetTimeStamp=function(t){this.lastEndTime=null;var e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)},i.resetNextTimestamp=function(){this.isVideoContiguous=!1,this.lastEndTime=null},i.resetInitSegment=function(t,e,i,r){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,r),this.emitInitSegment=!0},i.generateInitSegment=function(t,e){var i=this.audioCodec,r=this.videoCodec;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var s=this.initData=vt(t),n=s.audio,a=s.video;if(e)Rt(t,e);else{var o=n||a;null!=o&&o.encrypted&&this.warn('Init segment with encrypted track with has no key ("'+o.codec+'")!')}n&&(i=Bn(n,J.AUDIO,this)),a&&(r=Bn(a,J.VIDEO,this));var l={};n&&a?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:n?l.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:t,id:"audio"}:a?l.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l},i.remux=function(t,e,i,r,s,n){var a,o,l=this.initPTS,h=this.lastEndTime,d={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};k(h)||(h=this.lastEndTime=s||0);var u=e.samples;if(!u.length)return d;var c={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=bt(u,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,v=Nn(p,1/0),y=Nn(m,1/0),E=Nn(p,0,!0),T=Nn(m,0,!0),S=s,A=0,L=m&&(!p||!l&&y<v||l&&l.trackId===f.audio.id),R=L?m:p;if(R){var I=R.timescale,b=R.start-s*I,D=L?f.audio.id:f.video.id;S=R.start/I,A=L?T-y:E-v,!n&&l||!Un(l,S,s,A)&&I===l.timescale||(l&&this.warn("Timestamps at playlist time: "+(n?"":"~")+s+" "+b/I+" != initPTS: "+l.baseTime/l.timescale+" ("+l.baseTime+"/"+l.timescale+") trackId: "+l.trackId),this.log("Found initPTS at playlist time: "+s+" offset: "+(S-s)+" ("+b+"/"+I+") trackId: "+D),l=null,c.initPTS=b,c.timescale=I,c.trackId=D)}else this.warn("No audio or video samples found for initPTS at playlist time: "+s);l?(c.initPTS=l.baseTime,c.timescale=l.timescale,c.trackId=l.trackId):(c.timescale&&void 0!==c.trackId&&void 0!==c.initPTS||(this.warn("Could not set initPTS"),c.initPTS=S,c.timescale=1,c.trackId=-1),this.initPTS=l={baseTime:c.initPTS,timescale:c.timescale,trackId:c.trackId});var _=S-l.baseTime/l.timescale,P=_+A;A>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var C=!!f.audio,w=!!f.video,O="";C&&(O+="audio"),w&&(O+="video");var x={data1:u,startPTS:_,startDTS:_,endPTS:P,endDTS:P,type:O,hasAudio:C,hasVideo:w,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};d.audio=C&&!w?x:void 0,d.video=w?x:void 0;var M=null==p?void 0:p.sampleCount;if(M){var F=p.keyFrameIndex,N=-1!==F;x.nb=M,x.dropped=0===F||this.isVideoContiguous?0:N?F:M,x.independent=N,x.firstKeyFrame=F,N&&p.keyFrameStart&&(x.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=N),this.isVideoContiguous||(this.isVideoContiguous=N),x.dropped&&this.warn("fmp4 does not start with IDR: firstIDR "+F+"/"+M+" dropped: "+x.dropped+" start: "+(x.firstKeyFramePTS||"NA"))}return d.initSegment=c,d.id3=On(i,s,l,l),r.samples.length&&(d.text=xn(r,s,l)),d},e}(N);function Nn(t,e,i){return void 0===i&&(i=!1),void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Un(t,e,i,r){if(null===t)return!0;var s=Math.max(r,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>s}function Bn(t,e,i){var r=t.codec;return r&&r.length>4?r:e===J.AUDIO?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?qt(r,!1):(i.warn('Unhandled audio codec "'+r+'" in mp4 MAP'),r||"mp4a"):(i.warn('Unhandled video codec "'+r+'" in mp4 MAP'),r||"avc1")}try{Mn=self.performance.now.bind(self.performance)}catch(t){Mn=Date.now}var Gn=[{demux:Js,remux:Fn},{demux:ln,remux:Pn},{demux:js,remux:Pn},{demux:zs,remux:Pn}];Gn.splice(2,0,{demux:Xs,remux:Pn});var $n=function(){function t(t,e,i,r,s,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=i,this.id=s,this.logger=n}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,i,r){var s=this,n=i.transmuxing;n.executeStart=Mn();var a=new Uint8Array(t),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var h=r||o,d=h.contiguous,u=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,m=h.initSegmentChange,p=l.audioCodec,v=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,S=Kn(a,e);if(S&&Bi(S.method)){var A=this.getDecrypter(),L=Gi(S.method);if(!A.isSync())return this.asyncResult=!0,this.decryptionPromise=A.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,L).then((function(t){var e=s.push(t,null,i);return s.decryptionPromise=null,e})),this.decryptionPromise;var R=A.softwareDecrypt(a,S.key.buffer,S.iv.buffer,L);if(i.part>-1){var I=A.flush();R=I?I.buffer:I}if(!R)return n.executeEnd=Mn(),Vn(i);a=new Uint8Array(R)}var b=this.needsProbing(u,c);if(b){var k=this.configureTransmuxer(a);if(k)return this.logger.warn("[transmuxer] "+k.message),this.observer.emit(w.ERROR,w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),n.executeEnd=Mn(),Vn(i)}(u||c||m||b)&&this.resetInitSegment(T,p,v,E,e),(u||m||b)&&this.resetInitialTimestamp(y),d||this.resetContiguity();var D=this.transmux(a,S,g,f,i);this.asyncResult=Hn(D);var _=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,n.executeEnd=Mn(),D},e.flush=function(t){var e=this,i=t.transmuxing;i.executeStart=Mn();var r=this.decrypter,s=this.currentTransmuxState,n=this.decryptionPromise;if(n)return this.asyncResult=!0,n.then((function(){return e.flush(t)}));var a=[],o=s.timeOffset;if(r){var l=r.flush();l&&a.push(this.push(l.buffer,null,t))}var h=this.demuxer,d=this.remuxer;if(!h||!d){i.executeEnd=Mn();var u=[Vn(t)];return this.asyncResult?Promise.resolve(u):u}var c=h.flush(o);return Hn(c)?(this.asyncResult=!0,c.then((function(i){return e.flushRemux(a,i,t),a}))):(this.flushRemux(a,c,t),this.asyncResult?Promise.resolve(a):a)},e.flushRemux=function(t,e,i){var r=e.audioTrack,s=e.videoTrack,n=e.id3Track,a=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+i.sn+(i.part>-1?" part: "+i.part:"")+" of "+(this.id===x.MAIN?"level":"track")+" "+i.level);var d=this.remuxer.remux(r,s,n,a,h,l,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Mn()},e.resetInitialTimestamp=function(t){var e=this.demuxer,i=this.remuxer;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,i,r,s){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(t,e,i,r),a.resetInitSegment(t,e,i,s))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,i,r,s){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,r,s):this.transmuxUnencrypted(t,i,r,s)},e.transmuxUnencrypted=function(t,e,i,r){var s=this.demuxer.demux(t,e,!1,!this.config.progressive),n=s.audioTrack,a=s.videoTrack,o=s.id3Track,l=s.textTrack;return{remuxResult:this.remuxer.remux(n,a,o,l,e,i,!1,this.id),chunkMeta:r}},e.transmuxSampleAes=function(t,e,i,r,s){var n=this;return this.demuxer.demuxSampleAes(t,e,i).then((function(t){return{remuxResult:n.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,r,!1,n.id),chunkMeta:s}}))},e.configureTransmuxer=function(t){for(var e,i=this.config,r=this.observer,s=this.typeSupported,n=0,a=Gn.length;n<a;n++){var o;if(null!=(o=Gn[n].demux)&&o.probe(t,this.logger)){e=Gn[n];break}}if(!e)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,h=this.remuxer,d=e.remux,u=e.demux;h&&h instanceof d||(this.remuxer=new d(r,i,s,this.logger)),l&&l instanceof u||(this.demuxer=new u(r,i,s,this.logger),this.probe=u.probe)},e.needsProbing=function(t,e){return!this.demuxer||!this.remuxer||t||e},e.getDecrypter=function(){var t=this.decrypter;return t||(t=this.decrypter=new fi(this.config)),t},t}();function Kn(t,e){var i=null;return t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e),i}var Vn=function(t){return{remuxResult:{},chunkMeta:t}};function Hn(t){return"then"in t&&t.then instanceof Function}var Yn=function(t,e,i,r,s){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=i,this.duration=r,this.defaultInitPts=s||null},Wn=function(t,e,i,r,s,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=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n},jn=[];function qn(){self.addEventListener("message",(function(t){var e=t.data,i=e.instanceNo;if(void 0!==i){var r=jn[i];if("reset"===e.cmd&&(delete jn[e.resetNo],r&&r.destroy(),e.cmd="init"),"init"===e.cmd){var s=JSON.parse(e.config),n=new L;n.on(w.FRAG_DECRYPTED,Zn),n.on(w.ERROR,Zn);var a=H(s.debug,e.id);return Jn(a,i),jn[i]=new $n(n,e.typeSupported,s,"",e.id,a),void Zn("init",null,i)}if(r)switch(e.cmd){case"configure":r.configure(e.config);break;case"demux":var o=r.push(e.data,e.decryptdata,e.chunkMeta,e.state);Hn(o)?o.then((function(t){Xn(self,t,i)})).catch((function(t){Zn(w.ERROR,{instanceNo:i,type:P.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,chunkMeta:e.chunkMeta,fatal:!1,error:t,err:t,reason:"transmuxer-worker push error"},i)})):Xn(self,o,i);break;case"flush":var l=e.chunkMeta,h=r.flush(l);Hn(h)?h.then((function(t){zn(self,t,l,i)})).catch((function(t){Zn(w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,chunkMeta:e.chunkMeta,fatal:!1,error:t,err:t,reason:"transmuxer-worker flush error"},i)})):zn(self,h,l,i)}}}))}function Xn(t,e,i){if(ta(e.remuxResult))return!1;var r=[],s=e.remuxResult,n=s.audio,a=s.video;return n&&Qn(r,n),a&&Qn(r,a),t.postMessage({event:"transmuxComplete",data:e,instanceNo:i},r),!0}function Qn(t,e){e.data1&&t.push(e.data1.buffer),e.data2&&t.push(e.data2.buffer)}function zn(t,e,i,r){e.reduce((function(e,i){return Xn(t,i,r)||e}),!1)||t.postMessage({event:"transmuxComplete",data:e[0],instanceNo:r}),t.postMessage({event:"flush",data:i,instanceNo:r})}function Zn(t,e,i){self.postMessage({event:t,data:e,instanceNo:i})}function Jn(t,e){var i=function(i){t[i]=function(){var t=Array.prototype.join.call(arguments," ");Zn("workerLog",{logType:i,message:t},e)}};for(var r in t)i(r)}function ta(t){return!(t.audio||t.video||t.text||t.id3||t.initSegment)}void 0!==e&&e&&qn();var ea="1.6.9",ia={};function ra(){return!0}function sa(){var e=ia[ea];if(e)return e.clientCount++,e;var i=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),r=self.URL.createObjectURL(i),s={worker:new self.Worker(r),objectURL:r,clientCount:1};return ia[ea]=s,s}function na(t){var e=ia[t];if(e)return e.clientCount++,e;var i=new self.URL(t,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return ia[t]=r,r}function aa(t){var e=ia[t||ea];if(e&&1==e.clientCount--){var i=e.worker,r=e.objectURL;delete ia[t||ea],r&&self.URL.revokeObjectURL(r),i.terminate()}}var oa=0,la=function(){function t(t,e,i,r){var s=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=oa++,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=function(t){var e=t.data,i=s.hls;if(i&&null!=e&&e.event&&e.instanceNo===s.instanceNo)switch(e.event){case"init":var r,n=null==(r=s.workerContext)?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(e.data);break;case"flush":s.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=s.frag,e.data.part=s.part,e.data.id=s.id,i.trigger(e.event,e.data)}},this.onWorkerError=function(t){if(s.hls){var e=new Error(t.message+" ("+t.filename+":"+t.lineno+")");s.hls.config.enableWorker=!1,s.hls.logger.warn('Error in "'+s.id+'" Web Worker, fallback to inline'),s.hls.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})}};var n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;var a=function(t,e){(e=e||{}).frag=s.frag||void 0,t===w.ERROR&&(e.parent=s.id,e.part=s.part,s.error=e.error),s.hls.trigger(t,e)};this.observer=new L,this.observer.on(w.FRAG_DECRYPTED,a),this.observer.on(w.ERROR,a);var o=te(n.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var l=this.hls.logger;if(n.workerPath||ra()){try{n.workerPath?(l.log("loading Web Worker "+n.workerPath+' for "'+e+'"'),this.workerContext=na(n.workerPath)):(l.log('injecting Web Worker for "'+e+'"'),this.workerContext=sa());var h=this.workerContext.worker;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:e,config:Le(n)})}catch(i){l.warn('Error setting up "'+e+'" Web Worker, fallback to inline',i),this.terminateWorker(),this.error=null,this.transmuxer=new $n(this.observer,o,n,"",e,t.logger)}return}}this.transmuxer=new $n(this.observer,o,n,"",e,t.logger)}var e=t.prototype;return e.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var t=this.instanceNo;this.instanceNo=oa++;var e=this.hls.config,i=te(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Le(e)})}},e.terminateWorker=function(){if(this.workerContext){var t=this.workerContext.worker;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),aa(this.hls.config.workerPath)}},e.destroy=function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}var e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},e.push=function(t,e,i,r,s,n,a,o,l,h){var d,u,c=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,g=this.transmuxer,m=n?n.start:s.start,p=s.decryptdata,v=this.frag,y=!(v&&s.cc===v.cc),E=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,S=this.part?l.part-this.part.index:-1,A=0===T&&l.id>1&&l.id===(null==v?void 0:v.stats.chunkCount),L=!E&&(1===T||0===T&&(1===S||A&&S<=0)),R=self.performance.now();(E||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=R),!n||!S&&L||(n.stats.parsing.start=R);var I=!(v&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=v.initSegment)?void 0:u.url)),b=new Wn(y,L,o,E,m,I);if(!L||y||I){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+s.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===x.MAIN?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+m+"\n initSegmentChange: "+I);var k=new Yn(i,r,e,a,h);this.configureTransmuxer(k)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(g){var D=g.push(t,p,l,b);Hn(D)?D.then((function(t){c.handleTransmuxComplete(t)})).catch((function(t){c.transmuxerError(t,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(D)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:t});else if(r){var s=r.flush(t);Hn(s)?s.then((function(i){e.handleFlushResult(i,t)})).catch((function(i){e.transmuxerError(i,t,"transmuxer-interface flush error")})):this.handleFlushResult(s,t)}},e.transmuxerError=function(t,e,i){this.hls&&(this.error=t,this.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))},e.handleFlushResult=function(t,e){var i=this;t.forEach((function(t){i.handleTransmuxComplete(t)})),this.onFlush(e)},e.configureTransmuxer=function(t){var e=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}(),ha=100,da=function(t){function e(e,i,r){var s;return(s=t.call(this,e,i,r,"audio-stream-controller",x.AUDIO)||this).mainAnchor=null,s.mainFragLoading=null,s.audioOnly=!1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s.registerListeners(),s}l(e,t);var i=e.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),t.prototype.onHandlerDestroying.call(this),this.resetItem()},i.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},i.registerListeners=function(){t.prototype.registerListeners.call(this);var e=this.hls;e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(w.BUFFER_RESET,this.onBufferReset,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){var e=this.hls;e&&(t.prototype.unregisterListeners.call(this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(w.BUFFER_RESET,this.onBufferReset,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this))},i.onInitPtsFound=function(t,e){var i=e.frag,r=e.id,s=e.initPTS,n=e.timescale,a=e.trackId;if(r===x.MAIN){var o=i.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:s,timescale:n,trackId:a},this.log("InitPTS for cc: "+o+" found from main: "+s/n+" ("+s+"/"+n+") trackId: "+a),this.mainAnchor=i,this.state===jr.WAITING_INIT_PTS){var h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==o)&&this.syncWithAnchor(i,null==h?void 0:h.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(i,l)):this.state===jr.IDLE&&this.tick()}},i.getLoadPosition=function(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:t.prototype.getLoadPosition.call(this)},i.syncWithAnchor=function(t,e){var i,r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(!e||(null==r?void 0:r.cc)!==e.cc){var s=(r||t).cc,n=He(this.getLevelDetails(),s,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===jr.IDLE&&this.doTickIdle())}},i.startLoad=function(t,e){if(!this.levels)return this.startPosition=t,void(this.state=jr.STOPPED);var i=this.lastCurrentTime;this.stopLoad(),this.setInterval(ha),i>0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),t=i,this.state=jr.IDLE):this.state=jr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()},i.doTick=function(){switch(this.state){case jr.IDLE:this.doTickIdle();break;case jr.WAITING_TRACK:var e=this.levels,i=this.trackId,r=null==e?void 0:e[i],s=null==r?void 0:r.details;if(s&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(s))break;this.state=jr.WAITING_INIT_PTS}break;case jr.FRAG_LOADING_WAITING_RETRY:var n,a=performance.now(),o=this.retryDate;if(!o||a>=o||null!=(n=this.media)&&n.seeking){var l=this.levels,h=this.trackId;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==l?void 0:l[h])||null),this.state=jr.IDLE}break;case jr.WAITING_INIT_PTS:var d=this.waitingData;if(d){var u=d.frag,c=d.part,f=d.cache,g=d.complete,m=this.mainAnchor;if(void 0!==this.initPTS[u.cc]){this.waitingData=null,this.state=jr.FRAG_LOADING;var p={frag:u,part:c,payload:f.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(p),g&&t.prototype._handleFragmentLoadComplete.call(this,p)}else m&&m.cc!==d.frag.cc&&this.syncWithAnchor(m,d.frag)}else this.state=jr.IDLE}this.onTickEnd()},i.resetLoadingState=function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),t.prototype.resetLoadingState.call(this)},i.onTickEnd=function(){var t=this.media;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)},i.doTickIdle=function(){var t,e=this.hls,i=this.levels,r=this.media,s=this.trackId,n=e.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&n.startFragPrefetch)&&null!=i&&i[s]){var a=i[s],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=jr.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,J.AUDIO,x.AUDIO));var h=this.getFwdBufferInfo(l,x.AUDIO);if(null!==h){if(!this.switchingTrack&&this._streamEnded(h,o))return e.trigger(w.BUFFER_EOS,{type:"audio"}),void(this.state=jr.ENDED);var d=h.len,u=e.maxBufferLength,c=o.fragments,f=c[0].start,g=this.getLoadPosition(),m=this.flushing?g:h.end;if(this.switchingTrack&&r){var p=g;o.PTSKnown&&p<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(d>=u&&!this.switchingTrack&&m<c[c.length-1].start)){var v=this.getNextFragment(m,o);if(v&&this.isLoopLoading(v,m)&&(v=this.getNextFragmentLoopLoading(v,o,h,x.MAIN,u)),v){var y=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&et(v)&&!v.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===ei.OK&&(this.mainFragLoading=y=null),y&&et(y))){if(v.start>y.end){var E=this.fragmentTracker.getFragAtPos(m,x.MAIN);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(v.start>y.end)return}this.loadFragment(v,a,m)}else this.bufferFlushed=!0}}}},i.onMediaDetaching=function(e,i){this.bufferFlushed=this.flushing=!1,t.prototype.onMediaDetaching.call(this,e,i)},i.onAudioTracksUpdated=function(t,e){var i=e.audioTracks;this.resetTransmuxer(),this.levels=i.map((function(t){return new ye(t)}))},i.onAudioTrackSwitching=function(t,e){var i=!!e.url;this.trackId=e.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==jr.STOPPED&&(this.setInterval(ha),this.state=jr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())},i.onManifestLoading=function(){t.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},i.onLevelLoaded=function(t,e){this.mainDetails=e.details;var i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(w.AUDIO_TRACK_LOADED,i))},i.onAudioTrackLoaded=function(t,e){var i,r=this.levels,s=e.details,n=e.id,a=e.groupId,o=e.track;if(r){var l=this.mainDetails;if(!l||s.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==jr.STOPPED&&(this.state=jr.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+n+' "'+o.name+'" of "'+a+'" loaded ['+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration);var h=r[n],d=0;if(s.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;var u;h.details&&(d=this.alignPlaylists(s,h.details,null==(u=this.levelLastLoaded)?void 0:u.details)),s.alignedSliding||(Hr(s,l),s.alignedSliding||Yr(s,l),d=s.fragmentStart)}h.details=s,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(w.AUDIO_TRACK_UPDATED,{details:s,id:n,groupId:e.groupId}),this.state!==jr.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=jr.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+n+' "'+o.name+'" of "'+a+'"')},i._handleFragmentLoadProgress=function(t){var e,i=t.frag,r=t.part,s=t.payload,n=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);var d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new la(this.hls,x.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==c){var g=!1,m=r?r.index:-1,p=-1!==m,v=new Si(i.level,i.sn,i.stats.chunkCount,s.byteLength,m,p);u.push(s,f,d,"",i,r,h.totalduration,g,v,c)}else this.log("Unknown video PTS for cc "+i.cc+", waiting for video PTS before demuxing audio frag "+i.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new Qr,complete:!1}).cache.push(new Uint8Array(s)),this.state!==jr.STOPPED&&(this.state=jr.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i._handleFragmentLoadComplete=function(e){this.waitingData?this.waitingData.complete=!0:t.prototype._handleFragmentLoadComplete.call(this,e)},i.onBufferReset=function(){this.mediaBuffer=null},i.onBufferCreated=function(t,e){this.bufferFlushed=this.flushing=!1;var i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)},i.onFragLoading=function(t,e){!this.audioOnly&&e.frag.type===x.MAIN&&et(e.frag)&&(this.mainFragLoading=e,this.state===jr.IDLE&&this.tick())},i.onFragBuffered=function(t,e){var i=e.frag,r=e.part;if(i.type===x.AUDIO)if(this.fragContextChanged(i))this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if(et(i)){this.fragPrevious=i;var s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(w.AUDIO_TRACK_SWITCHED,c({},s)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==x.MAIN||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},i.onError=function(e,i){var r;if(i.fatal)this.state=jr.ERROR;else switch(i.details){case C.FRAG_GAP:case C.FRAG_PARSING_ERROR:case C.FRAG_DECRYPT_ERROR:case C.FRAG_LOAD_ERROR:case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_ERROR:case C.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(x.AUDIO,i);break;case C.AUDIO_TRACK_LOAD_ERROR:case C.AUDIO_TRACK_LOAD_TIMEOUT:case C.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==jr.WAITING_TRACK||(null==(r=i.context)?void 0:r.type)!==O.AUDIO_TRACK||(this.state=jr.IDLE);break;case C.BUFFER_ADD_CODEC_ERROR:case C.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)||this.resetLoadingState();break;case C.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case C.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}},i.onBufferFlushing=function(t,e){e.type!==J.VIDEO&&(this.flushing=!0)},i.onBufferFlushed=function(t,e){var i=e.type;if(i!==J.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===jr.ENDED&&(this.state=jr.IDLE);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,x.AUDIO),this.tick())}},i._handleTransmuxComplete=function(t){var e,i="audio",r=this.hls,s=t.remuxResult,n=t.chunkMeta,o=this.getCurrentContext(n);if(o){var l=o.frag,h=o.part,d=o.level,u=d.details,c=s.audio,f=s.text,g=s.id3,m=s.initSegment;if(!this.fragContextChanged(l)&&u){if(this.state=jr.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){var p=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(d,m.tracks,p,n),r.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:m.tracks})}if(c){var v=c.startPTS,y=c.endPTS,E=c.startDTS,T=c.endDTS;h&&(h.elementaryStreams[J.AUDIO]={startPTS:v,endPTS:y,startDTS:E,endDTS:T}),l.setElementaryStreamInfo(J.AUDIO,v,y,E,T),this.bufferFragmentData(c,l,h,n)}if(null!=g&&null!=(e=g.samples)&&e.length){var S=a({id:i,frag:l,details:u},g);r.trigger(w.FRAG_PARSING_METADATA,S)}if(f){var A=a({id:i,frag:l,details:u},f);r.trigger(w.FRAG_PARSING_USERDATA,A)}}else this.fragmentTracker.removeFragment(l)}else this.resetWhenMissingContext(n)},i._bufferInitSegment=function(t,e,i,r){if(this.state===jr.PARSING&&(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,e.audio)){var s=e.audio;s.id=x.AUDIO;var n=t.audioCodec;this.log("Init audio buffer, container:"+s.container+", codecs[level/parsed]=["+n+"/"+s.codec+"]"),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(w.BUFFER_CODECS,e);var a=s.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(w.BUFFER_APPENDING,o)}this.tickImmediate()}},i.loadFragment=function(e,i,r){var s,n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===ei.NOT_LOADED||n===ei.PARTIAL)if(et(e))if(null!=(s=i.details)&&s.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter "+e.cc+" of live stream before loading audio fragment "+e.sn+" of level "+this.trackId),this.state=jr.WAITING_INIT_PTS;var a=this.mainDetails;a&&a.fragmentStart!==i.details.fragmentStart&&Yr(i.details,a)}else t.prototype.loadFragment.call(this,e,i,r);else this._loadInitSegment(e,i);else this.clearTrackerIfNeeded(e)},i.flushAudioIfNeeded=function(e){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;Pe({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.channels},e,Oe)||(Fe(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}},i.completeAudioSwitch=function(t){var e=this.hls;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(w.AUDIO_TRACK_SWITCHED,c({},t))},e}(qr),ua=function(t){function e(e,i){var r;return(r=t.call(this,i,e.logger)||this).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=e,r}l(e,t);var i=e.prototype;return i.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},i.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},i.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},i.stopLoad=function(){this.canLoad=!1,this.clearTimer()},i.switchParams=function(t,e,i){var r=null==e?void 0:e.renditionReports;if(r){for(var s=-1,n=0;n<r.length;n++){var a=r[n],o=void 0;try{o=new self.URL(a.URI,e.url).href}catch(t){this.warn("Could not construct new URL for Rendition Report: "+t),o=a.URI||""}if(o===t){s=n;break}o===t.substring(0,o.length)&&(s=n)}if(-1!==s){var l=r[s],h=parseInt(l["LAST-MSN"])||e.lastPartSn,d=parseInt(l["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){var u=Math.min(e.age-e.partTarget,e.targetduration);d>=0&&u>e.partTarget&&(d+=1)}var c=i&&pe(i);return new ve(h,d>=0?d:void 0,c)}}},i.loadPlaylist=function(t){this.clearTimer()},i.loadingPlaylist=function(t,e){this.clearTimer()},i.shouldLoadPlaylist=function(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)},i.getUrlWithDirectives=function(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}return t},i.playlistLoaded=function(t,e,i){var r=e.details,s=e.stats,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;r.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach((function(t){t.setStart(t.playlistOffset+l)}))}if(r.live||null!=i&&i.live){var h="levelInfo"in e?e.levelInfo:e.track;if(r.reloaded(i),i&&r.fragments.length>0){kr(i,r,this);var d=r.playlistParsingError;if(d){this.warn(d);var u=this.hls;if(!u.config.ignorePlaylistParsingErrors){var c,f=e.networkDetails;return void u.trigger(w.ERROR,{type:P.NETWORK_ERROR,details:C.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:d,reason:d.message,level:e.level||void 0,parent:null==(c=r.fragments[0])?void 0:c.type,networkDetails:f,stats:s})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);var g,m=this.hls.mainForwardBufferInfo,p=m?m.end-m.len:0,v=xr(r,1e3*(r.edge-p));if(r.requestScheduled+v<n?r.requestScheduled=n:r.requestScheduled+=v,this.log("live playlist "+t+" "+(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var T=this.hls.config.lowLatencyMode,S=r.lastPartSn,A=r.endSN,L=r.lastPartIndex,R=S===A;-1!==L?R?(y=A+1,E=T?0:L):(y=S,E=T?L+1:r.maxPartIndex):y=A+1;var I=r.age,b=I+r.ageHeader,k=Math.min(b-r.partTarget,1.5*r.targetduration);if(k>0){if(b>3*r.targetduration)this.log("Playlist last advanced "+I.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=i&&i.tuneInGoal&&b-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+i.tuneInGoal+" to: "+k+" with playlist age: "+r.age),k=0;else{var D=Math.floor(k/r.targetduration);y+=D,void 0!==E&&(E+=Math.round(k%r.targetduration/r.partTarget)),this.log("CDN Tune-in age: "+r.ageHeader+"s last advanced "+I.toFixed(2)+"s goal: "+k+" skip sn "+D+" to part "+E)}r.tuneInGoal=k}if(g=this.getDeliveryDirectives(r,e.deliveryDirectives,y,E),T||!R)return r.requestScheduled=n,void this.loadingPlaylist(h,g)}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,e.deliveryDirectives,y,E));g&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(v-2*a,v/2)),this.scheduleLoading(h,g,r)}else this.clearTimer()},i.scheduleLoading=function(t,e,i){var r=this,s=i||t.details;if(s){var n=self.performance.now(),a=s.requestScheduled;if(n>=a)this.loadingPlaylist(t,e);else{var o=a-n;this.log("reload live playlist "+(t.name||t.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return r.loadingPlaylist(t,e)}),o)}}else this.loadingPlaylist(t,e)},i.getDeliveryDirectives=function(t,e,i,r){var s=pe(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,r=e.part,s=me.No),new ve(i,r,s)},i.checkRetry=function(t){var e=this,i=t.details,r=Ye(t),s=t.errorAction,n=s||{},a=n.action,o=n.retryCount,l=void 0===o?0:o,h=n.retryConfig,d=!!s&&!!h&&(a===ze.RetryRequest||!s.resolved&&a===ze.SendAlternateToPenaltyBox);if(d){var u;if(l>=h.maxNumRetry)return!1;if(r&&null!=(u=t.context)&&u.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" without delivery-directives'),this.loadPlaylist();else{var c=je(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return e.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" in '+c+"ms")}t.levelRetry=!0,s.resolved=!0}return d},e}(N);function ca(t,e){if(t.length!==e.length)return!1;for(var i=0;i<t.length;i++)if(!fa(t[i].attrs,e[i].attrs))return!1;return!0}function fa(t,e,i){var r=t["STABLE-RENDITION-ID"];return r&&!i?r===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(i){return t[i]!==e[i]}))}function ga(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}var ma=function(t){function e(e){var i;return(i=t.call(this,e,"audio-track-controller")||this).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.registerListeners(),i}l(e,t);var i=e.prototype;return i.registerListeners=function(){var t=this.hls;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVEL_LOADING,this.onLevelLoading,this),t.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(w.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVEL_LOADING,this.onLevelLoading,this),t.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(w.ERROR,this.onError,this)},i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,t.prototype.destroy.call(this)},i.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},i.onManifestParsed=function(t,e){this.tracks=e.audioTracks||[]},i.onAudioTrackLoaded=function(t,e){var i=e.id,r=e.groupId,s=e.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=e.details,this.log("Audio track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,e,a)}else this.warn("Audio track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(t,e){this.switchLevel(e.level)},i.onLevelSwitching=function(t,e){this.switchLevel(e.level)},i.switchLevel=function(t){var e=this.hls.levels[t];if(e){var i=e.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(t){return-1===(null==r?void 0:r.indexOf(t))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(t){return!i||-1!==i.indexOf(t.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(t){return t.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(t,e){t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.audioPreference;if(!s&&a){var o=_e(a,n,Oe);if(o>-1)s=n[o];else{var l=_e(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var d={audioTracks:n};this.log("Updating audio tracks, "+n.length+" track(s) found in group(s): "+(null==i?void 0:i.join(","))),this.hls.trigger(w.AUDIO_TRACKS_UPDATED,d);var u=this.trackId;if(-1!==h&&-1===u)this.setAudioTrack(h);else if(n.length&&-1===u){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+n.length);this.warn(f.message),this.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}},i.onError=function(t,e){!e.fatal&&e.context&&(e.context.type!==O.AUDIO_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))},i.setAudioOption=function(t){var e=this.hls;if(e.config.audioPreference=t,t){var i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&Pe(t,r,Oe))return r;var s=_e(t,this.tracksInGroup,Oe);if(s>-1){var n=this.tracksInGroup[s];return this.setAudioTrack(s),n}if(r){var a=e.loadLevel;-1===a&&(a=e.firstAutoLevel);var o=xe(t,e.levels,i,a,Oe);if(-1===o)return null;e.nextLoadLevel=o}if(t.channels||t.audioCodec){var l=_e(t,i);if(l>-1)return i[l]}}}return null},i.setAudioTrack=function(t){var e=this.tracksInGroup;if(t<0||t>=e.length)this.warn("Invalid audio track id: "+t);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=e[t],s=r.details&&!r.details.live;if(!(t===this.trackId&&r===i&&s||(this.log("Switching to audio-track "+t+' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId+" channels:"+r.channels),this.trackId=t,this.currentTrack=r,this.hls.trigger(w.AUDIO_TRACK_SWITCHING,c({},r)),s))){var n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}}},i.findTrackId=function(t){for(var e=this.tracksInGroup,i=0;i<e.length;i++){var r=e[i];if((!this.selectDefaultTrack||r.default)&&(!t||Pe(t,r,Oe)))return i}if(t){for(var s=t.name,n=t.lang,a=t.assocLang,o=t.characteristics,l=t.audioCodec,h=t.channels,d=0;d<e.length;d++)if(Pe({name:s,lang:n,assocLang:a,characteristics:o,audioCodec:l,channels:h},e[d],Oe))return d;for(var u=0;u<e.length;u++){var c=e[u];if(fa(t.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return u}for(var f=0;f<e.length;f++){var g=e[f];if(fa(t.attrs,g.attrs,["LANGUAGE"]))return f}}return-1},i.loadPlaylist=function(e){t.prototype.loadPlaylist.call(this);var i=this.currentTrack;this.shouldLoadPlaylist(i)&&Fe(i.url,this.hls)&&this.scheduleLoading(i,e)},i.loadingPlaylist=function(e,i){t.prototype.loadingPlaylist.call(this,e,i);var r=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,i),a=e.details,o=null==a?void 0:a.age;this.log("Loading audio-track "+r+' "'+e.name+'" lang:'+e.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type?" "+a.type||0:""):"")+" "+n),this.hls.trigger(w.AUDIO_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:e})},s(e,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}}])}(ua),pa=function(){function t(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}var e=t.prototype;return e.destroy=function(){this.tracks=this.queues=null},e.append=function(t,e,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[e];r.push(t),1!==r.length||i||this.executeNext(e)}},e.appendBlocker=function(t){var e=this;return new Promise((function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};e.append(r,t)}))},e.prependBlocker=function(t){var e=this;return new Promise((function(i){if(e.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};e.queues[t].unshift(r)}}))},e.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(t){var e,i=null==(e=t[0])?void 0:e.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(t[0].execute(),t.splice(0,1))}))},e.unblockAudio=function(t){null!==this.queues&&this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")},e.executeNext=function(t){if(null!==this.queues&&null!==this.tracks){var e=this.queues[t];if(e.length){var i=e[0];try{i.execute()}catch(e){var r;if(i.onError(e),null===this.queues||null===this.tracks)return;var s=null==(r=this.tracks[t])?void 0:r.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(t)}}}},e.shiftAndExecuteNext=function(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))},e.current=function(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null},e.toString=function(){var t=this.queues,e=this.tracks;return null===t||null===e?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},e.list=function(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?t+": ("+this.listSbInfo(t)+") "+this.listOps(t):""},e.listSbInfo=function(t){var e,i=null==(e=this.tracks)?void 0:e[t],r=null==i?void 0:i.buffer;return r?"SourceBuffer"+(r.updating?" updating":"")+(i.ended?" ended":"")+(i.ending?" ending":""):"none"},e.listOps=function(t){var e;return(null==(e=this.queues)?void 0:e[t].map((function(t){return t.label})).join(", "))||""},t}(),va=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ya="HlsJsTrackRemovedError",Ea=function(t){function e(e){var i;return(i=t.call(this,e)||this).name=ya,i}return l(e,t),e}(p(Error)),Ta=function(t){function e(e,i){var r;return(r=t.call(this,"buffer-controller",e.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(t){var e;r.hls&&"open"===(null==(e=r.mediaSource)?void 0:e.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(t){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(t){var e=r,i=e.media,s=e.mediaSource;t&&r.log("Media source opened"),i&&s&&(s.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(w.MEDIA_ATTACHED,{media:i,mediaSource:s}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var t=r,e=t.mediaSrc,i=t._objectUrl;e!==i&&r.error("Media element src was set while attaching MediaSource ("+i+" > "+e+")")},r.hls=e,r.fragmentTracker=i,r.appendSource=j(W(e.config.preferManagedMediaSource)),r.initTracks(),r.registerListeners(),r}l(e,t);var i=e.prototype;return i.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},i.destroy=function(){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},i.registerListeners=function(){var t=this.hls;t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.BUFFER_RESET,this.onBufferReset,this),t.on(w.BUFFER_APPENDING,this.onBufferAppending,this),t.on(w.BUFFER_CODECS,this.onBufferCodecs,this),t.on(w.BUFFER_EOS,this.onBufferEos,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(w.FRAG_PARSED,this.onFragParsed,this),t.on(w.FRAG_CHANGED,this.onFragChanged,this),t.on(w.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.BUFFER_RESET,this.onBufferReset,this),t.off(w.BUFFER_APPENDING,this.onBufferAppending,this),t.off(w.BUFFER_CODECS,this.onBufferCodecs,this),t.off(w.BUFFER_EOS,this.onBufferEos,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(w.FRAG_PARSED,this.onFragParsed,this),t.off(w.FRAG_CHANGED,this.onFragChanged,this),t.off(w.ERROR,this.onError,this)},i.transferMedia=function(){var t=this,e=this.media,i=this.mediaSource;if(!e)return null;var r={};if(this.operationQueue){var s=this.isUpdating();s||this.operationQueue.removeBlockers();var n=this.isQueued();(s||n)&&this.warn("Transfering MediaSource with"+(n?" operations in queue":"")+(s?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var o=this.transferData;return!this.sourceBufferCount&&o&&o.mediaSource===i?a(r,o.tracks):this.sourceBuffers.forEach((function(e){var i=e[0];i&&(r[i]=a({},t.tracks[i]),t.removeBuffer(i)),e[0]=e[1]=null})),{media:e,mediaSource:i,tracks:r}},i.initTracks=function(){var t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},i.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},i.onManifestParsed=function(t,e){var i,r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(r+" bufferCodec event(s) expected."),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()},i.onMediaAttaching=function(t,e){var i=this.media=e.media;this.transferData=this.overrides=void 0;var r=W(this.appendSource);if(r){var s=!!e.mediaSource;(s||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);var n=this.mediaSource=e.mediaSource||new r;if(this.assignMediaSource(n),s)this._objectUrl=i.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&n instanceof o,Sa(i),Aa(i,a),i.load()}catch(t){i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}},i.assignMediaSource=function(t){var e,i;this.log(((null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created")+" media source: "+(null==(i=t.constructor)?void 0:i.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))},i.attachTransferred=function(){var t=this,e=this.media,i=this.transferData;if(i&&e){var r=this.tracks,s=i.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=function(){Promise.resolve().then((function(){t.media&&t.mediaSourceOpenOrEnded&&t._onMediaSourceOpen()}))};if(s&&n&&a){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: "+Le(r,(function(t,e){return"initSegment"===t?void 0:e}))+";\ntransfer tracks: "+Le(s,(function(t,e){return"initSegment"===t?void 0:e}))+"}"),!q(s,r)){i.mediaSource=null,i.tracks=void 0;var l=e.currentTime,h=this.details,d=Math.max(l,(null==h?void 0:h.fragments[0].start)||0);return d-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+d):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(s)+'"->"'+Object.keys(r)+'") start time: '+d+" currentTime: "+l),this.onMediaDetaching(w.MEDIA_DETACHING,{}),this.onMediaAttaching(w.MEDIA_ATTACHING,i),void(e.currentTime=d))}this.transferData=void 0,n.forEach((function(e){var i=e,r=s[i];if(r){var n=r.buffer;if(n){var a=t.fragmentTracker,o=r.id;if(a.hasFragments(o)||a.hasParts(o)){var l=Ri.getBuffered(n);a.detectEvictedFragments(i,l,o,null,!0)}var h=La(i),d=[i,n];t.sourceBuffers[h]=d,n.updating&&t.operationQueue&&t.operationQueue.prependBlocker(i),t.trackSourceBuffer(i,r)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},i.onMediaDetaching=function(t,e){var i=this,r=!!e.transferMedia;this.transferData=this.overrides=void 0;var s=this.media,n=this.mediaSource,a=this._objectUrl;if(n){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach((function(t){var e=t[0];e&&i.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===n.readyState;try{for(var l=n.sourceBuffers,h=l.length;h--;)o&&l[h].abort(),n.removeSourceBuffer(l[h]);o&&n.endOfStream()}catch(t){this.warn("onMediaDetaching: "+t.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&Sa(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(w.MEDIA_DETACHED,e)},i.onBufferReset=function(){var t=this;this.sourceBuffers.forEach((function(e){var i=e[0];i&&t.resetBuffer(i)})),this.initTracks()},i.resetBuffer=function(t){var e,i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn("onBufferReset "+t,e)}delete this.tracks[t]},i.removeBuffer=function(t){this.removeBufferListeners(t),this.sourceBuffers[La(t)]=[null,null];var e=this.tracks[t];e&&(e.buffer=void 0)},i.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new pa(this.tracks)},i.onBufferCodecs=function(t,e){var i=this,r=this.tracks,s=Object.keys(e);this.log('BUFFER_CODECS: "'+s+'" (current SB count '+this.sourceBufferCount+")");var n="audiovideo"in e&&(r.audio||r.video)||r.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&s.some((function(t){return!r[t]}));n||a?this.warn('Unsupported transition between "'+Object.keys(r)+'" and "'+s+'" SourceBuffers'):(s.forEach((function(t){var s,n,a=e[t],o=a.id,l=a.codec,h=a.levelCodec,d=a.container,u=a.metadata,c=a.supplemental,f=r[t],g=null==(s=i.transferData)||null==(s=s.tracks)?void 0:s[t],m=null!=g&&g.buffer?g:f,p=(null==m?void 0:m.pendingCodec)||(null==m?void 0:m.codec),v=null==m?void 0:m.levelCodec;f||(f=r[t]={buffer:void 0,listeners:[],codec:l,supplemental:c,container:d,levelCodec:h,metadata:u,id:o});var y=Qt(p,v),E=null==y?void 0:y.replace(va,"$1"),T=Qt(l,h),S=null==(n=T)?void 0:n.replace(va,"$1");T&&y&&E!==S&&("audio"===t.slice(0,5)&&(T=qt(T,i.appendSource)),i.log("switching codec "+p+" to "+T),T!==(f.pendingCodec||f.codec)&&(f.pendingCodec=T),f.container=d,i.appendChangeType(t,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())},i.appendChangeType=function(t,e,i){var r=this,s=e+";codecs="+i,n={label:"change-type="+s,execute:function(){var n=r.tracks[t];if(n){var a=n.buffer;null!=a&&a.changeType&&(r.log("changing "+t+" sourceBuffer type to "+s),a.changeType(s),n.codec=i,n.container=e)}r.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Failed to change "+t+" SourceBuffer type",e)}};this.append(n,t,this.isPending(this.tracks[t]))},i.blockAudio=function(t){var e,i=this,r=t.start,s=r+.05*t.duration;if(!0!==(null==(e=this.fragmentTracker.getAppendedFrag(r,x.MAIN))?void 0:e.gap)){var n={label:"block-audio",execute:function(){var t,e=i.tracks.video;(i.lastVideoAppendEnd>s||null!=e&&e.buffer&&Ri.isBuffered(e.buffer,s)||!0===(null==(t=i.fragmentTracker.getAppendedFrag(s,x.MAIN))?void 0:t.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:n,frag:t},this.append(n,"audio",!0)}},i.unblockAudio=function(){var t=this.blockedAudioAppend,e=this.operationQueue;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))},i.onBufferAppending=function(t,e){var i=this,r=this.tracks,s=e.data,n=e.type,a=e.parent,o=e.frag,l=e.part,h=e.chunkMeta,d=e.offset,u=h.buffering[n],c=o.sn,f=o.cc,g=self.performance.now();u.start=g;var m=o.stats.buffering,p=l?l.stats.buffering:null;0===m.start&&(m.start=g),p&&0===p.start&&(p.start=g);var v=r.audio,y=!1;"audio"===n&&"audio/mpeg"===(null==v?void 0:v.container)&&(y=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var E=r.video,T=null==E?void 0:E.buffer;if(T&&"initSegment"!==c){var S=l||o,A=this.blockedAudioAppend;if("audio"!==n||"main"===a||this.blockedAudioAppend||E.ending||E.ended){if("video"===n){var L=S.end;if(A){var R=A.frag.start;(L>R||L<this.lastVideoAppendEnd||Ri.isBuffered(T,R))&&this.unblockAudio()}this.lastVideoAppendEnd=L}}else{var I=S.start+.05*S.duration,b=T.buffered,D=this.currentOp("video");b.length||D?!D&&!Ri.isBuffered(T,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(S):this.blockAudio(S)}}var _=(l||o).start,O={label:"append-"+n,execute:function(){var t;u.executeStart=self.performance.now();var e=null==(t=i.tracks[n])?void 0:t.buffer;e&&(y?i.updateTimestampOffset(e,_,.1,n,c,f):void 0!==d&&k(d)&&i.updateTimestampOffset(e,d,1e-6,n,c,f)),i.appendExecutor(s,n)},onStart:function(){},onComplete:function(){var t=self.performance.now();u.executeEnd=u.end=t,0===m.first&&(m.first=t),p&&0===p.first&&(p.first=t);var e={};i.sourceBuffers.forEach((function(t){var i=t[0],r=t[1];i&&(e[i]=Ri.getBuffered(r))})),i.appendErrors[n]=0,"audio"===n||"video"===n?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(w.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:e})},onError:function(t){var e,r={type:P.MEDIA_ERROR,parent:o.type,details:C.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1},s=null==(e=i.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)r.details=C.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!s)r.errorAction=ti(!0);else if(t.name===ya&&0===i.sourceBufferCount)r.errorAction=ti(!0);else{var a=++i.appendErrors[n];i.warn("Failed "+a+"/"+i.hls.config.appendErrorMaxRetry+' times to append segment in "'+n+'" sourceBuffer ('+(s||"no media error")+")"),(a>=i.hls.config.appendErrorMaxRetry||s)&&(r.fatal=!0)}i.hls.trigger(w.ERROR,r)}};this.append(O,n,this.isPending(this.tracks[n]))},i.getFlushOp=function(t,e,i){var r=this;return this.log('queuing "'+t+'" remove '+e+"-"+i),{label:"remove",execute:function(){r.removeExecutor(t,e,i)},onStart:function(){},onComplete:function(){r.hls.trigger(w.BUFFER_FLUSHED,{type:t})},onError:function(s){r.warn("Failed to remove "+e+"-"+i+' from "'+t+'" SourceBuffer',s)}}},i.onBufferFlushing=function(t,e){var i=this,r=e.type,s=e.startOffset,n=e.endOffset;r?this.append(this.getFlushOp(r,s,n),r):this.sourceBuffers.forEach((function(t){var e=t[0];e&&i.append(i.getFlushOp(e,s,n),e)}))},i.onFragParsed=function(t,e){var i=this,r=e.frag,s=e.part,n=[],a=s?s.elementaryStreams:r.elementaryStreams;a[J.AUDIOVIDEO]?n.push("audiovideo"):(a[J.AUDIO]&&n.push("audio"),a[J.VIDEO]&&n.push("video"));var o=function(){var t=self.performance.now();r.stats.buffering.end=t,s&&(s.stats.buffering.end=t);var e=s?s.stats:r.stats;i.hls.trigger(w.FRAG_BUFFERED,{frag:r,part:s,stats:e,id:r.type})};0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+r.type+" level: "+r.level+" sn: "+r.sn),this.blockBuffers(o,n).catch((function(t){i.warn("Fragment buffered callback "+t),i.stepOperationQueue(i.sourceBufferTypes)}))},i.onFragChanged=function(t,e){this.trimBuffers()},i.onBufferEos=function(t,e){var i,r=this;this.sourceBuffers.forEach((function(t){var i=t[0];if(i){var s=r.tracks[i];e.type&&e.type!==i||(s.ending=!0,s.ended||(s.ended=!0,r.log(i+" buffer reached EOS")))}}));var s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var e,i=t[0];return i&&!(null!=(e=r.tracks[i])&&e.ended)}))?s?(this.log("Queueing EOS"),this.blockUntilOpen((function(){r.tracksEnded();var t=r.mediaSource;t&&"open"===t.readyState?(r.log("Calling mediaSource.endOfStream()"),t.endOfStream(),r.hls.trigger(w.BUFFERED_TO_END,void 0)):t&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+t.readyState)}))):(this.tracksEnded(),this.hls.trigger(w.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()},i.tracksEnded=function(){var t=this;this.sourceBuffers.forEach((function(e){var i=e[0];if(null!==i){var r=t.tracks[i];r&&(r.ending=!1)}}))},i.onLevelUpdated=function(t,e){var i=e.details;i.fragments.length&&(this.details=i,this.updateDuration())},i.updateDuration=function(){var t=this;this.blockUntilOpen((function(){var e=t.getDurationAndRange();e&&t.updateMediaSource(e)}))},i.onError=function(t,e){if(e.details===C.BUFFER_APPEND_ERROR&&e.frag){var i,r=null==(i=e.errorAction)?void 0:i.nextAutoLevel;k(r)&&r!==e.frag.level&&this.resetAppendErrors()}},i.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},i.trimBuffers=function(){var t=this.hls,e=this.details,i=this.media;if(i&&null!==e&&this.sourceBufferCount){var r=t.config,s=i.currentTime,n=e.levelTargetDuration,a=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(k(a)&&a>=0){var o=Math.max(a,n),l=Math.floor(s/n)*n-o;this.flushBackBuffer(s,n,l)}var h=r.frontBufferFlushThreshold;if(k(h)&&h>0){var d=Math.max(r.maxBufferLength,h),u=Math.max(d,n),c=Math.floor(s/n)*n+u;this.flushFrontBuffer(s,n,c)}}},i.flushBackBuffer=function(t,e,i){var r=this;this.sourceBuffers.forEach((function(t){var e=t[0],s=t[1];if(s){var n=Ri.getBuffered(s);if(n.length>0&&i>n.start(0)){var a;r.hls.trigger(w.BACK_BUFFER_REACHED,{bufferEnd:i});var o=r.tracks[e];if(null!=(a=r.details)&&a.live)r.hls.trigger(w.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=o&&o.ended)return void r.log("Cannot flush "+e+" back buffer while SourceBuffer is in ended state");r.hls.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}}))},i.flushFrontBuffer=function(t,e,i){var r=this;this.sourceBuffers.forEach((function(e){var s=e[0],n=e[1];if(n){var a=Ri.getBuffered(n),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(i>l||t>=l&&t<=h)return;r.hls.trigger(w.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}}))},i.getDurationAndRange=function(){var t,e=this.details,i=this.mediaSource;if(!e||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){var s=Math.max(0,e.fragmentStart);return{duration:1/0,start:s,end:Math.max(s,r)}}return{duration:1/0}}var n=null==(t=this.overrides)?void 0:t.duration;if(n)return k(n)?{duration:n}:null;var a=this.media.duration;return r>(k(i.duration)?i.duration:0)&&r>a||!k(a)?{duration:r}:null},i.updateMediaSource=function(t){var e=t.duration,i=t.start,r=t.end,s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==e&&(k(e)&&this.log("Updating MediaSource duration to "+e.toFixed(3)),s.duration=e),void 0!==i&&void 0!==r&&(this.log("MediaSource duration is set to "+s.duration+". Setting seekable range to "+i+"-"+r+"."),s.setLiveSeekableRange(i,r)))},i.checkPendingTracks=function(){var t=this.bufferCodecEventsTotal,e=this.pendingTrackCount,i=this.tracks;if(this.log("checkPendingTracks (pending: "+e+" codec events expected: "+t+") "+Le(i)),this.tracksReady){var r,s=null==(r=this.transferData)?void 0:r.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}},i.bufferCreated=function(){var t=this;if(this.sourceBufferCount){var e={};this.sourceBuffers.forEach((function(i){var r=i[0],s=i[1];if(r){var n=t.tracks[r];e[r]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}})),this.hls.trigger(w.BUFFER_CREATED,{tracks:e}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(e){var i=e[0];t.executeNext(i)}))}else{var i=new Error("could not create source buffer for media codec(s)");this.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:i,reason:i.message})}},i.createSourceBuffers=function(){var t=this.tracks,e=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in t){var s=r,n=t[s];if(this.isPending(n)){var a=this.getTrackCodec(n,s),o=n.container+";codecs="+a;n.codec=a,this.log("creating sourceBuffer("+o+")"+(this.currentOp(s)?" Queued":"")+" "+Le(n));try{var l=i.addSourceBuffer(o),h=La(s),d=[s,l];e[h]=d,n.buffer=l}catch(t){var u;return this.error("error while trying to add sourceBuffer: "+t.message),this.shiftAndExecuteNext(s),null==(u=this.operationQueue)||u.removeBlockers(),delete this.tracks[s],void this.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:s,mimeType:o,parent:n.id})}this.trackSourceBuffer(s,n)}}this.bufferCreated()},i.getTrackCodec=function(t,e){var i=t.supplemental,r=t.codec;i&&("video"===e||"audiovideo"===e)&&Gt(i,"video")&&(r=Xt(r,i));var s=Qt(r,t.levelCodec);return s?"audio"===e.slice(0,5)?qt(s,this.appendSource):s:""},i.trackSourceBuffer=function(t,e){var i=this,r=e.buffer;if(r){var s=this.getTrackCodec(e,t);this.tracks[t]={buffer:r,codec:s,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",(function(t,e){var r=e.removedRanges;null!=r&&r.length&&i.hls.trigger(w.BUFFER_FLUSHED,{type:t})}))}},i.onSBUpdateStart=function(t){var e=this.currentOp(t);e&&e.onStart()},i.onSBUpdateEnd=function(t){var e;if("closed"!==(null==(e=this.mediaSource)?void 0:e.readyState)){var i=this.currentOp(t);i&&(i.onComplete(),this.shiftAndExecuteNext(t))}else this.resetBuffer(t)},i.onSBUpdateError=function(t,e){var i,r=new Error(t+" SourceBuffer error. MediaSource readyState: "+(null==(i=this.mediaSource)?void 0:i.readyState));this.error(""+r,e),this.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});var s=this.currentOp(t);s&&s.onError(r)},i.updateTimestampOffset=function(t,e,i,r,s,n){var a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log("Updating "+r+" SourceBuffer timestampOffset to "+e+" (sn: "+s+" cc: "+n+")"),t.timestampOffset=e)},i.removeExecutor=function(t,e,i){var r=this.media,s=this.mediaSource,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!r||!s||!a)return this.warn("Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(t);var o=k(r.duration)?r.duration:1/0,l=k(s.duration)?s.duration:1/0,h=Math.max(0,e),d=Math.min(i,o,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log("Removing ["+h+","+d+"] from the "+t+" SourceBuffer"),a.remove(h,d)):this.shiftAndExecuteNext(t)},i.appendExecutor=function(t,e){var i=this.tracks[e],r=null==i?void 0:i.buffer;if(!r)throw new Ea("Attempting to append to the "+e+" SourceBuffer, but it does not exist");i.ending=!1,i.ended=!1,r.appendBuffer(t)},i.blockUntilOpen=function(t){var e=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch((function(t){e.warn("SourceBuffer blocked callback "+t),e.stepOperationQueue(e.sourceBufferTypes)}));else try{t()}catch(t){this.warn("Callback run without blocking "+this.operationQueue+" "+t)}},i.isUpdating=function(){return this.sourceBuffers.some((function(t){var e=t[0],i=t[1];return e&&i.updating}))},i.isQueued=function(){var t=this;return this.sourceBuffers.some((function(e){var i=e[0];return i&&!!t.currentOp(i)}))},i.isPending=function(t){return!!t&&!t.buffer},i.blockBuffers=function(t,e){var i=this;if(void 0===e&&(e=this.sourceBufferTypes),!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);var r=this.operationQueue,s=e.map((function(t){return i.appendBlocker(t)}));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((function(e){r===i.operationQueue&&(t(),i.stepOperationQueue(i.sourceBufferTypes))}))},i.stepOperationQueue=function(t){var e=this;t.forEach((function(t){var i,r=null==(i=e.tracks[t])?void 0:i.buffer;r&&!r.updating&&e.shiftAndExecuteNext(t)}))},i.append=function(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)},i.appendBlocker=function(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)},i.currentOp=function(t){return this.operationQueue?this.operationQueue.current(t):null},i.executeNext=function(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)},i.shiftAndExecuteNext=function(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)},i.addBufferListener=function(t,e,i){var r=this.tracks[t];if(r){var s=r.buffer;if(s){var n=i.bind(this,t);r.listeners.push({event:e,listener:n}),s.addEventListener(e,n)}}},i.removeBufferListeners=function(t){var e=this.tracks[t];if(e){var i=e.buffer;i&&(e.listeners.forEach((function(t){i.removeEventListener(t.event,t.listener)})),e.listeners.length=0)}},s(e,[{key:"mediaSourceOpenOrEnded",get:function(){var t,e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}},{key:"sourceBufferTracks",get:function(){var t=this;return Object.keys(this.tracks).reduce((function(e,i){var r=t.tracks[i];return e[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e}),{})}},{key:"bufferedToEnd",get:function(){var t=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var i=e[0];if(i){var r=t.tracks[i];if(r)return!r.ended||r.ending}return!1}))}},{key:"tracksReady",get:function(){var t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var t,e,i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}},{key:"pendingTrackCount",get:function(){var t=this;return Object.keys(this.tracks).reduce((function(e,i){return e+(t.isPending(t.tracks[i])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(t,e){return t+(e[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(t){return t[0]})).filter((function(t){return!!t}))}}])}(N);function Sa(t){var e=t.querySelectorAll("source");[].slice.call(e).forEach((function(e){t.removeChild(e)}))}function Aa(t,e){var i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}function La(t){return"audio"===t?1:0}var Ra=function(){function t(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()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},e.registerListeners=function(){var t=this.hls;t.on(w.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.BUFFER_CODECS,this.onBufferCodecs,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this)},e.unregisterListener=function(){var t=this.hls;t.off(w.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.BUFFER_CODECS,this.onBufferCodecs,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this)},e.onFpsDropLevelCapping=function(t,e){var i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})},e.onMediaAttaching=function(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},e.onManifestParsed=function(t,e){var i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()},e.onLevelsUpdated=function(t,e){this.timer&&k(this.autoLevelCapping)&&this.detectPlayerSize()},e.onBufferCodecs=function(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()},e.onMediaDetaching=function(){this.stopCapping(),this.media=null},e.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var t=this.hls.levels;if(t.length){var e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log("Setting autoLevelCapping to "+i+": "+t[i].height+"p@"+t[i].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},e.getMaxLevel=function(e){var i=this,r=this.hls.levels;if(!r.length)return-1;var s=r.filter((function(t,r){return i.isLevelAllowed(t)&&r<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)},e.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},e.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e},e.isLevelAllowed=function(t){return!this.restrictedLevels.some((function(e){return t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height}))},t.getMaxLevelByMediaSize=function(t,e,i){if(null==t||!t.length)return-1;for(var r=function(t,e){return!e||t.width!==e.width||t.height!==e.height},s=t.length-1,n=Math.max(e,i),a=0;a<t.length;a+=1){var o=t[a];if((o.width>=n||o.height>=n)&&r(o,t[a+1])){s=a;break}}return s},s(t,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}}])}(),Ia={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ba={HLS:"h"},ka=function t(e,i){Array.isArray(e)&&(e=e.map((function(e){return e instanceof t?e:new t(e)}))),this.value=e,this.params=i},Da="Dict";function _a(t){return Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":"object"==typeof t?JSON.stringify(t):String(t)}function Pa(t,e,i,r){return new Error("failed to "+t+' "'+_a(e)+'" as '+i,{cause:r})}function Ca(t,e,i){return Pa("serialize",t,e,i)}var wa=function(t){this.description=t},Oa="Bare Item",xa="Boolean";function Ma(t){if("boolean"!=typeof t)throw Ca(t,xa);return t?"?1":"?0"}function Fa(t){return btoa(String.fromCharCode.apply(String,t))}var Na="Byte Sequence";function Ua(t){if(!1===ArrayBuffer.isView(t))throw Ca(t,Na);return":"+Fa(t)+":"}var Ba="Integer";function Ga(t){return t<-999999999999999||999999999999999<t}function $a(t){if(Ga(t))throw Ca(t,Ba);return t.toString()}function Ka(t){return"@"+$a(t.getTime()/1e3)}function Va(t,e){if(t<0)return-Va(-t,e);var i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){var r=Math.floor(t*i);return(r%2==0?r:r+1)/i}return Math.round(t*i)/i}var Ha="Decimal";function Ya(t){var e=Va(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ca(t,Ha);var i=e.toString();return i.includes(".")?i:i+".0"}var Wa="String",ja=/[\x00-\x1f\x7f]+/;function qa(t){if(ja.test(t))throw Ca(t,Wa);return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function Xa(t){return t.description||t.toString().slice(7,-1)}var Qa="Token";function za(t){var e=Xa(t);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Ca(e,Qa);return e}function Za(t){switch(typeof t){case"number":if(!k(t))throw Ca(t,Oa);return Number.isInteger(t)?$a(t):Ya(t);case"string":return qa(t);case"symbol":return za(t);case"boolean":return Ma(t);case"object":if(t instanceof Date)return Ka(t);if(t instanceof Uint8Array)return Ua(t);if(t instanceof wa)return za(t);default:throw Ca(t,Oa)}}var Ja="Key";function to(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Ca(t,Ja);return t}function eo(t){return null==t?"":Object.entries(t).map((function(t){var e=t[0],i=t[1];return!0===i?";"+to(e):";"+to(e)+"="+Za(i)})).join("")}function io(t){return t instanceof ka?""+Za(t.value)+eo(t.params):Za(t)}function ro(t){return"("+t.value.map(io).join(" ")+")"+eo(t.params)}function so(t,e){if(void 0===e&&(e={whitespace:!0}),"object"!=typeof t||null==t)throw Ca(t,Da);var i=t instanceof Map?t.entries():Object.entries(t),r=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map((function(t){var e=t[0],i=t[1];i instanceof ka==0&&(i=new ka(i));var r=to(e);return!0===i.value?r+=eo(i.params):(r+="=",Array.isArray(i.value)?r+=ro(i):r+=io(i)),r})).join(","+r)}function no(t,e){return so(t,e)}var ao="CMCD-Object",oo="CMCD-Request",lo="CMCD-Session",ho="CMCD-Status",uo={br:ao,ab:ao,d:ao,ot:ao,tb:ao,tpb:ao,lb:ao,tab:ao,lab:ao,url:ao,pb:oo,bl:oo,tbl:oo,dl:oo,ltc:oo,mtp:oo,nor:oo,nrr:oo,rc:oo,sn:oo,sta:oo,su:oo,ttfb:oo,ttfbb:oo,ttlb:oo,cmsdd:oo,cmsds:oo,smrt:oo,df:oo,cs:oo,ts:oo,cid:lo,pr:lo,sf:lo,sid:lo,st:lo,v:lo,msd:lo,bs:ho,bsd:ho,cdn:ho,rtp:ho,bg:ho,pt:ho,ec:ho,e:ho},co={REQUEST:oo};function fo(t){return Object.keys(t).reduce((function(e,i){var r;return null===(r=t[i])||void 0===r||r.forEach((function(t){return e[t]=i})),e}),{})}function go(t,e){var i={};if(!t)return i;var r=Object.keys(t),s=e?fo(e):{};return r.reduce((function(e,i){var r,n=uo[i]||s[i]||co.REQUEST;return(null!==(r=e[n])&&void 0!==r?r:e[n]={})[i]=t[i],e}),i)}function mo(t){return["ot","sf","st","e","sta"].includes(t)}function po(t){return"number"==typeof t?k(t):null!=t&&""!==t&&!1!==t}var vo="event";function yo(t,e){var i=new URL(t),r=new URL(e);if(i.origin!==r.origin)return t;for(var s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}var Eo=function(t){return Math.round(t)},To=function(t,e){return Array.isArray(t)?t.map((function(t){return To(t,e)})):t instanceof ka&&"string"==typeof t.value?new ka(To(t.value,e),t.params):(e.baseUrl&&(t=yo(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t)},So=function(t){return 100*Eo(t/100)},Ao={br:Eo,d:Eo,bl:So,dl:So,mtp:So,nor:function(t,e){var i=t;return e.version>=2&&(t instanceof ka&&"string"==typeof t.value?i=new ka([t]):"string"==typeof t&&(i=[t])),To(i,e)},rtp:So,tb:Eo},Lo="request",Ro="response",Io=["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"],bo=["e"],ko=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Do(t){return ko.test(t)}function _o(t){return Io.includes(t)||bo.includes(t)||Do(t)}var Po=["d","dl","nor","ot","rtp","su"];function Co(t){return Io.includes(t)||Po.includes(t)||Do(t)}var wo=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Oo(t){return Io.includes(t)||Po.includes(t)||wo.includes(t)||Do(t)}var xo,Mo=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Fo(t){return Mo.includes(t)||Do(t)}var No=((xo={})[Ro]=Oo,xo[vo]=_o,xo[Lo]=Co,xo);function Uo(t,e){void 0===e&&(e={});var i={};if(null==t||"object"!=typeof t)return i;var r=e.version||t.v||1,s=e.reportingMode||Lo,n=1===r?Fo:No[s],o=Object.keys(t).filter(n),l=e.filter;"function"==typeof l&&(o=o.filter(l));var h=s===Ro||s===vo;h&&!o.includes("ts")&&o.push("ts"),r>1&&!o.includes("v")&&o.push("v");var d=a({},Ao,e.formatters),u={version:r,reportingMode:s,baseUrl:e.baseUrl};return o.sort().forEach((function(e){var s=t[e],n=d[e];if("function"==typeof n&&(s=n(s,u)),"v"===e){if(1===r)return;s=r}"pr"==e&&1===s||(h&&"ts"===e&&!k(s)&&(s=Date.now()),po(s)&&(mo(e)&&"string"==typeof s&&(s=new wa(s)),i[e]=s))})),i}function Bo(t,e){void 0===e&&(e={});var i={};if(!t)return i;var r=go(Uo(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(r).reduce((function(t,e){var i=e[0],r=no(e[1],{whitespace:!1});return r&&(t[i]=r),t}),i)}function Go(t,e,i){return a(t,Bo(e,i))}var $o="CMCD";function Ko(t,e){return void 0===e&&(e={}),t?no(Uo(t,e),{whitespace:!1}):""}function Vo(t,e){if(void 0===e&&(e={}),!t)return"";var i=Ko(t,e);return encodeURIComponent(i)}function Ho(t,e){if(void 0===e&&(e={}),!t)return"";var i=Vo(t,e);return $o+"="+i}var Yo=/CMCD=[^&#]+/;function Wo(t,e,i){var r=Ho(e,i);if(!r)return t;if(Yo.test(t))return t.replace(Yo,r);var s=t.includes("?")?"&":"?";return""+t+s+r}var jo=function(){function t(t){var e=this;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=function(){e.initialized&&(e.starved=!0),e.buffering=!0},this.onPlaying=function(){e.initialized||(e.initialized=!0),e.buffering=!1},this.applyPlaylistData=function(t){try{e.apply(t,{ot:Ia.MANIFEST,su:!e.initialized})}catch(t){e.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(t){try{var i=t.frag,r=t.part,s=e.hls.levels[i.level],n=e.getObjectType(i),a={d:1e3*(r||i).duration,ot:n};n!==Ia.VIDEO&&n!==Ia.AUDIO&&n!=Ia.MUXED||(a.br=s.bitrate/1e3,a.tb=e.getTopBandwidth(n)/1e3,a.bl=e.getBufferLength(n));var o=r?e.getNextPart(r):e.getNextFrag(i);null!=o&&o.url&&o.url!==i.url&&(a.nor=o.url),e.apply(t,a)}catch(t){e.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;var i=this.config=t.config,r=i.cmcd;null!=r&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||t.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHED,this.onMediaDetached,this),t.on(w.BUFFER_CREATED,this.onBufferCreated,this)},e.unregisterListeners=function(){var t=this.hls;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHED,this.onMediaDetached,this),t.off(w.BUFFER_CREATED,this.onBufferCreated,this)},e.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null},e.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},e.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},e.onBufferCreated=function(t,e){var i,r;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer},e.createData=function(){var t;return{v:1,sf:ba.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},e.apply=function(t,e){void 0===e&&(e={}),a(e,this.createData());var i=e.ot===Ia.INIT||e.ot===Ia.VIDEO||e.ot===Ia.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);var r=this.includeKeys;r&&(e=Object.keys(e).reduce((function(t,i){return r.includes(i)&&(t[i]=e[i]),t}),{}));var s={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),Go(t.headers,e,s)):t.url=Wo(t.url,e,s)},e.getNextFrag=function(t){var e,i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){var r=t.sn-i.startSN;return i.fragments[r+1]}},e.getNextPart=function(t){var e,i=t.index,r=t.fragment,s=null==(e=this.hls.levels[r.level])||null==(e=e.details)?void 0:e.partList;if(s)for(var n=r.sn,a=s.length-1;a>=0;a--){var o=s[a];if(o.index===i&&o.fragment.sn===n)return s[a+1]}},e.getObjectType=function(t){var e=t.type;return"subtitle"===e?Ia.TIMED_TEXT:"initSegment"===t.sn?Ia.INIT:"audio"===e?Ia.AUDIO:"main"===e?this.hls.audioTracks.length?Ia.VIDEO:Ia.MUXED:void 0},e.getTopBandwidth=function(t){var e,i=0,r=this.hls;if(t===Ia.AUDIO)e=r.audioTracks;else{var s=r.maxAutoLevel,n=s>-1?s+1:r.levels.length;e=r.levels.slice(0,n)}return e.forEach((function(t){t.bitrate>i&&(i=t.bitrate)})),i>0?i:NaN},e.getBufferLength=function(t){var e=this.media,i=t===Ia.AUDIO?this.audioBuffer:this.videoBuffer;return i&&e?1e3*Ri.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len:NaN},e.createPlaylistLoader=function(){var t=this.config.pLoader,e=this.applyPlaylistData,i=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new i(t)}var r=t.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(t,i,r){e(t),this.loader.load(t,i,r)},s(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e.createFragmentLoader=function(){var t=this.config.fLoader,e=this.applyFragmentData,i=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new i(t)}var r=t.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(t,i,r){e(t),this.loader.load(t,i,r)},s(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t}(),qo=3e5,Xo=function(t){function e(e){var i;return(i=t.call(this,"content-steering",e.logger)||this).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=e,i.registerListeners(),i}l(e,t);var i=e.prototype;return i.registerListeners=function(){var t=this.hls;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t&&(t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.ERROR,this.onError,this))},i.pathways=function(){return(this.levels||[]).reduce((function(t,e){return-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t}),[])},i.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}},i.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},i.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},i.removeLevel=function(t){var e=this.levels;e&&(this.levels=e.filter((function(e){return e!==t})))},i.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},i.onManifestLoaded=function(t,e){var i=e.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())},i.onManifestParsed=function(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks},i.onError=function(t,e){var i=e.errorAction;if((null==i?void 0:i.action)===ze.SendAlternateToPenaltyBox&&i.flags===Ze.MoveAllAlternatesMatchingHost){var r=this.levels,s=this._pathwayPriority,n=this.pathwayId;if(e.context){var a=e.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&r?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&r&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n),e.details!==C.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn("Could not resolve "+e.details+' ("'+e.error.message+'") with content-steering for Pathway: '+n+" levels: "+(r?r.length:r)+" priorities: "+Le(s)+" penalized: "+Le(this.penalizedPathways)):i.resolved=!0}},i.filterParsedLevels=function(t){this.levels=t;var e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){var i=t[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+i+'"'),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log("Found "+e.length+"/"+t.length+' levels in Pathway "'+this.pathwayId+'"'),e},i.getLevelsForPathway=function(t){return null===this.levels?[]:this.levels.filter((function(e){return t===e.pathwayId}))},i.updatePathwayPriority=function(t){var e;this._pathwayPriority=t;var i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((function(t){r-i[t]>qo&&delete i[t]}));for(var s=0;s<t.length;s++){var n=t[s];if(!(n in i)){if(n===this.pathwayId)return;var a=this.hls.nextLoadLevel,o=this.hls.levels[a];if((e=this.getLevelsForPathway(n)).length>0){this.log('Setting Pathway to "'+n+'"'),this.pathwayId=n,Ur(e),this.hls.trigger(w.LEVELS_UPDATED,{levels:e});var l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=a);break}}}},i.getPathwayForGroupId=function(t,e,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),s=0;s<r.length;s++)if(e===O.AUDIO_TRACK&&r[s].hasAudioGroup(t)||e===O.SUBTITLE_TRACK&&r[s].hasSubtitleGroup(t))return r[s].pathwayId;return i},i.clonePathways=function(t){var e=this,i=this.levels;if(i){var r={},s={};t.forEach((function(t){var n=t.ID,a=t["BASE-ID"],o=t["URI-REPLACEMENT"];if(!i.some((function(t){return t.pathwayId===n}))){var l=e.getLevelsForPathway(a).map((function(t){var e=new wi(t.attrs);e["PATHWAY-ID"]=n;var i=e.AUDIO&&e.AUDIO+"_clone_"+n,a=e.SUBTITLES&&e.SUBTITLES+"_clone_"+n;i&&(r[e.AUDIO]=i,e.AUDIO=i),a&&(s[e.SUBTITLES]=a,e.SUBTITLES=a);var l=zo(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new ye({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(var d=1;d<t.audioGroups.length;d++)h.addGroupId("audio",t.audioGroups[d]+"_clone_"+n);if(t.subtitleGroups)for(var u=1;u<t.subtitleGroups.length;u++)h.addGroupId("text",t.subtitleGroups[u]+"_clone_"+n);return h}));i.push.apply(i,l),Qo(e.audioTracks,r,o,n),Qo(e.subtitleTracks,s,o,n)}}))}},i.loadSteeringManifest=function(t){var e,i=this,r=this.hls.config,s=r.loader;this.loader&&this.loader.destroy(),this.loader=new s(r);try{e=new self.URL(t)}catch(e){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+t)}if("data:"!==e.protocol){var n=0|(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate);e.searchParams.set("_HLS_pathway",this.pathwayId),e.searchParams.set("_HLS_throughput",""+n)}var a={responseType:"json",url:e.href},o=r.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},d={onSuccess:function(t,r,s,n){i.log('Loaded steering manifest: "'+e+'"');var a=t.data;if(1===(null==a?void 0:a.VERSION)){i.updated=performance.now(),i.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,e).href}catch(t){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}i.scheduleRefresh(i.uri||s.url),l&&i.clonePathways(l);var d={steeringManifest:a,url:e.toString()};i.hls.trigger(w.STEERING_MANIFEST_LOADED,d),h&&i.updatePathwayPriority(h)}else i.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(t,e,r,s){if(i.log("Error loading steering manifest: "+t.code+" "+t.text+" ("+e.url+")"),i.stopLoad(),410===t.code)return i.enabled=!1,void i.log("Steering manifest "+e.url+" no longer available");var n=1e3*i.timeToLoad;if(429!==t.code)i.scheduleRefresh(i.uri||e.url,n);else{var a=i.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(n=1e3*parseFloat(o))}i.log("Steering manifest "+e.url+" rate limited")}},onTimeout:function(t,e,r){i.log("Timeout loading steering manifest ("+e.url+")"),i.scheduleRefresh(i.uri||e.url)}};this.log("Requesting steering manifest: "+e),this.loader.load(a,h,d)},i.scheduleRefresh=function(t,e){var i=this;void 0===e&&(e=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var e,r=null==(e=i.hls)?void 0:e.media;!r||r.ended?i.scheduleRefresh(t,1e3*i.timeToLoad):i.loadSteeringManifest(t)}),e)},s(e,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(t){this.updatePathwayPriority(t)}}])}(N);function Qo(t,e,i,r){t&&Object.keys(e).forEach((function(s){var n=t.filter((function(t){return t.groupId===s})).map((function(t){var n=a({},t);return n.details=void 0,n.attrs=new wi(n.attrs),n.url=n.attrs.URI=zo(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=r,n}));t.push.apply(t,n)}))}function zo(t,e,i,r){var s,n=r.HOST,a=r.PARAMS,o=r[i];e&&(s=null==o?void 0:o[e])&&(t=s);var l=new self.URL(t);return n&&!s&&(l.host=n),a&&Object.keys(a).sort().forEach((function(t){t&&l.searchParams.set(t,a[t])})),l.href}function Zo(t,e,i){Jo(t,e,i),t.addEventListener(e,i)}function Jo(t,e,i){t.removeEventListener(e,i)}var tl=function(t){function e(i){var r;return(r=t.call(this,"eme",i.logger)||this).hls=void 0,r.config=void 0,r.media=null,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.mediaKeys=null,r.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],r.onMediaEncrypted=function(t){var e=t.initDataType,i=t.initData,s='"'+t.type+'" event: init data type: "'+e+'"';if(r.debug(s),null!==i){if(!r.keyFormatPromise){var n=Object.keys(r.keySystemAccessPromises);n.length||(n=zi(r.config));var a=n.map(Qi).filter((function(t){return!!t}));r.keyFormatPromise=r.getKeyFormatPromise(a)}r.keyFormatPromise.then((function(n){var a=Xi(n);if("sinf"===e&&a===ji.FAIRPLAY){var o;try{var l=ht(new Uint8Array(i)),h=It($i(JSON.parse(l).sinf));if(!h)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(h.subarray(8,24))}catch(t){return void r.warn(s+" Failed to parse sinf: "+t)}for(var d,u=Q.hexDump(o),c=r,f=c.keyIdToKeySessionPromise,g=c.mediaKeySessions,m=f[u],p=function(){var t=g[v],s=t.decryptdata;if(!s.keyId)return 0;var n=Q.hexDump(s.keyId);return u===n||-1!==s.uri.replace(/-/g,"").indexOf(u)?(m=f[n])?(s.pssh||(delete f[n],s.pssh=new Uint8Array(i),s.keyId=o,(m=f[u]=m.then((function(){return r.generateRequestWithPreferredKeySession(t,e,i,"encrypted-event-key-match")}))).catch((function(t){return r.handleError(t)}))),1):0:void 0},v=0;v<g.length&&(0===(d=p())||1!==d);v++);m||r.handleError(new Error("Key ID "+u+" not encountered in playlist. Key-system sessions "+g.length+"."))}else r.log('Ignoring "'+t.type+'" event with init data type: "'+e+'" for selected key-system '+a)})).catch((function(t){return r.handleError(t)}))}},r.onWaitingForKey=function(t){r.log('"'+t.type+'" event')},r.hls=i,r.config=i.config,r.registerListeners(),r}l(e,t);var i=e.prototype;return i.destroy=function(){this.onDestroying(),this.onMediaDetached();var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onWaitingForKey=null},i.registerListeners=function(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(w.DESTROYING,this.onDestroying,this)},i.unregisterListeners=function(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(w.DESTROYING,this.onDestroying,this)},i.getLicenseServerUrl=function(t){var e=this.config,i=e.drmSystems,r=e.widevineLicenseUrl,s=i[t];return s?s.licenseUrl:t===ji.WIDEVINE&&r?r:void 0},i.getLicenseServerUrlOrThrow=function(t){var e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error('no license server URL configured for key-system "'+t+'"');return e},i.getServerCertificateUrl=function(t){var e=this.config.drmSystems[t];if(e)return e.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+t+'"]')},i.attemptKeySystemAccess=function(t){var e=this,i=this.hls.levels,r=function(t,e,i){return!!t&&i.indexOf(t)===e},s=i.map((function(t){return t.audioCodec})).filter(r),n=i.map((function(t){return t.videoCodec})).filter(r);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((function(i,r){var a=function(t){var o=t.shift();e.getMediaKeysPromise(o,s,n).then((function(t){return i({keySystem:o,mediaKeys:t})})).catch((function(e){t.length?a(t):r(e instanceof el?e:new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};a(t)}))},i.requestMediaKeySystemAccess=function(t,e){var i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function "+i;return null===Ji&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(r))}return i(t,e)},i.getMediaKeysPromise=function(t,e,i){var r=this,s=tr(t,e,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t],a=null==n?void 0:n.keySystemAccess;if(!a){this.log('Requesting encrypted media "'+t+'" key-system access with config: '+Le(s)),a=this.requestMediaKeySystemAccess(t,s);var o=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch((function(e){r.log('Failed to obtain access to key-system "'+t+'": '+e)})),a.then((function(e){r.log('Access for key-system "'+e.keySystem+'" obtained');var i=r.fetchServerCertificate(t);return r.log('Create media-keys for "'+t+'"'),o.mediaKeys=e.createMediaKeys().then((function(e){return r.log('Media-keys created for "'+t+'"'),o.hasMediaKeys=!0,i.then((function(i){return i?r.setMediaKeysServerCertificate(e,t,i):e}))})),o.mediaKeys.catch((function(e){r.error('Failed to create media-keys for "'+t+'"}: '+e)})),o.mediaKeys}))}return a.then((function(){return n.mediaKeys}))},i.createMediaKeySessionContext=function(t){var e=t.decryptdata,i=t.keySystem,r=t.mediaKeys;this.log('Creating key-system session "'+i+'" keyId: '+Q.hexDump(e.keyId||[]));var s=r.createSession(),n={decryptdata:e,keySystem:i,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n},i.renewKeySession=function(t){var e=t.decryptdata;if(e.pssh){var i=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)},i.getKeyIdString=function(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return Q.hexDump(t.keyId)},i.updateKeySession=function(t,e){var i,r=t.mediaKeysSession;return this.log('Updating key-session "'+r.sessionId+'" for keyID '+Q.hexDump((null==(i=t.decryptdata)?void 0:i.keyId)||[])+"\n } (data length: "+(e?e.byteLength:e)+")"),r.update(e)},i.getSelectedKeySystemFormats=function(){var t=this;return Object.keys(this.keySystemAccessPromises).map((function(e){return{keySystem:e,hasMediaKeys:t.keySystemAccessPromises[e].hasMediaKeys}})).filter((function(t){return!!t.hasMediaKeys})).map((function(t){return Qi(t.keySystem)})).filter((function(t){return!!t}))},i.getKeySystemAccess=function(t){var e=this;return this.getKeySystemSelectionPromise(t).then((function(t){var i=t.keySystem,r=t.mediaKeys;return e.attemptSetMediaKeys(i,r)}))},i.selectKeySystem=function(t){var e=this;return new Promise((function(i,r){return e.getKeySystemSelectionPromise(t).then((function(t){var e=t.keySystem,s=Qi(e);s?i(s):r(new Error('Unable to find format for key-system "'+e+'"'))})).catch(r)}))},i.selectKeySystemFormat=function(t){var 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},i.getKeyFormatPromise=function(t){var e=zi(this.config),i=t.map(Xi).filter((function(t){return!!t&&-1!==e.indexOf(t)}));return this.selectKeySystem(i)},i.loadKey=function(t){var e=this,i=t.keyInfo.decryptdata,r=this.getKeyIdString(i),s="(keyId: "+r+' format: "'+i.keyFormat+'" method: '+i.method+" uri: "+i.uri+")";this.log("Starting session for key "+s);var n=this.keyIdToKeySessionPromise[r];return n||(n=this.getKeySystemForKeyPromise(i).then((function(r){var n=r.keySystem,a=r.mediaKeys;return e.throwIfDestroyed(),e.log("Handle encrypted media sn: "+t.frag.sn+" "+t.frag.type+": "+t.frag.level+" using key "+s),e.attemptSetMediaKeys(n,a).then((function(){return e.throwIfDestroyed(),e.createMediaKeySessionContext({keySystem:n,mediaKeys:a,decryptdata:i})}))})),(this.keyIdToKeySessionPromise[r]=n.then((function(t){var r="cenc",s=i.pssh?i.pssh.buffer:null;return e.generateRequestWithPreferredKeySession(t,r,s,"playlist-key")}))).catch((function(t){return e.handleError(t)}))),n},i.throwIfDestroyed=function(t){if(!this.hls)throw new Error("invalid state")},i.handleError=function(t){this.hls&&(this.error(t.message),t instanceof el?this.hls.trigger(w.ERROR,t.data):this.hls.trigger(w.ERROR,{type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))},i.getKeySystemForKeyPromise=function(t){var e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){var r=Xi(t.keyFormat),s=r?[r]:zi(this.config);return this.attemptKeySystemAccess(s)}return i},i.getKeySystemSelectionPromise=function(t){if(t.length||(t=zi(this.config)),0===t.length)throw new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+Le({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(t)},i.attemptSetMediaKeys=function(t,e){var i=this;if(this.mediaKeys===e)return Promise.resolve();var r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+t+'"');var s=Promise.all(r).then((function(){if(!i.media)throw i.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return i.media.setMediaKeys(e)}));return this.mediaKeys=e,this.setMediaKeysQueue.push(s),s.then((function(){i.log('Media-keys set for "'+t+'"'),r.push(s),i.setMediaKeysQueue=i.setMediaKeysQueue.filter((function(t){return-1===r.indexOf(t)}))}))},i.generateRequestWithPreferredKeySession=function(t,e,i,r){var s,n=this,a=null==(s=this.config.drmSystems)||null==(s=s[t.keySystem])?void 0:s.generateRequest;if(a)try{var o=a.call(this.hls,e,i,t);if(!o)throw new Error("Invalid response from configured generateRequest filter");e=o.initDataType,i=o.initData?o.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){var l;if(this.warn(t.message),null!=(l=this.hls)&&l.config.debug)throw t}if(null===i)return this.log('Skipping key-session request for "'+r+'" (no initData)'),Promise.resolve(t);var h=this.getKeyIdString(t.decryptdata);this.log('Generating key-session request for "'+r+'": '+h+" (init data type: "+e+" length: "+(i?i.byteLength:null)+")");var d=new L,u=t._onmessage=function(e){var i=t.mediaKeysSession;if(i){var r=e.messageType,s=e.message;n.log('"'+r+'" message event for session "'+i.sessionId+'" message size: '+s.byteLength),"license-request"===r||"license-renewal"===r?n.renewLicense(t,s).catch((function(t){d.eventNames().length?d.emit("error",t):n.handleError(t)})):"license-release"===r?t.keySystem===ji.FAIRPLAY&&(n.updateKeySession(t,Ki("acknowledged")),n.removeSession(t)):n.warn('unhandled media key message type "'+r+'"')}else d.emit("error",new Error("invalid state"))},c=t._onkeystatuseschange=function(e){if(t.mediaKeysSession){n.onKeyStatusChange(t);var i=t.keyStatus;d.emit("keyStatus",i),"expired"===i&&(n.warn(t.keySystem+" expired for key "+h),n.renewKeySession(t))}else d.emit("error",new Error("invalid state"))};Zo(t.mediaKeysSession,"message",u),Zo(t.mediaKeysSession,"keystatuseschange",c);var f=new Promise((function(t,e){d.on("error",e),d.on("keyStatus",(function(i){i.startsWith("usable")?t():"output-restricted"===i?e(new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?e(new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},'key status changed to "'+i+'"')):"expired"===i?e(new Error("key expired while generating request")):n.warn('unhandled key status change "'+i+'"')}))}));return t.mediaKeysSession.generateRequest(e,i).then((function(){var e;n.log('Request generated for key-session "'+(null==(e=t.mediaKeysSession)?void 0:e.sessionId)+'" keyId: '+h)})).catch((function(t){throw new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},"Error generating key-session request: "+t)})).then((function(){return f})).catch((function(e){throw d.removeAllListeners(),n.removeSession(t),e})).then((function(){return d.removeAllListeners(),t}))},i.onKeyStatusChange=function(t){var e=this;t.mediaKeysSession.keyStatuses.forEach((function(i,r){if("string"==typeof r&&"object"==typeof i){var s=r;r=i,i=s}e.log('key status change "'+i+'" for keyStatuses keyId: '+Q.hexDump("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))+" session keyId: "+Q.hexDump(new Uint8Array(t.decryptdata.keyId||[]))+" uri: "+t.decryptdata.uri),t.keyStatus=i}))},i.fetchServerCertificate=function(t){var e=this.config,i=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log('Fetching server certificate for "'+t+'"'),new Promise((function(s,n){var a={responseType:"arraybuffer",url:r},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(t,e,i,r){s(t.data)},onError:function(e,i,s,o){n(new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:c({url:a.url,data:void 0},e)},'"'+t+'" certificate request failed ('+r+"). Status: "+e.code+" ("+e.text+")"))},onTimeout:function(e,i,s){n(new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},'"'+t+'" certificate request timed out ('+r+")"))},onAbort:function(t,e,i){n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()},i.setMediaKeysServerCertificate=function(t,e,i){var r=this;return new Promise((function(s,n){t.setServerCertificate(i).then((function(n){r.log("setServerCertificate "+(n?"success":"not supported by CDM")+" ("+(null==i?void 0:i.byteLength)+') on "'+e+'"'),s(t)})).catch((function(t){n(new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))},i.renewLicense=function(t,e){var i=this;return this.requestLicense(t,new Uint8Array(e)).then((function(e){return i.updateKeySession(t,new Uint8Array(e)).catch((function(t){throw new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))}))},i.unpackPlayReadyKeyMessage=function(t,e){var i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;var r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0)for(var n,a=0,o=s.length;a<o;a++){var l,h,d=null==(l=(n=s[a]).querySelector("name"))?void 0:l.textContent,u=null==(h=n.querySelector("value"))?void 0:h.textContent;d&&u&&t.setRequestHeader(d,u)}var c=r.querySelector("Challenge"),f=null==c?void 0:c.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return Ki(atob(f))},i.setupLicenseXHR=function(t,e,i,r){var s=this,n=this.config.licenseXhrSetup;return n?Promise.resolve().then((function(){if(!i.decryptdata)throw new Error("Key removed");return n.call(s.hls,t,e,i,r)})).catch((function(a){if(!i.decryptdata)throw a;return t.open("POST",e,!0),n.call(s.hls,t,e,i,r)})).then((function(i){return t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:i||r}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))},i.requestLicense=function(t,e){var i=this,r=this.config.keyLoadPolicy.default;return new Promise((function(s,n){var a=i.getLicenseServerUrlOrThrow(t.keySystem);i.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=i.config.licenseResponseCallback;if(h)try{l=h.call(i.hls,o,a,t)}catch(t){i.error(t)}s(l)}else{var d=r.errorRetry,u=d?d.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>u||o.status>=400&&o.status<500)n(new el({type:P.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+a+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=u-i._requestLicenseFailureCount+1;i.warn("Retrying license request, "+c+" attempts left"),i.requestLicense(t,e).then(s,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,i.setupLicenseXHR(o,a,t,e).then((function(e){var r=e.xhr,s=e.licenseChallenge;t.keySystem==ji.PLAYREADY&&(s=i.unpackPlayReadyKeyMessage(r,s)),r.send(s)}))}))},i.onDestroying=function(){this.unregisterListeners(),this._clear()},i.onMediaAttached=function(t,e){if(this.config.emeEnabled){var i=e.media;this.media=i,Zo(i,"encrypted",this.onMediaEncrypted),Zo(i,"waitingforkey",this.onWaitingForKey)}},i.onMediaDetached=function(){var t=this.media;t&&(Jo(t,"encrypted",this.onMediaEncrypted),Jo(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)},i._clear=function(){var t,i=this;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.mediaKeys||this.mediaKeySessions.length){var r=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,nr.clearKeyUriToKeyIdMap();var n=s.length;e.CDMCleanupPromise=Promise.all(s.map((function(t){return i.removeSession(t)})).concat(null==r||null==(t=r.setMediaKeys(null))?void 0:t.catch((function(t){var e;i.log("Could not clear media keys: "+t),null==(e=i.hls)||e.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+t)})})))).catch((function(t){var e;i.log("Could not close sessions and clear media keys: "+t),null==(e=i.hls)||e.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+t)})})).then((function(){n&&i.log("finished closing key sessions and clearing media keys")}))}},i.onManifestLoading=function(){this.keyFormatPromise=null},i.onManifestLoaded=function(t,e){var i=e.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce((function(t,e){return-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t}),[]);this.log("Selecting key-system from session-keys "+r.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(r)}},i.removeSession=function(t){var e=this,i=t.mediaKeysSession,r=t.licenseXhr;if(i){this.log("Remove licenses and keys and close session "+i.sessionId),t._onmessage&&(i.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;var s=this.mediaKeySessions.indexOf(t);return s>-1&&this.mediaKeySessions.splice(s,1),(ir(this.config.drmSystemOptions)?new Promise((function(t,e){self.setTimeout((function(){return e(new Error("MediaKeySession.remove() timeout"))}),8e3),i.remove().then(t)})):Promise.resolve()).catch((function(t){var i;e.log("Could not remove session: "+t),null==(i=e.hls)||i.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+t)})})).then((function(){return i.close()})).catch((function(t){var i;e.log("Could not close session: "+t),null==(i=e.hls)||i.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+t)})}))}},e}(N);tl.CDMCleanupPromise=void 0;var el=function(t){function e(e,i){var r;return(r=t.call(this,i)||this).data=void 0,e.error||(e.error=new Error(i)),r.data=e,e.err=e.error,r}return l(e,t),e}(p(Error)),il=function(){function t(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()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(w.MEDIA_DETACHING,this.onMediaDetaching,this)},e.unregisterListeners=function(){this.hls.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(w.MEDIA_DETACHING,this.onMediaDetaching,this)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var i=this.hls.config;if(i.capLevelOnFPSDrop){var r=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}},e.onMediaDetaching=function(){this.media=null},e.checkFPS=function(t,e,i){var r=performance.now();if(e){if(this.lastTime){var s=r-this.lastTime,n=i-this.lastDroppedFrames,a=e-this.lastDecodedFrames,o=1e3*n/s,l=this.hls;if(l.trigger(w.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){var h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=h)&&(h-=1,l.trigger(w.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}();function rl(t){for(var e=5381,i=t.length;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}var sl=.025,nl=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function al(t,e,i){return t.identifier+"-"+(i+1)+"-"+rl(e)}var ol=function(){function t(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)}var e=t.prototype;return e.setDateRange=function(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)},e.reset=function(){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)},e.isAssetPastPlayoutLimit=function(t){var e;if(t>0&&t>=this.assetList.length)return!0;var i=this.playoutLimit;return!(t<=0||isNaN(i))&&(0===i||((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i)},e.findAssetIndex=function(t){return this.assetList.indexOf(t)},e.toString=function(){return ul(this)},s(t,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var t=this.dateRange.startTime;if(this.snapOptions.out){var e=this.dateRange.tagAnchor;if(e)return ll(t,e)}return t}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var t=this.dateRange.tagAnchor;if(t){var e=this.dateRange.startTime;return e-ll(e,t)<.1}return!1}},{key:"resumptionOffset",get:function(){var t=this.resumeOffset,e=k(t)?t:this.duration;return this.cumulativeDuration+e}},{key:"resumeTime",get:function(){var t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var e=this.resumeAnchor;if(e)return ll(t,e)}return t}},{key:"appendInPlace",get:function(){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)<sl))},set:function(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(t){this._timelineStart=t}},{key:"duration",get:function(){var t,e=this.playoutLimit;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t},set:function(t){this._duration=t}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?nl.Range:nl.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}}])}();function ll(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<sl)?e.start:e.start+e.duration}function hl(t,e,i){var r=new self.URL(t,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",e),r}function dl(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function ul(t){return'["'+t.identifier+'" '+(t.cue.pre?"<pre>":t.cue.post?"<post>":"")+t.timelineStart.toFixed(2)+"-"+t.resumeTime.toFixed(2)+"]"}function cl(t){var e=t.timelineStart,i=t.duration||0;return'["'+t.identifier+'" '+e.toFixed(2)+"-"+(e+i).toFixed(2)+"]"}var fl=function(){function t(t,e,i,r){var s=this;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=function(){s.reachedPlayout(s.currentTime)&&s.hls&&s.hls.trigger(w.PLAYOUT_LIMIT_REACHED,{})};var n=this.hls=new t(e);this.interstitial=i,this.assetItem=r;var a=function(){s.hasDetails=!0};n.once(w.LEVEL_LOADED,a),n.once(w.AUDIO_TRACK_LOADED,a),n.once(w.SUBTITLE_TRACK_LOADED,a),n.on(w.MEDIA_ATTACHING,(function(t,e){var i=e.media;s.removeMediaListeners(),s.mediaAttached=i,s.interstitial.playoutLimit&&(i.addEventListener("timeupdate",s.checkPlayout),s.appendInPlace&&n.on(w.BUFFER_APPENDED,(function(){var t=s.bufferedEnd;s.reachedPlayout(t)&&(s._bufferedEosTime=t,n.trigger(w.BUFFERED_TO_END,void 0))})))}))}var e=t.prototype;return e.loadSource=function(){var t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{var e=this.assetItem.uri;try{e=hl(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}},e.bufferedInPlaceToEnd=function(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;var i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=Ri.bufferInfo(t,r,0);return this.getAssetTime(s.end)>=i-.02},e.reachedPlayout=function(t){var e=this.interstitial.playoutLimit;return this.startOffset+t>=e},e.getAssetTime=function(t){var e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)},e.removeMediaListeners=function(){var t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))},e.bufferSnapShot=function(){var t;this.mediaAttached&&null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},e.destroy=function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null},e.attachMedia=function(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)},e.detachMedia=function(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()},e.resumeBuffering=function(){var t;null==(t=this.hls)||t.resumeBuffering()},e.pauseBuffering=function(){var t;null==(t=this.hls)||t.pauseBuffering()},e.transferMedia=function(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null},e.resetDetails=function(){var t=this.hls;if(t&&this.hasDetails){t.stopLoad();var e=function(t){return delete t.details};t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}},e.on=function(t,e,i){var r;null==(r=this.hls)||r.on(t,e)},e.once=function(t,e,i){var r;null==(r=this.hls)||r.once(t,e)},e.off=function(t,e,i){var r;null==(r=this.hls)||r.off(t,e)},e.toString=function(){var t;return"HlsAssetPlayer: "+cl(this.assetItem)+" "+(null==(t=this.hls)?void 0:t.sessionId)+" "+(this.appendInPlace?"append-in-place":"")},s(t,[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"destroyed",get:function(){var t;return!(null!=(t=this.hls)&&t.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var t;return(null==(t=this.hls)?void 0:t.media)||null}},{key:"bufferedEnd",get:function(){var t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var e=Ri.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}},{key:"currentTime",get:function(){var t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}},{key:"duration",get:function(){var t=this.assetItem.duration;if(!t)return 0;var e=this.interstitial.playoutLimit;if(e){var i=e-this.startOffset;if(i>0&&i<t)return i}return t}},{key:"remaining",get:function(){var t=this.duration;return t?Math.max(0,t-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0},set:function(t){var e=this.timelineOffset;if(t!==e){var i=t-e;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}}])}(),gl=.033,ml=function(t){function e(e,i){var r;return(r=t.call(this,"interstitials-sched",i)||this).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=e,r}l(e,t);var i=e.prototype;return i.destroy=function(){this.reset(),this.onScheduleUpdate=null},i.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(t){return t.reset()})),this.events=this.items=null},i.resetErrorsInRange=function(t,e){return this.events?this.events.reduce((function(i,r){return t<=r.startOffset&&e>r.startOffset?(delete r.error,i+1):i}),0):0},i.getEvent=function(t){return t&&this.eventMap[t]||null},i.hasEvent=function(t){return t in this.eventMap},i.findItemIndex=function(t,e){if(t.event)return this.findEventIndex(t.event.identifier);var i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i},i.findItemIndexAtTime=function(t,e){var i=this.items;if(i)for(var r=0;r<i.length;r++){var s=i[r];if(e&&"primary"!==e&&(s=s[e]),t===s.start||t>s.start&&t<s.end)return r}return-1},i.findJumpRestrictedIndex=function(t,e){var i=this.items;if(i)for(var r=t;r<=e&&i[r];r++){var s=i[r].event;if(null!=s&&s.restrictions.jump&&!s.appendInPlace)return r}return-1},i.findEventIndex=function(t){var e=this.items;if(e)for(var i=e.length;i--;){var r;if((null==(r=e[i].event)?void 0:r.identifier)===t)return i}return-1},i.findAssetIndex=function(t,e){var i=t.assetList,r=i.length;if(r>1)for(var s=0;s<r;s++){var n=i[s];if(!n.error){var a=n.timelineStart;if(e===a||e>a&&(e<a+(n.duration||0)||s===r-1))return s}}return 0},i.parseInterstitialDateRanges=function(t,e){var i=this,r=t.main.details,s=r.dateRanges,n=this.events,a=this.parseDateRanges(s,{url:r.url},e),o=Object.keys(s),l=n?n.filter((function(t){return!o.includes(t.identifier)})):[];a.length&&a.sort((function(t,e){var i=t.cue.pre,r=t.cue.post,s=e.cue.pre,n=e.cue.post;if(i&&!s)return-1;if(s&&!i)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(i||s||r||n)){var a=t.startTime,o=e.startTime;if(a!==o)return a-o}return t.dateRange.tagOrder-e.dateRange.tagOrder})),this.events=a,l.forEach((function(t){i.removeEvent(t)})),this.updateSchedule(t,l)},i.updateSchedule=function(t,e,i){void 0===e&&(e=[]),void 0===i&&(i=!1);var r=this.events||[];if(r.length||e.length||this.length<2){var s=this.items,n=this.parseSchedule(r,t);(i||e.length||(null==s?void 0:s.length)!==n.length||n.some((function(t,e){return Math.abs(t.playout.start-s[e].playout.start)>.005||Math.abs(t.playout.end-s[e].playout.end)>.005})))&&(this.items=n,this.onScheduleUpdate(e,s))}},i.parseDateRanges=function(t,e,i){for(var r=[],s=Object.keys(t),n=0;n<s.length;n++){var a=s[n],o=t[a];if(o.isInterstitial){var l=this.eventMap[a];l?l.setDateRange(o):(l=new ol(o,e),this.eventMap[a]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r},i.parseSchedule=function(t,e){var i=[],r=e.main.details,s=r.live?1/0:r.edge,n=0;if((t=t.filter((function(t){return!(t.error||t.cue.once&&t.hasPlayed)}))).length){this.resolveOffsets(t,e);var a=0,o=0;if(t.forEach((function(e,r){var l=e.cue.pre,h=e.cue.post,d=t[r-1]||null,u=e.appendInPlace,c=h?s:e.startOffset,f=e.duration,g=e.timelineOccupancy===nl.Range?f:0,m=e.resumptionOffset,p=(null==d?void 0:d.startTime)===c,v=c+e.cumulativeDuration,y=u?v+f:c+m;if(l||!h&&c<=0){var E=o;o+=g,e.timelineStart=v;var T=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:T,end:n},integrated:{start:E,end:o}})}else{if(!(c<=s))return;if(!p){var S=c-a;if(S>gl){var A=a,L=o;o+=S;var R=n;n+=S;var I={previousEvent:t[r-1]||null,nextEvent:e,start:A,end:A+S,playout:{start:R,end:n},integrated:{start:L,end:o}};i.push(I)}else S>0&&d&&(d.cumulativeDuration+=S,i[i.length-1].end=c)}h&&(y=v),e.timelineStart=v;var b=o;o+=g;var k=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:k,end:n},integrated:{start:b,end:o}})}var D=e.resumeTime;a=h||D>s?s:D})),a<s){var l,h=a,d=o,u=s-a;o+=u;var c=n;n+=u,i.push({previousEvent:(null==(l=i[i.length-1])?void 0:l.event)||null,nextEvent:null,start:a,end:h+u,playout:{start:c,end:n},integrated:{start:d,end:o}})}this.setDurations(s,n,o)}else{var f=0;i.push({previousEvent:null,nextEvent:null,start:f,end:s,playout:{start:f,end:s},integrated:{start:f,end:s}}),this.setDurations(s,s,s)}return i},i.setDurations=function(t,e,i){this.durations={primary:t,playout:e,integrated:i}},i.resolveOffsets=function(t,e){var i=this,r=e.main.details,s=r.live?1/0:r.edge,n=0,a=-1;t.forEach((function(o,l){var h=o.cue.pre,d=o.cue.post,u=h?0:d?s:o.startTime;i.updateAssetDurations(o),a===u?o.cumulativeDuration=n:(n=0,a=u),!d&&o.snapOptions.in&&(o.resumeAnchor=Ge(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(i.primaryCanResumeInPlaceAt(o,e)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<t.length&&t[l+1].startTime-t[l].resumeTime<gl&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&i.warn("Could not change append strategy for abutting event "+o));var c=k(o.resumeOffset)?o.resumeOffset:o.duration;n+=c}))},i.primaryCanResumeInPlaceAt=function(t,e){var i=this,r=t.resumeTime,s=t.startTime+t.resumptionOffset;return Math.abs(r-s)>sl?(this.log('"'+t.identifier+'" resumption '+r+" not aligned with estimated timeline end "+s),!1):!Object.keys(e).some((function(s){var n=e[s].details,a=n.edge;if(r>=a)return i.log('"'+t.identifier+'" resumption '+r+" past "+s+" playlist end "+a),!1;var o=Ge(null,n.fragments,r);if(!o)return i.log('"'+t.identifier+'" resumption '+r+" does not align with any fragments in "+s+" playlist ("+n.fragStart+"-"+n.fragmentEnd+")"),!0;var l="audio"===s?.175:0;return!(Math.abs(o.start-r)<sl+l||Math.abs(o.end-r)<sl+l||(i.log('"'+t.identifier+'" resumption '+r+" not aligned with "+s+" fragment bounds ("+o.start+"-"+o.end+" sn: "+o.sn+" cc: "+o.cc+")"),0))}))},i.updateAssetDurations=function(t){if(t.assetListLoaded){for(var e=t.timelineStart,i=0,r=!1,s=!1,n=0;n<t.assetList.length;n++){var a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,r||(r=null===a.duration),s||(s=!!a.error),i+=a.error?0:a.duration||0}t.duration=r&&!s?Math.max(i,t.duration):i}},i.removeEvent=function(t){t.reset(),delete this.eventMap[t.identifier]},s(e,[{key:"duration",get:function(){var t=this.items;return t?t[t.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var t,e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){var i=e.assetList,r=i[i.length-1];if(r)return r.identifier}return null}}])}(N);function pl(t){return"["+(t.event?'"'+t.event.identifier+'"':"primary")+": "+t.start.toFixed(2)+"-"+t.end.toFixed(2)+"]"}var vl=function(){function t(t){this.hls=void 0,this.hls=t}var e=t.prototype;return e.destroy=function(){this.hls=null},e.loadAssetList=function(t,e){var i,r=this,s=t.assetListUrl;try{i=hl(s,this.hls.sessionId,t.baseUrl)}catch(e){var n=this.assignAssetListError(t,C.ASSET_LIST_LOAD_ERROR,e,s);return void this.hls.trigger(w.ERROR,n)}e&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+e);var a=this.hls.config,o=new(0,a.loader)(a),l={responseType:"json",url:i.href},h=a.interstitialAssetListLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,i,s,n){var a=e.data,o=null==a?void 0:a.ASSETS;if(Array.isArray(o))t.assetListResponse=a,r.hls.trigger(w.ASSET_LIST_LOADED,{event:t,assetListResponse:a,networkDetails:n});else{var l=r.assignAssetListError(t,C.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,n);r.hls.trigger(w.ERROR,l)}},onError:function(e,i,s,n){var a=r.assignAssetListError(t,C.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+e.code+" "+e.text+" ("+i.url+")"),i.url,n,s);r.hls.trigger(w.ERROR,a)},onTimeout:function(e,i,s){var n=r.assignAssetListError(t,C.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+i.url+")"),i.url,e,s);r.hls.trigger(w.ERROR,n)}};return o.load(l,d,u),this.hls.trigger(w.ASSET_LIST_LOADING,{event:t}),o},e.assignAssetListError=function(t,e,i,r,s,n){return t.error=i,{type:P.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:r,error:i,networkDetails:n,stats:s}},t}();function yl(t){null==t||t.play().catch((function(){}))}var El=function(t){function e(e,i){var r;return(r=t.call(this,"interstitials",e.logger)||this).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var t=r.currentTime;if(void 0!==t&&!r.playbackDisabled&&r.schedule){var e=t-r.timelinePos;if(!(Math.abs(e)<1/7056e5)){var i=e<=-.01;r.timelinePos=t,r.bufferedPos=t;var s=r.playingItem;if(s)if(i&&r.schedule.resetErrorsInRange(t,t-e)&&r.updateSchedule(!0),r.checkBuffer(),i&&t<s.start||t>=s.end){var n,a=r.findItemIndex(s),o=r.schedule.findItemIndexAtTime(t);if(-1===o&&(o=a+(i?-1:1),r.log("seeked "+(i?"back ":"")+"to position not covered by schedule "+t+" (resolving from "+a+" to "+o+")")),!r.isInterstitial(s)&&null!=(n=r.media)&&n.paused&&(r.shouldPlay=!1),!i&&o>a){var l=r.schedule.findJumpRestrictedIndex(a+1,o);if(l>a)return void r.setSchedulePosition(l)}r.setSchedulePosition(o)}else{var h=r.playingAsset;if(h){var d,u=h.timelineStart,c=h.duration||0;(i&&t<u||t>=u+c)&&(null!=(d=s.event)&&d.appendInPlace&&(r.clearInterstitial(s.event,s),r.flushFrontBuffer(t)),r.setScheduleToAssetAtTime(t,h))}else if(r.playingLastItem&&r.isInterstitial(s)){var f=s.event.assetList[0];f&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(t,f))}}else r.checkBuffer()}}},r.onTimeupdate=function(){var t=r.currentTime;if(void 0!==t&&!r.playbackDisabled&&t>r.timelinePos){r.timelinePos=t,t>r.bufferedPos&&r.checkBuffer();var e=r.playingItem;if(e&&!r.playingLastItem){if(t>=e.end){r.timelinePos=e.end;var i=r.findItemIndex(e);r.setSchedulePosition(i+1)}var s=r.playingAsset;s&&t>=s.timelineStart+(s.duration||0)&&r.setScheduleToAssetAtTime(t,s)}}},r.onScheduleUpdate=function(t,e){var i=r.schedule;if(i){var s=r.playingItem,n=i.events||[],a=i.items||[],o=i.durations,l=t.map((function(t){return t.identifier})),h=!(!n.length&&!l.length);(h||e)&&r.log("INTERSTITIALS_UPDATED ("+n.length+"): "+n+"\nSchedule: "+a.map((function(t){return pl(t)}))+" pos: "+r.timelinePos),l.length&&r.log("Removed events "+l);var d=null,u=null;s&&(d=r.updateItem(s,r.timelinePos),r.itemsMatch(s,d)?r.playingItem=d:r.waitingItem=r.endedItem=null),r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var c=r.bufferingItem;if(c&&(u=r.updateItem(c,r.bufferedPos),r.itemsMatch(c,u)?r.bufferingItem=u:c.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(c.event,null))),t.forEach((function(t){t.assetList.forEach((function(t){r.clearAssetPlayer(t.identifier,null)}))})),r.playerQueue.forEach((function(t){if(t.interstitial.appendInPlace){var e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(s){Math.abs(i)>sl&&r.warn(s+' ("'+t.assetId+'" '+t.timelineOffset+"->"+e+")")}}})),h||e){if(r.hls.trigger(w.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:a.slice(0),durations:o,removedIds:l}),r.isInterstitial(s)&&l.includes(s.event.identifier))return r.warn('Interstitial "'+s.event.identifier+'" removed while playing'),void r.primaryFallback(s.event);s&&r.trimInPlace(d,s),c&&r.trimInPlace(u,c),r.checkBuffer()}}},r.hls=e,r.HlsPlayerClass=i,r.assetListLoader=new vl(e),r.schedule=new ml(r.onScheduleUpdate,e.logger),r.registerListeners(),r}l(e,t);var i=e.prototype;return i.registerListeners=function(){var t=this.hls;t&&(t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(w.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(w.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(w.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(w.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(w.BUFFER_APPENDED,this.onBufferAppended,this),t.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(w.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(w.MEDIA_ENDED,this.onMediaEnded,this),t.on(w.ERROR,this.onError,this),t.on(w.DESTROYING,this.onDestroying,this))},i.unregisterListeners=function(){var t=this.hls;t&&(t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(w.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(w.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(w.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(w.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(w.BUFFER_CODECS,this.onBufferCodecs,this),t.off(w.BUFFER_APPENDED,this.onBufferAppended,this),t.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(w.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(w.MEDIA_ENDED,this.onMediaEnded,this),t.off(w.ERROR,this.onError,this),t.off(w.DESTROYING,this.onDestroying,this))},i.startLoad=function(){this.resumeBuffering()},i.stopLoad=function(){this.pauseBuffering()},i.resumeBuffering=function(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()},i.pauseBuffering=function(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()},i.destroy=function(){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},i.onDestroying=function(){var t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)},i.removeMediaListeners=function(t){Jo(t,"play",this.onPlay),Jo(t,"pause",this.onPause),Jo(t,"seeking",this.onSeeking),Jo(t,"timeupdate",this.onTimeupdate)},i.onMediaAttaching=function(t,e){var i=this.media=e.media;Zo(i,"seeking",this.onSeeking),Zo(i,"timeupdate",this.onTimeupdate),Zo(i,"play",this.onPlay),Zo(i,"pause",this.onPause)},i.onMediaAttached=function(t,e){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var s=this.findItemIndex(i);this.setSchedulePosition(s)}},i.clearScheduleState=function(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},i.onMediaDetaching=function(t,e){var i=!!e.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){var s=this.getBufferingPlayer();s&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}},i.isInterstitial=function(t){return!(null==t||!t.event)},i.retreiveMediaSource=function(t,e){var i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)},i.transferMediaFromPlayer=function(t,e){var i=t.interstitial.appendInPlace,r=t.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&r)return void(this.detachedData={media:r});var s=t.transferMedia();this.log("transfer MediaSource from "+t+" "+Le(s)),this.detachedData=s}else e&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))},i.transferMediaTo=function(t,e){var i,r,s=this;if(t.media!==e){var n,a=null,o=this.hls,l=t!==o,h=l&&t.interstitial.appendInPlace,d=null==(i=this.detachedData)?void 0:i.mediaSource;if(o.media)h&&(a=o.transferMedia(),this.detachedData=a),n="Primary";else if(d){var u=this.getBufferingPlayer();u?(a=u.transferMedia(),n=""+u):n="detached MediaSource"}else n="detached media";if(!a)if(d)a=this.detachedData,this.log("using detachedData: MediaSource "+Le(a));else if(!this.detachedData||o.media===e){var c=this.playerQueue;c.length>1&&c.forEach((function(t){if(l&&t.interstitial.appendInPlace!==h){var e=t.interstitial;s.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&s.warn("Could not change append strategy for queued assets "+e)}})),this.hls.detachMedia(),this.detachedData={media:e}}var f=a&&"mediaSource"in a&&"closed"!==(null==(r=a.mediaSource)?void 0:r.readyState),g=f&&a?a:e;this.log((f?"transfering MediaSource":"attaching media")+" to "+(l?t:"Primary")+" from "+n+" (media.currentTime: "+e.currentTime+")");var m=this.schedule;if(g===a&&m){var p=l&&t.assetId===m.assetIdAtEnd;g.overrides={duration:m.duration,endOfStream:!l||p,cueRemoval:!l}}t.attachMedia(g)}},i.onInterstitialCueEnter=function(){this.onTimeupdate()},i.checkStart=function(){var t=this.schedule,e=null==t?void 0:t.events;if(e&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){var s=this.hls.startPosition;if(this.timelinePos=s,e.length&&e[0].cue.pre){var n=t.findEventIndex(e[0].identifier);this.setSchedulePosition(n)}else if(s>=0||!this.primaryLive){var a=this.timelinePos=s>0?s:0,o=t.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){var l=t.findItemIndex(r);this.setSchedulePosition(l)}}},i.advanceAssetBuffering=function(t,e){var i=t.event,r=i.findAssetIndex(e),s=dl(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var n,a=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(t)+1];a&&this.bufferedToItem(a)}}else this.bufferedToEvent(t,s)},i.advanceAfterAssetEnded=function(t,e,i){var r=dl(t,i);if(t.isAssetPastPlayoutLimit(r)){if(this.schedule){var s=this.schedule.items;if(s){var n=e+1;if(n>=s.length)return void this.setSchedulePosition(-1);var a=t.resumeTime;this.timelinePos<a&&(this.timelinePos=a,t.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(n)}}}else{if(t.appendInPlace){var o=t.assetList[r];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(e,r)}},i.setScheduleToAssetAtTime=function(t,e){var i=this.schedule;if(i){var r=e.parentIdentifier,s=i.getEvent(r);if(s){var n=i.findEventIndex(r),a=i.findAssetIndex(s,t);this.advanceAfterAssetEnded(s,n,a-1)}}},i.setSchedulePosition=function(t,e){var i,r=null==(i=this.schedule)?void 0:i.items;if(r&&!this.playbackDisabled){var s=t>=0?r[t]:null;this.log("setSchedulePosition "+t+", "+e+" ("+(s?pl(s):s)+")");var n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){var o=n.event,l=this.playingAsset,h=null==l?void 0:l.identifier,d=h?this.getAssetPlayer(h):null;if(d&&h&&(!this.eventItemsMatch(n,s)||void 0!==e&&h!==o.assetList[e].identifier)){var u,c=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED "+(c+1)+"/"+o.assetList.length+" "+cl(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(w.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:c,event:o,schedule:r.slice(0),scheduleIndex:t,player:d}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),c));this.retreiveMediaSource(h,s),!d.media||null!=(u=this.detachedData)&&u.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+pl(n)),o.hasPlayed=!0,this.hls.trigger(w.INTERSTITIAL_ENDED,{event:o,schedule:r.slice(0),scheduleIndex:t}),o.cue.once)){var f;this.updateSchedule();var g=null==(f=this.schedule)?void 0:f.items;if(s&&g){var m=this.findItemIndex(s);this.advanceSchedule(m,g,e,n,a)}return}}this.advanceSchedule(t,r,e,n,a)}},i.advanceSchedule=function(t,e,i,r,s){var n=this,a=this.schedule;if(a){var o=t>=0?e[t]:null,l=this.primaryMedia,h=this.playerQueue;if(h.length&&h.forEach((function(e){var i=e.interstitial,r=a.findEventIndex(i.identifier);(r<t||r>t+1)&&n.clearInterstitial(i,o)})),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var d=o.event;if(void 0===i){var u=dl(d,(i=a.findAssetIndex(d,this.timelinePos))-1);if(d.isAssetPastPlayoutLimit(u)||d.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(d,t,i);i=u}var c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(d,i);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED "+pl(o)+" "+(d.appendInPlace?"append in place":"")),this.hls.trigger(w.INTERSTITIAL_STARTED,{event:d,schedule:e.slice(0),scheduleIndex:t})),!d.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+d);if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial "+d);this.waitingItem=this.endedItem=null,this.playingItem=o;var g=d.assetList[i];if(!g)return void this.advanceAfterAssetEnded(d,t,i||0);if(f||(f=this.getAssetPlayer(g.identifier)),null===f||f.destroyed){var m=d.assetList.length;this.warn("asset "+(i+1)+"/"+m+" player destroyed "+d),(f=this.createAssetPlayer(d,g,i)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(f,i,e,t,l),this.shouldPlay&&yl(f.media)}else null!==o?(this.resumePrimary(o,t,r),this.shouldPlay&&yl(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}},i.resumePrimary=function(t,e,i){var r,s;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log("resuming "+pl(t)),null==(r=this.detachedData)||!r.mediaSource){var n=this.timelinePos;(n<t.start||n>=t.end)&&(n=this.getPrimaryResumption(t,e),this.timelinePos=n),this.attachPrimary(n,t)}if(i){var a=null==(s=this.schedule)?void 0:s.items;a&&(this.log("INTERSTITIALS_PRIMARY_RESUMED "+pl(t)),this.hls.trigger(w.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:e}),this.checkBuffer())}},i.getPrimaryResumption=function(t,e){var i=t.start;if(this.primaryLive){var r=this.primaryDetails;if(0===e)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i},i.isAssetBuffered=function(t){var e=this.getAssetPlayer(t.identifier);return null!=e&&e.hls?e.hls.bufferedToEnd:Ri.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)},i.attachPrimary=function(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(t,i)),i||(this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}},i.startLoadingPrimaryAt=function(t,e){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-t)>.5?r.startLoad(t,e):r.bufferingEnabled||r.resumeBuffering()},i.onManifestLoading=function(){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(w.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(w.BUFFER_CODECS,this.onBufferCodecs,this)},i.onLevelUpdated=function(t,e){if(-1!==e.level&&this.schedule){var i=this.hls.levels[e.level],r=c(c({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}},i.onAudioTrackUpdated=function(t,e){var i=this.hls.audioTracks[e.id],r=this.mediaSelection;if(r){var s=c(c({},r),{},{audio:i});this.mediaSelection=s}else this.altSelection=c(c({},this.altSelection),{},{audio:i})},i.onSubtitleTrackUpdated=function(t,e){var i=this.hls.subtitleTracks[e.id],r=this.mediaSelection;if(r){var s=c(c({},r),{},{subtitles:i});this.mediaSelection=s}else this.altSelection=c(c({},this.altSelection),{},{subtitles:i})},i.onAudioTrackSwitching=function(t,e){var i=De(e);this.playerQueue.forEach((function(t){var r=t.hls;return r&&(r.setAudioOption(e)||r.setAudioOption(i))}))},i.onSubtitleTrackSwitch=function(t,e){var i=De(e);this.playerQueue.forEach((function(t){var r=t.hls;return r&&(r.setSubtitleOption(e)||-1!==e.id&&r.setSubtitleOption(i))}))},i.onBufferCodecs=function(t,e){var i=e.tracks;i&&(this.requiredTracks=i)},i.onBufferAppended=function(t,e){this.checkBuffer()},i.onBufferFlushed=function(t,e){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}},i.onBufferedToEnd=function(t){if(this.schedule){var e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(var i=0;i<e.length;i++){var r=e[i];if(r.cue.post){var s,n=this.schedule.findEventIndex(r.identifier),a=null==(s=this.schedule.items)?void 0:s[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}},i.onMediaEnded=function(t){var e=this.playingItem;if(!this.playingLastItem&&e){var i=this.findItemIndex(e);this.setSchedulePosition(i+1)}else this.shouldPlay=!1},i.updateItem=function(t,e){var i,r=null==(i=this.schedule)?void 0:i.items;return t&&r&&r[this.findItemIndex(t,e)]||null},i.trimInPlace=function(t,e){var i=this;if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((function(e,r){t.event.isAssetPastPlayoutLimit(r)&&i.clearAssetPlayer(e.identifier,null)}));var r=t.end+.25,s=Ri.bufferInfo(this.primaryMedia,r,0);(s.end>r||(s.nextStart||0)>r)&&(this.attachPrimary(r,null),this.flushFrontBuffer(r))}},i.itemsMatch=function(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))},i.eventItemsMatch=function(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))},i.findItemIndex=function(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1},i.updateSchedule=function(t){var e;void 0===t&&(t=!1);var i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))},i.checkBuffer=function(t){var e,i=null==(e=this.schedule)?void 0:e.items;if(i){var r=Ri.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=r.len<1),this.updateBufferedPos(r.end,i,t)}},i.updateBufferedPos=function(t,e,i){var r=this.schedule,s=this.bufferingItem;if(!(this.bufferedPos>t)&&r)if(1===e.length&&this.itemsMatch(e[0],s))this.bufferedPos=t;else{var n=this.playingItem,a=this.findItemIndex(n),o=r.findItemIndexAtTime(t);if(this.bufferedPos<t){var l,h=this.findItemIndex(s),d=Math.min(h+1,e.length-1),u=e[d];if((-1===o&&s&&t>=s.end||null!=(l=u.event)&&l.appendInPlace&&t+.01>=u.start)&&(o=d),this.isInterstitial(s)){var c=s.event;if(d-a>1&&!1===c.appendInPlace)return;if(0===c.assetList.length&&c.assetListLoader)return}if(this.bufferedPos=t,o>h&&o>a)this.bufferedToItem(u);else{var f=this.primaryDetails;this.primaryLive&&f&&t>f.edge-f.targetduration&&u.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else i&&n&&!this.itemsMatch(n,s)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}},i.assetsBuffered=function(t,e){var i=this;return 0!==t.event.assetList.length&&!t.event.assetList.some((function(t){var r=i.getAssetPlayer(t.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(e))}))},i.setBufferingItem=function(t){var e=this,i=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(t,i)&&r){var s=r.items,n=r.events;if(!s||!n)return i;var a=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));var l=o?o.remaining:i?i.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY "+pl(t)+(i?" ("+l.toFixed(2)+" remaining)":"")),!this.playbackDisabled)if(a){var h=r.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((function(t,i){var r=e.getAssetPlayer(t.identifier);r&&(i===h&&r.loadSource(),r.resumeBuffering())}))}else this.hls.resumeBuffering(),this.playerQueue.forEach((function(t){return t.pauseBuffering()}));this.hls.trigger(w.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return i},i.bufferedToItem=function(t,e){void 0===e&&(e=0);var i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;if(r)if(r.mediaSource){var s=!0;this.attachPrimary(t.start,t,s)}else this.preloadPrimary(t);else this.preloadPrimary(t)}},i.preloadPrimary=function(t){var e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)},i.bufferedToEvent=function(t,e){var i=t.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){var n=this.preloadAssets(i,e);if(null!=n&&n.interstitial.appendInPlace){var a=this.primaryMedia;a&&this.bufferAssetPlayer(n,a)}}},i.preloadAssets=function(t,e){var i=t.assetUrl,r=t.assetList.length,s=0===r&&!t.assetListLoader,n=t.cue.once;if(s){var a,o=t.timelineStart;if(t.appendInPlace){var l,h=this.playingItem;this.isInterstitial(h)||(null==h||null==(l=h.nextEvent)?void 0:l.identifier)!==t.identifier||this.flushFrontBuffer(o+.25)}var d=0;if(!this.playingItem&&this.primaryLive&&-1===(d=this.hls.startPosition)&&(d=this.hls.liveSyncPosition||0),d&&!t.cue.pre&&!t.cue.post){var u=d-o;u>0&&(a=Math.round(1e3*u)/1e3)}if(this.log("Load interstitial asset "+(e+1)+"/"+(i?1:r)+" "+t+(a?" live-start: "+d+" start-offset: "+a:"")),i)return this.createAsset(t,0,0,o,t.duration,i);var c=this.assetListLoader.loadAssetList(t,a);c&&(t.assetListLoader=c)}else if(!n&&r){for(var f=e;f<r;f++){var g=t.assetList[f],m=this.getAssetPlayerQueueIndex(g.identifier);-1!==m&&!this.playerQueue[m].destroyed||g.error||this.createAssetPlayer(t,g,f)}var p=t.assetList[e];if(p){var v=this.getAssetPlayer(p.identifier);return v&&v.loadSource(),v}}return null},i.flushFrontBuffer=function(t){var e=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at "+t),Object.keys(i).forEach((function(i){e.hls.trigger(w.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:i})})))},i.getAssetPlayerQueueIndex=function(t){for(var e=this.playerQueue,i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1},i.getAssetPlayer=function(t){var e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null},i.getBufferingPlayer=function(){var t=this.playerQueue,e=this.primaryMedia;if(e)for(var i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null},i.createAsset=function(t,e,i,r,s,n){var a={parentIdentifier:t.identifier,identifier:al(t,n,e),duration:s,startOffset:i,timelineStart:r,uri:n};return this.createAssetPlayer(t,a,e)},i.createAssetPlayer=function(t,e,i){var r=this,s=this.hls,n=s.userConfig,o=n.videoPreference,l=s.loadLevelObj||s.levels[s.currentLevel];(o||l)&&(o=a({},o),l.videoCodec&&(o.videoCodec=l.videoCodec),l.videoRange&&(o.allowedVideoRanges=[l.videoRange]));var h=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack],u=0;if(this.primaryLive||t.appendInPlace){var f=this.timelinePos-e.timelineStart;if(f>1){var g=e.duration;g&&f<g&&(u=f)}}var m=e.identifier,p=c(c({},n),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:m,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:h||n.audioPreference,subtitlePreference:d||n.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(p.timelineOffset=e.timelineStart));var v=p.cmcd;null!=v&&v.sessionId&&v.contentId&&(p.cmcd=a({},v,{contentId:rl(e.uri)})),this.getAssetPlayer(m)&&this.warn("Duplicate date range identifier "+t+" and asset "+m);var y=new fl(this.HlsPlayerClass,p,t,e);this.playerQueue.push(y),t.assetList[i]=e;var E=!0,T=function(s){if(s.live){var n,a=new Error("Interstitials MUST be VOD assets "+t),o={fatal:!0,type:P.OTHER_ERROR,details:C.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},l=(null==(n=r.schedule)?void 0:n.findEventIndex(t.identifier))||-1;r.handleAssetItemError(o,t,l,i,a.message)}else{var h=s.edge-s.fragmentStart,d=e.duration;(E||null===d||h>d)&&(E=!1,r.log('Interstitial asset "'+m+'" duration change '+d+" > "+h),e.duration=h,r.updateSchedule())}};y.on(w.LEVEL_UPDATED,(function(t,e){var i=e.details;return T(i)})),y.on(w.LEVEL_PTS_UPDATED,(function(t,e){var i=e.details;return T(i)})),y.on(w.EVENT_CUE_ENTER,(function(){return r.onInterstitialCueEnter()}));var S=function(t,e){var i=r.getAssetPlayer(m);if(i&&e.tracks){i.off(w.BUFFER_CODECS,S),i.tracks=e.tracks;var s=r.primaryMedia;r.bufferingAsset===i.assetItem&&s&&!i.media&&r.bufferAssetPlayer(i,s)}};y.on(w.BUFFER_CODECS,S);var A=function(){var i,s=r.getAssetPlayer(m);if(r.log("buffered to end of asset "+s),s&&r.schedule){var n=r.schedule.findEventIndex(t.identifier),a=null==(i=r.schedule.items)?void 0:i[n];r.isInterstitial(a)&&r.advanceAssetBuffering(a,e)}};y.on(w.BUFFERED_TO_END,A);var L=function(e){return function(){if(r.getAssetPlayer(m)&&r.schedule){r.shouldPlay=!0;var i=r.schedule.findEventIndex(t.identifier);r.advanceAfterAssetEnded(t,i,e)}}};return y.once(w.MEDIA_ENDED,L(i)),y.once(w.PLAYOUT_LIMIT_REACHED,L(1/0)),y.on(w.ERROR,(function(e,s){if(r.schedule){var n=r.getAssetPlayer(m);if(s.details===C.BUFFER_STALLED_ERROR)return null!=n&&n.appendInPlace?void r.handleInPlaceStall(t):(r.onTimeupdate(),void r.checkBuffer(!0));r.handleAssetItemError(s,t,r.schedule.findEventIndex(t.identifier),i,"Asset player error "+s.error+" "+t)}})),y.on(w.DESTROYING,(function(){if(r.getAssetPlayer(m)&&r.schedule){var e=new Error("Asset player destroyed unexpectedly "+m),s={fatal:!0,type:P.OTHER_ERROR,details:C.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};r.handleAssetItemError(s,t,r.schedule.findEventIndex(t.identifier),i,e.message)}})),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED "+cl(e)),this.hls.trigger(w.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:y}),y},i.clearInterstitial=function(t,e){var i=this;t.assetList.forEach((function(t){i.clearAssetPlayer(t.identifier,e)})),t.reset()},i.resetAssetPlayer=function(t){var e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log('reset asset player "'+t+'" after error');var i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}},i.clearAssetPlayer=function(t,e){var i=this.getAssetPlayerQueueIndex(t);if(-1!==i){this.log('clear asset player "'+t+'" toSegment: '+(e?pl(e):e));var r=this.playerQueue[i];this.transferMediaFromPlayer(r,e),this.playerQueue.splice(i,1),r.destroy()}},i.emptyPlayerQueue=function(){for(var t;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]},i.startAssetPlayer=function(t,e,i,r,s){var n=t.interstitial,a=t.assetItem,o=t.assetId,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log("INTERSTITIAL_ASSET_STARTED "+(e+1)+"/"+l+" "+cl(a)),this.hls.trigger(w.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:r,player:t})),this.bufferAssetPlayer(t,s)},i.bufferAssetPlayer=function(t,e){var i,r;if(this.schedule){var s=t.interstitial,n=t.assetItem,a=this.schedule.findEventIndex(s.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(o){t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;var l=this.getBufferingPlayer();if(l!==t){var h=s.appendInPlace;if(!h||!1!==(null==l?void 0:l.interstitial.appendInPlace)){var d=(null==l?void 0:l.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!t.tracks)return void this.log("Waiting for track info before buffering "+t);if(d&&!q(d,t.tracks)){var u=new Error("Asset "+cl(n)+" SourceBuffer tracks ('"+Object.keys(t.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(d)+"')"),c={fatal:!0,type:P.OTHER_ERROR,details:C.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},f=s.findAssetIndex(n);return void this.handleAssetItemError(c,s,a,f,u.message)}}this.transferMediaTo(t,e)}}}}},i.handleInPlaceStall=function(t){var e=this.schedule,i=this.primaryMedia;if(e&&i){var r=i.currentTime,s=e.findAssetIndex(t,r),n=t.assetList[s];if(n){var a=this.getAssetPlayer(n.identifier);if(a){var o=a.currentTime||r-n.timelineStart,l=a.duration-o;if(this.warn("Stalled at "+o+" of "+(o+l)+" in "+a+" "+t+" (media.currentTime: "+r+")"),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){var h=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,h,s)}}}}},i.advanceInPlace=function(t){var e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)},i.handleAssetItemError=function(t,e,i,r,s){if(t.details!==C.BUFFER_STALLED_ERROR){var n=e.assetList[r]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR "+(n?cl(n):n)+" "+t.error),this.schedule){var o=(null==n?void 0:n.identifier)||"",l=this.getAssetPlayerQueueIndex(o),h=this.playerQueue[l]||null,d=this.schedule.items,u=a({},t,{fatal:!1,errorAction:ti(!0),asset:n,assetListIndex:r,event:e,schedule:d,scheduleIndex:i,player:h});if(this.hls.trigger(w.INTERSTITIAL_ASSET_ERROR,u),t.fatal){var c=this.playingAsset,f=this.bufferingAsset,g=new Error(s);if(n&&(this.clearAssetPlayer(o,null),n.error=g),e.assetList.some((function(t){return!t.error})))for(var m=r;m<e.assetList.length;m++)this.resetAssetPlayer(e.assetList[m].identifier);else e.error=g;this.updateSchedule(!0),e.error?this.primaryFallback(e):c&&c.identifier===o?this.advanceAfterAssetEnded(e,i,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}}}},i.primaryFallback=function(t){var e=t.timelineStart,i=this.effectivePlayingItem;if(i){this.log('Fallback to primary from event "'+t.identifier+'" start: '+e+" pos: "+this.timelinePos+" playing: "+pl(i)+" error: "+t.error);var r=this.timelinePos;-1===r&&(r=this.hls.startPosition);var s=this.updateItem(i,r);if(this.itemsMatch(i,s)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e)),!this.schedule)return;var n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}else this.checkStart()},i.onAssetListLoaded=function(t,e){var i,r,s=this,n=e.event,a=n.identifier,o=e.assetListResponse.ASSETS;if(null!=(i=this.schedule)&&i.hasEvent(a)){var l=n.timelineStart,h=n.duration,d=0;o.forEach((function(t,e){var i=parseFloat(t.DURATION);s.createAsset(n,e,d,l+d,i,t.URI),d+=i})),n.duration=d,this.log("Loaded asset-list with duration: "+d+" (was: "+h+") "+n);var u=this.waitingItem,c=(null==u?void 0:u.event.identifier)===a;this.updateSchedule();var f=null==(r=this.bufferingItem)?void 0:r.event;if(c){var g,m=this.schedule.findEventIndex(a),p=null==(g=this.schedule.items)?void 0:g[m];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m)return n.error=new Error("Interstitial no longer within playback range "+this.timelinePos+" "+n),this.updateSchedule(!0),void this.primaryFallback(n);this.setBufferingItem(p)}this.setSchedulePosition(m)}else if((null==f?void 0:f.identifier)===a){var v=n.assetList[0];if(v){var y=this.getAssetPlayer(v.identifier);if(f.appendInPlace){var E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}},i.onError=function(t,e){if(this.schedule)switch(e.details){case C.ASSET_LIST_PARSING_ERROR:case C.ASSET_LIST_LOAD_ERROR:case C.ASSET_LIST_LOAD_TIMEOUT:var i=e.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break;case C.BUFFER_STALLED_ERROR:var r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace)return void this.handleInPlaceStall(r.event);this.log("Primary player stall @"+this.timelinePos+" bufferedPos: "+this.bufferedPos),this.onTimeupdate(),this.checkBuffer(!0)}},s(e,[{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var t=this,e=function(){return t.bufferingItem||t.waitingItem},i=function(e){return e?t.getAssetPlayer(e.identifier):e},r=function(e,r,s,a,o){if(e){var l=e[r].start,h=e.event;if(h){if("playout"===r||h.timelineOccupancy!==nl.Point){var d=i(s);(null==d?void 0:d.interstitial)===h&&(l+=d.assetItem.startOffset+d[o])}}else l+=("bufferedPos"===a?n():t[a])-e.start;return l}return 0},s=function(e,i){var r;if(0!==e&&"primary"!==i&&null!=(r=t.schedule)&&r.length){var s,n=t.schedule.findItemIndexAtTime(e),a=null==(s=t.schedule.items)?void 0:s[n];if(a)return e+(a[i].start-a.start)}return e},n=function(){var e=t.bufferedPos;return e===Number.MAX_VALUE?a("primary"):Math.max(e,0)},a=function(e){var i,r;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(r=t.schedule)?void 0:r.durations[e])||0},o=function(e,s){var n,a,o=t.effectivePlayingItem;if((null==o||null==(n=o.event)||!n.restrictions.skip)&&t.schedule){t.log("seek to "+e+' "'+s+'"');var l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,s),d=null==(a=t.schedule.items)?void 0:a[h],u=t.getBufferingPlayer(),c=null==u?void 0:u.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&t.itemsMatch(l,d);if(l&&(f||g)){var m=i(t.playingAsset),p=(null==m?void 0:m.media)||t.primaryMedia;if(p){var v="primary"===s?p.currentTime:r(l,s,t.playingAsset,"timelinePos","currentTime"),y=e-v,E=(f?v:p.currentTime)+y;if(E>=0&&(!m||f||E<=m.duration))return void(p.currentTime=E)}}if(d){var T=e;if("primary"!==s){var S=e-d[s].start;T=d.start+S}var A=!t.isInterstitial(d);if(t.isInterstitial(l)&&!l.event.appendInPlace||!A&&!d.event.appendInPlace){if(l){var L=t.findItemIndex(l);if(h>L){var R=t.schedule.findJumpRestrictedIndex(L+1,h);if(R>L)return void t.setSchedulePosition(R)}var I=0;if(A)t.timelinePos=T,t.checkBuffer();else for(var b=d.event.assetList,k=e-(d[s]||d).start,D=b.length;D--;){var _=b[D];if(_.duration&&k>=_.startOffset&&k<_.startOffset+_.duration){I=D;break}}t.setSchedulePosition(h,I)}}else{var P=t.media||(f?null==u?void 0:u.media:null);P&&(P.currentTime=T)}}}},l=function(){var i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;var r=e();return t.isInterstitial(r)?r:null},h={get bufferedEnd(){var i,s=e(),n=t.bufferingItem;return n&&n===s&&(r(n,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-n.playout.start||(null==(i=t.bufferingAsset)?void 0:i.startOffset))||0},get currentTime(){var e=l(),i=t.effectivePlayingItem;return i&&i===e?r(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){var i=l(),r=t.effectivePlayingItem;r&&r===i&&o(e+r.playout.start,"playout")},get duration(){var t=l();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e,i=null==(e=l())?void 0:e.event.assetList;return i?i.map((function(e){return t.getAssetPlayer(e.identifier)})):[]},get playingIndex(){var e,i=null==(e=l())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return l()}};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 l()?h:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){var i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){var e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return n()},get currentTime(){var e=t.timelinePos;return e>0?e:0},set currentTime(t){o(t,"primary")},get duration(){return a("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){o(t,"integrated")},get duration(){return a("integrated")},get seekableStart(){var e;return s((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:function(){var e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){var r=t.findItemIndex(e);if(i.appendInPlace){var s=e.playout.start+e.event.duration;o(s+.001,"playout")}else t.advanceAfterAssetEnded(i,r,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var t,e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var t,e;if(null!==this.mediaSelection){var i=this.waitingItem||this.playingItem;if(!this.isInterstitial(i)||i.event.appendInPlace){var r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(r=this.primaryMedia);var s=null==(e=r)?void 0:e.currentTime;if(void 0!==s&&k(s))return s}}}},{key:"primaryMedia",get:function(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}},{key:"primaryLive",get:function(){var t;return!(null==(t=this.primaryDetails)||!t.live)}}])}(N),Tl=500,Sl=function(t){function e(e,i,r){var s;return(s=t.call(this,e,i,r,"subtitle-stream-controller",x.SUBTITLE)||this).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s.registerListeners(),s}l(e,t);var i=e.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),t.prototype.onHandlerDestroying.call(this),this.mainDetails=null},i.registerListeners=function(){t.prototype.registerListeners.call(this);var e=this.hls;e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(w.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.unregisterListeners=function(){t.prototype.unregisterListeners.call(this);var e=this.hls;e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(w.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.startLoad=function(t,e){this.stopLoad(),this.state=jr.IDLE,this.setInterval(Tl),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()},i.onManifestLoading=function(){t.prototype.onManifestLoading.call(this),this.mainDetails=null},i.onMediaDetaching=function(e,i){this.tracksBuffered=[],t.prototype.onMediaDetaching.call(this,e,i)},i.onLevelLoaded=function(t,e){this.mainDetails=e.details},i.onSubtitleFragProcessed=function(t,e){var i=e.frag,r=e.success;if(this.fragContextChanged(i)||(et(i)&&(this.fragPrevious=i),this.state=jr.IDLE),r){var s=this.tracksBuffered[this.currentTrackId];if(s){for(var n,a=i.start,o=0;o<s.length;o++)if(a>=s[o].start&&a<=s[o].end){n=s[o];break}var l=i.start+i.duration;n?n.end=l:(n={start:a,end:l},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}},i.onBufferFlushing=function(t,e){var i=e.startOffset,r=e.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var s=r-1;if(s<=0)return;e.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(t){for(var e=0;e<t.length;)if(t[e].end<=s)t.shift();else{if(!(t[e].start<s))break;t[e].start=s,e++}})),this.fragmentTracker.removeFragmentsInRange(i,s,x.SUBTITLE)}},i.onError=function(t,e){var i=e.frag;(null==i?void 0:i.type)===x.SUBTITLE&&(e.details===C.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==jr.STOPPED&&(this.state=jr.IDLE))},i.onSubtitleTracksUpdated=function(t,e){var i=this,r=e.subtitleTracks;this.levels&&ca(this.levels,r)?this.levels=r.map((function(t){return new ye(t)})):(this.tracksBuffered=[],this.levels=r.map((function(t){var e=new ye(t);return i.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,x.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)},i.onSubtitleTrackSwitch=function(t,e){var i;if(this.currentTrackId=e.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==jr.STOPPED&&this.setInterval(Tl)}else this.clearInterval()},i.onSubtitleTrackLoaded=function(t,e){var i,r=this.currentTrackId,s=this.levels,n=e.details,a=e.id;if(s){var o=s[a];if(!(a>=s.length)&&o){this.log("Subtitle track "+a+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;var h=this.mainDetails;if(!h)return void(this.startFragRequested=!1);var d,u=h.fragments[0];o.details?0===(l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details))&&u&&Or(n,l=u.start):n.hasProgramDateTime&&h.hasProgramDateTime?(Yr(n,h),l=n.fragmentStart):u&&Or(n,l=u.start),h&&!this.startFragRequested&&this.setStartPosition(h,l)}o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(w.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===jr.IDLE&&(Ge(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},i._handleFragmentLoadComplete=function(t){var e=this,i=t.frag,r=t.payload,s=i.decryptdata,n=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&Bi(s.method)){var a=performance.now();this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,Gi(s.method)).catch((function(t){throw n.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((function(t){var e=performance.now();n.trigger(w.FRAG_DECRYPTED,{frag:i,payload:t,stats:{tstart:a,tdecrypt:e}})})).catch((function(t){e.warn(t.name+": "+t.message),e.state=jr.IDLE}))}},i.doTick=function(){if(this.media){if(this.state===jr.IDLE){var t=this.currentTrackId,e=this.levels,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,s=this.getLoadPosition(),n=Ri.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),a=n.end,o=n.len,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var h=l.fragments,d=h.length,u=l.edge,c=null,f=this.fragPrevious;if(a<u){var g=r.maxFragLookUpTolerance,m=a>u-g?0:g;!(c=Ge(f,h,Math.max(h[0].start,a),m))&&f&&f.start<h[0].start&&(c=h[0])}else c=h[d-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;var p=h[c.sn-l.startSN-1];if(p&&p.cc===c.cc&&this.fragmentTracker.getState(p)===ei.NOT_LOADED&&(c=p),this.fragmentTracker.getState(c)===ei.NOT_LOADED){var v=this.mapToInitFragWhenRequired(c);v&&this.loadFragment(v,i,a)}}}else this.state=jr.IDLE},i.loadFragment=function(e,i,r){et(e)?t.prototype.loadFragment.call(this,e,i,r):this._loadInitSegment(e,i)},s(e,[{key:"mediaBufferTimeRanges",get:function(){return new Al(this.tracksBuffered[this.currentTrackId]||[])}}])}(qr),Al=function(t){this.buffered=void 0;var e=function(e,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '"+e+"' on 'TimeRanges': The index provided ("+i+") is greater than the maximum bound ("+r+")");return t[i][e]};this.buffered={get length(){return t.length},end:function(i){return e("end",i,t.length)},start:function(i){return e("start",i,t.length)}}};function Ll(t,e){var i;try{i=new Event("addtrack")}catch(t){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function Rl(t,e){var i=t.mode;if("disabled"===i&&(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{var r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,t.addCue(r)}catch(t){Y.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+t)}}"disabled"===i&&(t.mode=i)}function Il(t,e){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(var r=t.cues.length;r--;)e&&t.cues[r].removeEventListener("enter",e),t.removeCue(t.cues[r]);"disabled"===i&&(t.mode=i)}function bl(t,e,i,r){var s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var n=Dl(t.cues,e,i),a=0;a<n.length;a++)r&&!r(n[a])||t.removeCue(n[a]);"disabled"===s&&(t.mode=s)}function kl(t,e){if(e<=t[0].startTime)return 0;var i=t.length-1;if(e>t[i].endTime)return-1;for(var r,s=0,n=i;s<=n;)if(e<t[r=Math.floor((n+s)/2)].startTime)n=r-1;else{if(!(e>t[r].startTime&&s<i))return r;s=r+1}return t[s].startTime-e<e-t[n].startTime?s:n}function Dl(t,e,i){var r=[],s=kl(t,e);if(s>-1)for(var n=s,a=t.length;n<a;n++){var o=t[n];if(o.startTime>=e&&o.endTime<=i)r.push(o);else if(o.startTime>i)return r}return r}function _l(t){for(var e=[],i=0;i<t.length;i++){var r=t[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[i])}return e}var Pl=function(t){function e(e){var i;return(i=t.call(this,e,"subtitle-track-controller")||this).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var t=null,e=_l(i.media.textTracks),r=0;r<e.length;r++)if("hidden"===e[r].mode)t=e[r];else if("showing"===e[r].mode){t=e[r];break}var s=i.findTrackForTextTrack(t);i.subtitleTrack!==s&&i.setSubtitleTrack(s)}},i.registerListeners(),i}l(e,t);var i=e.prototype;return i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,t.prototype.destroy.call(this)},i.registerListeners=function(){var t=this.hls;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVEL_LOADING,this.onLevelLoading,this),t.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(w.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVEL_LOADING,this.onLevelLoading,this),t.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(w.ERROR,this.onError,this)},i.onMediaAttached=function(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))},i.pollTrackChange=function(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)},i.onMediaDetaching=function(t,e){var i=this.media;if(i){var r=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||_l(i.textTracks).forEach((function(t){Il(t)}))}},i.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},i.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},i.onSubtitleTrackLoaded=function(t,e){var i=e.id,r=e.groupId,s=e.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=e.details,this.log("Subtitle track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,e,a)}else this.warn("Subtitle track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(t,e){this.switchLevel(e.level)},i.onLevelSwitching=function(t,e){this.switchLevel(e.level)},i.switchLevel=function(t){var e=this.hls.levels[t];if(e){var i=e.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(t){return-1===(null==r?void 0:r.indexOf(t))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(t){return!i||-1!==i.indexOf(t.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(t){return t.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(t,e){t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;var o=_e(a,n);if(o>-1)s=n[o];else{var l=_e(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var d={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(w.SUBTITLE_TRACKS_UPDATED,d),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}}},i.findTrackId=function(t){for(var e=this.tracksInGroup,i=this.selectDefaultTrack,r=0;r<e.length;r++){var s=e[r];if((!i||s.default)&&(i||t)&&(!t||Pe(s,t)))return r}if(t){for(var n=0;n<e.length;n++){var a=e[n];if(fa(t.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(var o=0;o<e.length;o++){var l=e[o];if(fa(t.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},i.findTrackForTextTrack=function(t){if(t)for(var e=this.tracksInGroup,i=0;i<e.length;i++)if(ga(e[i],t))return i;return-1},i.onError=function(t,e){!e.fatal&&e.context&&(e.context.type!==O.SUBTITLE_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))},i.setSubtitleOption=function(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;var e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){var i=this.currentTrack;if(i&&Pe(t,i))return i;var r=_e(t,this.tracksInGroup);if(r>-1){var s=this.tracksInGroup[r];return this.setSubtitleTrack(r),s}if(i)return null;var n=_e(t,e);if(n>-1)return e[n]}}return null},i.loadPlaylist=function(e){t.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)},i.loadingPlaylist=function(e,i){t.prototype.loadingPlaylist.call(this,e,i);var r=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,i),a=e.details,o=null==a?void 0:a.age;this.log("Loading subtitle "+r+' "'+e.name+'" lang:'+e.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type?" "+a.type||0:""):"")+" "+n),this.hls.trigger(w.SUBTITLE_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:e})},i.toggleTrackModes=function(){var t=this.media;if(t){var e,i=_l(t.textTracks),r=this.currentTrack;if(r&&((e=i.filter((function(t){return ga(r,t)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+r.name+'" and language "'+r.lang+'"')),[].slice.call(i).forEach((function(t){"disabled"!==t.mode&&t!==e&&(t.mode="disabled")})),e){var s=this.subtitleDisplay?"showing":"hidden";e.mode!==s&&(e.mode=s)}}},i.setSubtitleTrack=function(t){var e=this.tracksInGroup;if(this.media)if(t<-1||t>=e.length||!k(t))this.warn("Invalid subtitle track id: "+t);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),r){var s=!!r.details&&!r.details.live;if(t!==this.trackId||r!==i||!s){this.log("Switching to subtitle-track "+t+(r?' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId:""));var n=r.id,a=r.groupId,o=void 0===a?"":a,l=r.name,h=r.type,d=r.url;this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:l,type:h,url:d});var u=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(u)}}else this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:t})}else this.queuedDefaultTrack=t},s(e,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}}])}(ua),Cl={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},wl=function(t){return String.fromCharCode(Cl[t]||t)},Ol=15,xl=100,Ml={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Fl={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Nl={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ul={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Bl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Gl=function(){function t(){this.time=null,this.verboseLevel=0}return t.prototype.log=function(t,e){if(this.verboseLevel>=t){var i="function"==typeof e?e():e;Y.log(this.time+" ["+t+"] "+i)}},t}(),$l=function(t){for(var e=[],i=0;i<t.length;i++)e.push(t[i].toString(16));return e},Kl=function(){function t(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}var e=t.prototype;return e.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},e.setStyles=function(t){for(var e=["foreground","underline","italics","background","flash"],i=0;i<e.length;i++){var r=e[i];t.hasOwnProperty(r)&&(this[r]=t[r])}},e.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},e.equals=function(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash},e.copy=function(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash},e.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},t}(),Vl=function(){function t(){this.uchar=" ",this.penState=new Kl}var e=t.prototype;return e.reset=function(){this.uchar=" ",this.penState.reset()},e.setChar=function(t,e){this.uchar=t,this.penState.copy(e)},e.setPenState=function(t){this.penState.copy(t)},e.equals=function(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)},e.copy=function(t){this.uchar=t.uchar,this.penState.copy(t.penState)},e.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},t}(),Hl=function(){function t(t){this.chars=[],this.pos=0,this.currPenState=new Kl,this.cueStartTime=null,this.logger=void 0;for(var e=0;e<xl;e++)this.chars.push(new Vl);this.logger=t}var e=t.prototype;return e.equals=function(t){for(var e=0;e<xl;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0},e.copy=function(t){for(var e=0;e<xl;e++)this.chars[e].copy(t.chars[e])},e.isEmpty=function(){for(var t=!0,e=0;e<xl;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t},e.setCursor=function(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>xl&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=xl)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var i=this.pos+1;i<e+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(e)},e.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},e.insertChar=function(t){var e=this;t>=144&&this.backSpace();var i=wl(t);this.pos>=xl?this.logger.log(0,(function(){return"Cannot insert "+t.toString(16)+" ("+i+") at position "+e.pos+". Skipping it!"})):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e<xl;e++)this.chars[e].reset()},e.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.getTextString=function(){for(var t=[],e=!0,i=0;i<xl;i++){var r=this.chars[i].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")},e.setPenStyles=function(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)},t}(),Yl=function(){function t(t){this.rows=[],this.currRow=Ol-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var e=0;e<Ol;e++)this.rows.push(new Hl(t));this.logger=t}var e=t.prototype;return e.reset=function(){for(var t=0;t<Ol;t++)this.rows[t].clear();this.currRow=Ol-1},e.equals=function(t){for(var e=!0,i=0;i<Ol;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e},e.copy=function(t){for(var e=0;e<Ol;e++)this.rows[e].copy(t.rows[e])},e.isEmpty=function(){for(var t=!0,e=0;e<Ol;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t},e.backSpace=function(){this.rows[this.currRow].backSpace()},e.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.insertChar=function(t){this.rows[this.currRow].insertChar(t)},e.setPen=function(t){this.rows[this.currRow].setPenStyles(t)},e.moveCursor=function(t){this.rows[this.currRow].moveCursor(t)},e.setCursor=function(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)},e.setPAC=function(t){this.logger.log(2,(function(){return"pacData = "+Le(t)}));var e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(var i=0;i<Ol;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){var n=s.rows[r].cueStartTime,a=this.logger.time;if(null!==n&&null!==a&&n<a)for(var o=0;o<this.nrRollUpRows;o++)this.rows[e-this.nrRollUpRows+o+1].copy(s.rows[r+o])}}this.currRow=e;var l=this.rows[this.currRow];if(null!==t.indent){var h=t.indent,d=Math.max(h-1,0);l.setCursor(t.indent),t.color=l.chars[d].penState.foreground}var u={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(u)},e.setBkgData=function(t){this.logger.log(2,(function(){return"bkgData = "+Le(t)})),this.backSpace(),this.setPen(t),this.insertChar(32)},e.setRollUpRows=function(t){this.nrRollUpRows=t},e.rollUp=function(){var t=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return t.getDisplayText()}));var e=this.currRow+1-this.nrRollUpRows,i=this.rows.splice(e,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},e.getDisplayText=function(t){t=t||!1;for(var e=[],i="",r=-1,s=0;s<Ol;s++){var n=this.rows[s].getTextString();n&&(r=s+1,t?e.push("Row "+r+": '"+n+"'"):e.push(n.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i},e.getTextAndFormat=function(){return this.rows},t}(),Wl=function(){function t(t,e,i){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 Yl(i),this.nonDisplayedMemory=new Yl(i),this.lastOutputScreen=new Yl(i),this.currRollUpRow=this.displayedMemory.rows[Ol-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}var e=t.prototype;return e.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Ol-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(function(){return"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)},e.insertChars=function(t){for(var e=this,i=0;i<t.length;i++)this.writeScreen.insertChar(t[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return r+": "+e.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+e.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},e.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},e.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},e.ccAOF=function(){},e.ccAON=function(){},e.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},e.ccRU=function(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)},e.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},e.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},e.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},e.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},e.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},e.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},e.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},e.ccEOC=function(){var t=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+t.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},e.ccTO=function(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)},e.ccMIDROW=function(t){var e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{var i=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[i]}this.logger.log(2,"MIDROW: "+Le(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var 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))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}(),jl=function(){function t(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Ql(),this.logger=void 0;var r=this.logger=new Gl;this.channels=[null,new Wl(t,e,r),new Wl(t+1,i,r)]}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var i=this;this.logger.time=t;for(var r=function(t){var r=127&e[t],s=127&e[t+1],n=!1,a=null;if(0===r&&0===s)return 0;i.logger.log(3,(function(){return"["+$l([e[t],e[t+1]])+"] -> ("+$l([r,s])+")"}));var o=i.cmdHistory;if(r>=16&&r<=31){if(Xl(r,s,o))return ql(null,null,o),i.logger.log(3,(function(){return"Repeated command ("+$l([r,s])+") is dropped"})),0;ql(r,s,i.cmdHistory),(n=i.parseCmd(r,s))||(n=i.parseMidrow(r,s)),n||(n=i.parsePAC(r,s)),n||(n=i.parseBackgroundAttributes(r,s))}else ql(null,null,o);if(!n&&(a=i.parseChars(r,s))){var l=i.currentChannel;l&&l>0?i.channels[l].insertChars(a):i.logger.log(2,"No channel found yet. TEXT-MODE?")}n||a||i.logger.log(2,(function(){return"Couldn't parse cleaned data "+$l([r,s])+" orig: "+$l([e[t],e[t+1]])}))},s=0;s<e.length;s+=2)r(s)},e.parseCmd=function(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;var i=20===t||21===t||23===t?1:2,r=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),this.currentChannel=i,!0},e.parseMidrow=function(t,e){var i=0;if((17===t||25===t)&&e>=32&&e<=47){if((i=17===t?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(e),this.logger.log(3,(function(){return"MIDROW ("+$l([t,e])+")"})),!0)}return!1},e.parsePAC=function(t,e){var i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127||(16===t||24===t)&&e>=64&&e<=95))return!1;var r=t<=23?1:2;i=e>=64&&e<=95?1===r?Ml[t]:Nl[t]:1===r?Fl[t]:Ul[t];var s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,e)),this.currentChannel=r,!0)},e.interpretPAC=function(t,e){var i,r={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r},e.parseChars=function(t,e){var i,r,s=null,n=null;return t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19?(r=17===n?e+80:18===n?e+112:e+144,this.logger.log(2,(function(){return"Special char '"+wl(r)+"' in channel "+i})),s=[r]):t>=32&&t<=127&&(s=0===e?[t]:[t,e]),s&&this.logger.log(3,(function(){return"Char codes = "+$l(s).join(",")})),s},e.parseBackgroundAttributes=function(t,e){var i;if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;var r={};16===t||24===t?(i=Math.floor((e-32)/2),r.background=Bl[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));var s=t<=23?1:2;return this.channels[s].setBkgData(r),!0},e.reset=function(){for(var t=0;t<Object.keys(this.channels).length;t++){var e=this.channels[t];e&&e.reset()}ql(null,null,this.cmdHistory)},e.cueSplitAtTime=function(t){for(var e=0;e<this.channels.length;e++){var i=this.channels[e];i&&i.cueSplitAtTime(t)}},t}();function ql(t,e,i){i.a=t,i.b=e}function Xl(t,e,i){return i.a===t&&i.b===e}function Ql(){return{a:null,b:null}}var zl=function(){if(null!=Wi&&Wi.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var i=e.toLowerCase();return!!~t.indexOf(i)&&i}function r(e){return i(t,e)}function s(t){return i(e,t)}function n(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)t[a]=n[a]}return t}function a(t,e,i){var a=this,o={enumerable:!0};a.hasBeenReset=!1;var l="",h=!1,d=t,u=e,c=i,f=null,g="",m=!0,p="auto",v="start",y=50,E="middle",T=50,S="middle";Object.defineProperty(a,"id",n({},o,{get:function(){return l},set:function(t){l=""+t}})),Object.defineProperty(a,"pauseOnExit",n({},o,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(a,"startTime",n({},o,{get:function(){return d},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"endTime",n({},o,{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(a,"text",n({},o,{get:function(){return c},set:function(t){c=""+t,this.hasBeenReset=!0}})),Object.defineProperty(a,"region",n({},o,{get:function(){return f},set:function(t){f=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"vertical",n({},o,{get:function(){return g},set:function(t){var e=r(t);if(!1===e)throw new SyntaxError("An invalid or illegal string was specified.");g=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"snapToLines",n({},o,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(a,"line",n({},o,{get:function(){return p},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");p=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"lineAlign",n({},o,{get:function(){return v},set:function(t){var e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"position",n({},o,{get:function(){return y},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"positionAlign",n({},o,{get:function(){return E},set:function(t){var e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"size",n({},o,{get:function(){return T},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"align",n({},o,{get:function(){return S},set:function(t){var e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),a.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Zl=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function Jl(t){function e(t,e,i,r){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(r||0)}var i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}var th=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,i){for(var r=0;r<i.length;++r)if(e===i[r]){this.set(t,e);break}},e.integer=function(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))},e.percent=function(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){var i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1},t}();function eh(t,e,i,r){var s=r?t.split(r):[t];for(var n in s)if("string"==typeof s[n]){var a=s[n].split(i);2===a.length&&e(a[0],a[1])}}var ih=new zl(0,0,""),rh="middle"===ih.align?"middle":"center";function sh(t,e,i){var r=t;function s(){var e=Jl(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(t,e){var r=new th;eh(t,(function(t,e){var s;switch(t){case"region":for(var n=i.length-1;n>=0;n--)if(i[n].id===e){r.set(t,i[n].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":s=e.split(","),r.integer(t,s[0]),r.percent(t,s[0])&&r.set("snapToLines",!1),r.alt(t,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",rh,"end"]);break;case"position":s=e.split(","),r.percent(t,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",rh,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",rh,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");var s=r.get("line","auto");"auto"===s&&-1===ih.line&&(s=-1),e.line=s,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",rh);var n=r.get("position","auto");"auto"===n&&50===ih.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),a(),e.endTime=s(),a(),n(t,e)}function nh(t){return t.replace(/<br(?: \/)?>/gi,"\n")}var ah=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new Zl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function i(){var t=e.buffer,i=0;for(t=nh(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;var r=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),r}function r(t){eh(t,(function(t,e){}),/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{var s="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;var n=(s=i()).match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}for(var a=!1;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(a?a=!1:s=i(),e.state){case"HEADER":/:/.test(s)?r(s):s||(e.state="ID");continue;case"NOTE":s||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){e.state="NOTE";break}if(!s)continue;if(e.cue=new zl(0,0,""),e.state="CUE",-1===s.indexOf("--\x3e")){e.cue.id=s;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{sh(s,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":var o=-1!==s.indexOf("--\x3e");if(!s||o&&(a=!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+=s;continue;case"BADCUE":s||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this},e.flush=function(){var 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},t}(),oh=/\r\n|\n\r|\n|\r/g,lh=function(t,e,i){return void 0===i&&(i=0),t.slice(i,i+e.length)===e},hh=function(t){var e=parseInt(t.slice(-3)),i=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),s=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(k(e)&&k(i)&&k(r)&&k(s)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*i,e+=6e4*r,e+=36e5*s};function dh(t,e,i){return rl(t.toString())+rl(e.toString())+rl(i)}var uh=function(t,e,i){var r=t[e],s=t[r.prevCC];if(!s||!s.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;t.ccOffset+=r.start-s.start,r.new=!1,s=t[(r=s).prevCC]}t.presentationOffset=i};function ch(t,e,i,r,s,n,a){var o,l=new ah,h=X(new Uint8Array(t)).trim().replace(oh,"\n").split("\n"),d=[],u=e?An(e.baseTime,e.timescale):0,c="00:00.000",f=0,g=0,m=!0;l.oncue=function(t){var n=i[r],a=i.ccOffset,l=(f-u)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:uh(i,r,l)),l){if(!e)return void(o=new Error("Missing initPTS for VTT MPEGTS"));a=l-i.presentationOffset}var h=t.endTime-t.startTime,c=Cn(9e4*(t.startTime+a-g),9e4*s)/9e4;t.startTime=Math.max(c,0),t.endTime=Math.max(c+h,0);var m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=dh(t.startTime,t.endTime,m)),t.endTime>0&&d.push(t)},l.onparsingerror=function(t){o=t},l.onflush=function(){o?a(o):n(d)},h.forEach((function(t){if(m){if(lh(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach((function(t){lh(t,"LOCAL:")?c=t.slice(6):lh(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{g=hh(c)/1e3}catch(t){o=t}return}""===t&&(m=!1)}l.parse(t+"\n")})),l.flush()}var fh="stpp.ttml.im1t",gh=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,mh=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ph={left:"start",center:"center",right:"end",start:"start",end:"end"};function vh(t,e,i,r){var s=mt(new Uint8Array(t),["mdat"]);if(0!==s.length){var n=s.map((function(t){return X(t)})),a=Tn(e.baseTime,1,e.timescale);try{n.forEach((function(t){return i(yh(t,a))}))}catch(t){r(t)}}else r(new Error("Could not parse IMSC1 mdat"))}function yh(t,e){var i=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((function(t,e){return t[e]=i.getAttribute("ttp:"+e)||r[e],t}),{}),n="preserve"!==i.getAttribute("xml:space"),o=Th(Eh(i,"styling","style")),l=Th(Eh(i,"layout","region")),h=Eh(i,"body","[begin]");return[].map.call(h,(function(t){var i=Sh(t,n);if(!i||!t.hasAttribute("begin"))return null;var r=Ih(t.getAttribute("begin"),s),h=Ih(t.getAttribute("dur"),s),d=Ih(t.getAttribute("end"),s);if(null===r)throw Rh(t);if(null===d){if(null===h)throw Rh(t);d=r+h}var u=new zl(r-e,d-e,i);u.id=dh(u.startTime,u.endTime,u.text);var c=Ah(l[t.getAttribute("region")],o[t.getAttribute("style")],o),f=c.textAlign;if(f){var g=ph[f];g&&(u.lineAlign=g),u.align=f}return a(u,c),u})).filter((function(t){return null!==t}))}function Eh(t,e,i){var r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Th(t){return t.reduce((function(t,e){var i=e.getAttribute("xml:id");return i&&(t[i]=e),t}),{})}function Sh(t,e){return[].slice.call(t.childNodes).reduce((function(t,i,r){var s;return"br"===i.nodeName&&r?t+"\n":null!=(s=i.childNodes)&&s.length?Sh(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent}),"")}function Ah(t,e,i){var r="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),n.reduce((function(i,n){var a=Lh(e,r,n)||Lh(t,r,n)||Lh(s,r,n);return a&&(i[n]=a),i}),{})}function Lh(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Rh(t){return new Error("Could not parse ttml timestamp "+t)}function Ih(t,e){if(!t)return null;var i=Jl(t);return null===i&&(gh.test(t)?i=bh(t,e):mh.test(t)&&(i=kh(t,e))),i}function bh(t,e){var i=gh.exec(t),r=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/e.frameRate}function kh(t,e){var i=mh.exec(t),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}var Dh=function(){function t(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}var e=t.prototype;return e.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},e.newCue=function(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[],this.startTime=null},t}(),_h=function(){function t(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=Oh(),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(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(w.FRAG_LOADING,this.onFragLoading,this),t.on(w.FRAG_LOADED,this.onFragLoaded,this),t.on(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(w.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this)}var e=t.prototype;return e.destroy=function(){var t=this.hls;t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(w.FRAG_LOADING,this.onFragLoading,this),t.off(w.FRAG_LOADED,this.onFragLoaded,this),t.off(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(w.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},e.initCea608Parsers=function(){var t=new Dh(this,"textTrack1"),e=new Dh(this,"textTrack2"),i=new Dh(this,"textTrack3"),r=new Dh(this,"textTrack4");this.cea608Parser1=new jl(1,t,e),this.cea608Parser2=new jl(3,i,r)},e.addCues=function(t,e,i,r,s){for(var n=!1,a=s.length;a--;){var o=s[a],l=wh(o[0],o[1],e,i);if(l>=0&&(o[0]=Math.min(o[0],e),o[1]=Math.max(o[1],i),n=!0,l/(i-e)>.5))return}if(n||s.push([e,i]),this.config.renderTextTracksNatively){var h=this.captionsTracks[t];this.Cues.newCue(h,e,i,r)}else{var d=this.Cues.newCue(null,e,i,r);this.hls.trigger(w.CUES_PARSED,{type:"captions",cues:d,track:t})}},e.onInitPtsFound=function(t,e){var i=this,r=e.frag,s=e.id,n=e.initPTS,a=e.timescale,o=e.trackId,l=this.unparsedVttFrags;s===x.MAIN&&(this.initPTS[r.cc]={baseTime:n,timescale:a,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach((function(t){i.initPTS[t.frag.cc]?i.onFragLoaded(w.FRAG_LOADED,t):i.hls.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))},e.getExistingTrack=function(t,e){var i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var s=i.textTracks[r];if(Ch(s,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null},e.createCaptionsTrack=function(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)},e.createNativeTrack=function(t){if(!this.captionsTracks[t]){var e=this.captionsProperties,i=this.captionsTracks,r=this.media,s=e[t],n=s.label,a=s.languageCode,o=this.getExistingTrack(n,a);if(o)i[t]=o,Il(i[t]),Ll(i[t],r);else{var l=this.createTextTrack("captions",n,a);l&&(l[t]=!0,i[t]=l)}}},e.createNonNativeTrack=function(t){if(!this.nonNativeCaptionsTracks[t]){var e=this.captionsProperties[t];if(e){var i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(w.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}},e.createTextTrack=function(t,e,i){var r=this.media;if(r)return r.addTextTrack(t,e,i)},e.onMediaAttaching=function(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()},e.onMediaDetaching=function(t,e){var i=!!e.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach((function(t){Il(r[t]),delete r[t]})),this.nonNativeCaptionsTracks={}}},e.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Oh(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},e._cleanTracks=function(){var t=this.media;if(t){var e=t.textTracks;if(e)for(var i=0;i<e.length;i++)Il(e[i])}},e.onSubtitleTracksUpdated=function(t,e){var i=this,r=e.subtitleTracks||[],s=r.some((function(t){return t.textCodec===fh}));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(ca(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var n=this.media,a=n?_l(n.textTracks):null;if(this.tracks.forEach((function(t,e){var r;if(a){for(var s=null,n=0;n<a.length;n++)if(a[n]&&Ch(a[n],t)){s=a[n],a[n]=null;break}s&&(r=s)}if(r)Il(r);else{var o=Ph(t);(r=i.createTextTrack(o,t.name,t.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)})),null!=a&&a.length){var o=a.filter((function(t){return null!==t})).map((function(t){return t.label}));o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: "+o.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")}}else if(this.tracks.length){var l=this.tracks.map((function(t){return{label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}}));this.hls.trigger(w.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}},e.onManifestLoaded=function(t,e){var i=this;this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((function(t){var e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(e){var r="textTrack"+e[1],s=i.captionsProperties[r];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)}}))},e.closedCaptionsForLevel=function(t){var e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]},e.onFragLoading=function(t,e){if(this.enabled&&e.frag.type===x.MAIN){var i,r,s=this.cea608Parser1,n=this.cea608Parser2,a=this.lastSn,o=e.frag,l=o.cc,h=o.sn,d=null!=(i=null==(r=e.part)?void 0:r.index)?i:-1;s&&n&&(h!==a+1||h===a&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),n.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=d}},e.onFragLoaded=function(t,e){var i=e.frag,r=e.payload;if(i.type===x.SUBTITLE)if(r.byteLength){var s=i.decryptdata,n="stats"in e;if(null==s||!s.encrypted||n){var a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===fh?this._parseIMSC1(i,r):this._parseVTTs(e)}}else this.hls.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})},e._parseIMSC1=function(t,e){var i=this,r=this.hls;vh(e,this.initPTS[t.cc],(function(e){i._appendCues(e,t.level),r.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(function(e){r.logger.log("Failed to parse IMSC1: "+e),r.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))},e._parseVTTs=function(t){var e,i=this,r=t.frag,s=t.payload,n=this.initPTS,a=this.unparsedVttFrags,o=n.length-1;if(n[r.cc]||-1!==o){var l=this.hls;ch(null!=(e=r.initSegment)&&e.data?Dt(r.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(function(t){i._appendCues(t,r.level),l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(function(e){var n="Missing initPTS for VTT MPEGTS"===e.message;n?a.push(t):i._fallbackToIMSC1(r,s),l.logger.log("Failed to parse VTT cue: "+e),n&&o>r.cc||l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:e})}))}else a.push(t)},e._fallbackToIMSC1=function(t,e){var i=this,r=this.tracks[t.level];r.textCodec||vh(e,this.initPTS[t.cc],(function(){r.textCodec=fh,i._parseIMSC1(t,e)}),(function(){r.textCodec="wvtt"}))},e._appendCues=function(t,e){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[e];if(!r||"disabled"===r.mode)return;t.forEach((function(t){return Rl(r,t)}))}else{var s=this.tracks[e];if(!s)return;var n=s.default?"default":"subtitles"+e;i.trigger(w.CUES_PARSED,{type:"subtitles",cues:t,track:n})}},e.onFragDecrypted=function(t,e){e.frag.type===x.SUBTITLE&&this.onFragLoaded(w.FRAG_LOADED,e)},e.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},e.onFragParsingUserdata=function(t,e){if(this.enabled&&this.config.enableCEA708Captions){var i=e.frag,r=e.samples;if(i.type!==x.MAIN||"NONE"!==this.closedCaptionsForLevel(i))for(var s=0;s<r.length;s++){var n=r[s].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();var a=this.extractCea608Data(n);this.cea608Parser1.addData(r[s].pts,a[0]),this.cea608Parser2.addData(r[s].pts,a[1])}}}},e.onBufferFlushing=function(t,e){var i=e.startOffset,r=e.endOffset,s=e.endOffsetSubtitles,n=e.type,a=this.media;if(a&&!(a.currentTime<r)){if(!n||"video"===n){var o=this.captionsTracks;Object.keys(o).forEach((function(t){return bl(o[t],i,r)}))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==s){var l=this.textTracks;Object.keys(l).forEach((function(t){return bl(l[t],i,s)}))}}},e.extractCea608Data=function(t){for(var e=[[],[]],i=31&t[0],r=2,s=0;s<i;s++){var n=t[r++],a=127&t[r++],o=127&t[r++];if((0!==a||0!==o)&&4&n){var l=3&n;0!==l&&1!==l||(e[l].push(a),e[l].push(o))}}return e},t}();function Ph(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Ch(t,e){return!!t&&t.kind===Ph(e)&&ga(e,t)}function wh(t,e,i,r){return Math.min(e,r)-Math.max(t,i)}function Oh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var xh=/\s/,Mh={newCue:function(t,e,i,r){for(var s,n,a,o,l,h=[],d=self.VTTCue||self.TextTrackCue,u=0;u<r.rows.length;u++)if(a=!0,o=0,l="",!(s=r.rows[u]).isEmpty()){for(var c,f=0;f<s.chars.length;f++)xh.test(s.chars[f].uchar)&&a?o++:(l+=s.chars[f].uchar,a=!1);s.cueStartTime=e,e===i&&(i+=1e-4),o>=16?o--:o++;var g=nh(l.trim()),m=dh(e,i,g);null!=t&&null!=(c=t.cues)&&c.getCueById(m)||((n=new d(e,i,g)).id=m,n.line=u+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(n))}return t&&h.length&&(h.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),h.forEach((function(e){return Rl(t,e)}))),h}};function Fh(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}var Nh=/(\d+)-(\d+)\/(\d+)/,Uh=function(){function t(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||Kh,this.controller=new self.AbortController,this.stats=new Z}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},e.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},e.abort=function(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,i){var r=this,s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();var n=Bh(t,this.controller.signal),a="arraybuffer"===t.responseType,o=a?"byteLength":"length",l=e.loadPolicy,h=l.maxTimeToFirstByteMs,d=l.maxLoadTimeMs;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=h&&k(h)?h:d,this.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,t,r.response))}),e.timeout),(Hn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(i){var n;r.response=r.loader=i;var o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(r.requestTimeout),e.timeout=d,r.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,t,r.response))}),d-(o-s.loading.start)),!i.ok){var l=i.status,h=i.statusText;throw new Vh(h||"fetch, bad network response",l,i)}s.loading.first=o,s.total=$h(i.headers)||s.total;var u=null==(n=r.callbacks)?void 0:n.onProgress;return u&&k(e.highWaterMark)?r.loadProgressively(i,s,t,e.highWaterMark,u):a?i.arrayBuffer():"json"===t.responseType?i.json():i.text()})).then((function(i){var n,a,l=r.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);var h=i[o];h&&(s.loaded=s.total=h);var d={url:l.url,data:i,code:l.status},u=null==(n=r.callbacks)?void 0:n.onProgress;u&&!k(e.highWaterMark)&&u(s,t,i,l),null==(a=r.callbacks)||a.onSuccess(d,s,t,l)})).catch((function(e){var i;if(self.clearTimeout(r.requestTimeout),!s.aborted){var n=e&&e.code||0,a=e?e.message:null;null==(i=r.callbacks)||i.onError({code:n,text:a},t,e?e.details:null,s)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.response?this.response.headers.get(t):null},e.loadProgressively=function(t,e,i,r,s){void 0===r&&(r=0);var n=new Qr,a=t.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return n.dataLength&&s(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return e.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(e,i,n.flush().buffer,t)):s(e,i,l.buffer,t),o()})).catch((function(){return Promise.reject()}))};return o()},t}();function Bh(t,e){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(a({},t.headers))};return t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),i}function Gh(t){var e=Nh.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function $h(t){var e=t.get("Content-Range");if(e){var i=Gh(e);if(k(i))return i}var r=t.get("Content-Length");if(r)return parseInt(r)}function Kh(t,e){return new self.Request(t.url,e)}var Vh=function(t){function e(e,i,r){var s;return(s=t.call(this,e)||this).code=void 0,s.details=void 0,s.code=i,s.details=r,s}return l(e,t),e}(p(Error)),Hh=/^age:\s*[\d.]+\s*$/im,Yh=function(){function t(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 Z,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},e.abortInternal=function(){var 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()))},e.abort=function(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,i){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=i,this.loadInternal()},e.loadInternal=function(){var t=this,e=this.config,i=this.context;if(e&&i){var r=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;var n=this.xhrSetup;n?Promise.resolve().then((function(){if(t.loader===r&&!t.stats.aborted)return n(r,i.url)})).catch((function(e){if(t.loader===r&&!t.stats.aborted)return r.open("GET",i.url,!0),n(r,i.url)})).then((function(){t.loader!==r||t.stats.aborted||t.openAndSendXhr(r,i,e)})).catch((function(e){var n;null==(n=t.callbacks)||n.onError({code:r.status,text:e.message},i,r,s)})):this.openAndSendXhr(r,i,e)}},e.openAndSendXhr=function(t,e,i){t.readyState||t.open("GET",e.url,!0);var r=e.headers,s=i.loadPolicy,n=s.maxTimeToFirstByteMs,a=s.maxLoadTimeMs;if(r)for(var o in r)t.setRequestHeader(o,r[o]);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),i.timeout=n&&k(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()},e.readystatechange=function(){var t=this.context,e=this.loader,i=this.stats;if(t&&e){var r=e.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;var n=e.status,a="text"===e.responseType?e.responseText:null;if(n>=200&&n<300){var o=null!=a?a:e.response;if(null!=o){var l,h;i.loading.end=Math.max(self.performance.now(),i.loading.first);var d="arraybuffer"===e.responseType?o.byteLength:o.length;i.loaded=i.total=d,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var u=null==(l=this.callbacks)?void 0:l.onProgress;u&&u(i,t,o,e);var c={url:e.responseURL,data:o,code:n};return void(null==(h=this.callbacks)||h.onSuccess(c,i,t,e))}}var f,g=s.loadPolicy.errorRetry;Xe(g,i.retry,!1,{url:t.url,data:void 0,code:n})?this.retry(g):(Y.error(n+" while loading "+t.url),null==(f=this.callbacks)||f.onError({code:n,text:e.statusText},t,e,i))}}},e.loadtimeout=function(){if(this.config){var t=this.config.loadPolicy.timeoutRetry;if(Xe(t,this.stats.retry,!0))this.retry(t);else{var e;Y.warn("timeout while loading "+(null==(e=this.context)?void 0:e.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}},e.retry=function(t){var e=this.context,i=this.stats;this.retryDelay=je(t,i.retry),i.retry++,Y.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==e?void 0:e.url)+", retrying "+i.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)},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&Hh.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.loader&&new RegExp("^"+t+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null},t}(),Wh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},jh=c(c({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:Yh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Ne,bufferController:Ta,capLevelController:Ra,errorController:Je,fpsController:il,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:Ji,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:Wh},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},qh()),{},{subtitleStreamController:Sl,subtitleTrackController:Pl,timelineController:_h,audioStreamController:da,audioTrackController:ma,emeController:tl,cmcdController:jo,contentSteeringController:Xo,interstitialsController:El});function qh(){return{cueHandler:Mh,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Xh(t,e,i){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"');var r=Qh(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(t){var n=("level"===t?"playlist":t)+"LoadPolicy",a=void 0===e[n],o=[];s.forEach((function(i){var s=t+"Loading"+i,l=e[s];if(void 0!==l&&a){o.push(s);var h=r[n].default;switch(e[n]={default:h},i){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+n+'": '+Le(e[n]))})),c(c({},r),e)}function Qh(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Qh):Object.keys(t).reduce((function(e,i){return e[i]=Qh(t[i]),e}),{}):t}function zh(t,e){var i=t.loader;i!==Uh&&i!==Yh?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):Fh()&&(t.loader=Uh,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Zh=2,Jh=.1,td=.05,ed=100,id=function(t){function e(e,i){var r;return(r=t.call(this,"gap-controller",e.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var t;null!=(t=r.media)&&t.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var t;r.hls&&(r.ended=(null==(t=r.media)?void 0:t.currentTime)||1,r.hls.trigger(w.MEDIA_ENDED,{stalled:!1}))},r.hls=e,r.fragmentTracker=i,r.registerListeners(),r}l(e,t);var i=e.prototype;return i.registerListeners=function(){var t=this.hls;t&&(t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.BUFFER_APPENDED,this.onBufferAppended,this))},i.unregisterListeners=function(){var t=this.hls;t&&(t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.BUFFER_APPENDED,this.onBufferAppended,this))},i.destroy=function(){t.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},i.onMediaAttached=function(t,e){this.setInterval(ed),this.mediaSource=e.mediaSource;var i=this.media=e.media;Zo(i,"playing",this.onMediaPlaying),Zo(i,"waiting",this.onMediaWaiting),Zo(i,"ended",this.onMediaEnded)},i.onMediaDetaching=function(t,e){this.clearInterval();var i=this.media;i&&(Jo(i,"playing",this.onMediaPlaying),Jo(i,"waiting",this.onMediaWaiting),Jo(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},i.onBufferAppended=function(t,e){this.buffered=e.timeRanges},i.tick=function(){var t;if(null!=(t=this.media)&&t.readyState&&this.hasBuffered){var e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}},i.poll=function(t,e){var i,r,s=null==(i=this.hls)?void 0:i.config;if(s){var n=this.media;if(n){var a=n.seeking,o=this.seeking&&!a,l=!this.seeking&&a,h=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,s.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)o&&this.stallResolved(t);else{if(h)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(w.MEDIA_ENDED,{stalled:!1})));if(Ri.getBuffered(n).length){var d=Ri.bufferInfo(n,t,0),u=d.nextStart||0,c=this.fragmentTracker;if(a&&c&&this.hls){var f=rd(this.hls.inFlightFragments,t),g=d.len>Zh,m=!u||f||u-t>Zh&&!c.getPartialFragment(t);if(g||m)return;this.moved=!1}var p=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(d.len>0||u))return;var v=Math.max(u,d.start||0)-t,y=null!=p&&p.live?2*p.targetduration:Zh,E=nd(t,c);if(v>0&&(v<=y||E))return void(n.paused||this._trySkipBufferHole(E))}var T=s.detectStallWithCurrentTimeMs,S=self.performance.now(),A=this.waiting,L=this.stalled;if(null===L){if(!(A>0&&S-A<T))return void(this.stalled=S);L=this.stalled=A}var R=S-L;if(!a&&(R>=T||A)&&this.hls){var I;if("ended"===(null==(I=this.mediaSource)?void 0:I.readyState)&&(null==p||!p.live)&&Math.abs(t-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(w.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}var b=Ri.bufferInfo(n,t,s.maxBufferHole);this._tryFixBufferStall(b,R,t)}else this.nudgeRetry=0}}}},i.stallResolved=function(t){var e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-e;this.log("playback not stuck anymore @"+t+", after "+Math.round(i)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(w.STALL_RESOLVED,{})}},i.nudgeOnVideoHole=function(t,e){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&t>r.end(0)){var s=Ri.bufferedInfo(Ri.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&e>=s.start){var n=Ri.timeRangesToArray(r),a=Ri.bufferedInfo(n,e,0).bufferedIndex;if(a>-1&&a<n.length-1){var o=Ri.bufferedInfo(n,t,0).bufferedIndex,l=n[a].end,h=n[a+1].start;if((-1===o||o>a)&&h-l<1&&t-l<2){var d=new Error("nudging playhead to flush pipeline after video hole. currentTime: "+t+" hole: "+l+" -> "+h+" buffered index: "+o);this.warn(d.message),this.media.currentTime+=1e-6;var u=nd(t,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);var c=Ri.bufferInfo(this.media,t,0);this.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:u,buffer:c.len,bufferInfo:c})}}}}},i._tryFixBufferStall=function(t,e,i){var r,s,n=this.fragmentTracker,a=this.media,o=null==(r=this.hls)?void 0:r.config;if(a&&n&&o){var l=null==(s=this.hls)?void 0:s.latestLevelDetails,h=nd(i,n);if((h||null!=l&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;var d=t.buffered,u=this.adjacentTraversal(t,i);(d&&d.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}},i.adjacentTraversal=function(t,e){var i=this.fragmentTracker,r=t.nextStart;if(i&&r){var s=i.getFragAtPos(e,x.MAIN),n=i.getFragAtPos(r,x.MAIN);if(s&&n)return n.sn-s.sn<2}return!1},i._reportStall=function(t){var e=this.hls,i=this.media,r=this.stallReported,s=this.stalled;if(!r&&null!==s&&i&&e){this.stallReported=!0;var n=new Error("Playback stalling at @"+i.currentTime+" due to low buffer ("+Le(t)+")");this.warn(n.message),e.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:t.len,bufferInfo:t,stalled:{start:s}})}},i._trySkipBufferHole=function(t){var e,i=this.fragmentTracker,r=this.media,s=null==(e=this.hls)?void 0:e.config;if(!r||!i||!s)return 0;var n=r.currentTime,a=Ri.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){var l=a.len<=s.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,d=o-n;if(d>0&&(l||h)){if(d>s.maxBufferHole){var u=!1;if(0===n){var c=i.getAppendedFrag(0,x.MAIN);c&&o<c.end&&(u=!0)}if(!u&&t){var f;if(null==(f=this.hls.loadLevelObj)||!f.details)return 0;if(rd(this.hls.inFlightFragments,o))return 0;for(var g=!1,m=t.end;m<o;){var p=nd(m,i);if(!p){g=!0;break}m+=p.duration}if(g)return 0}}var v=Math.max(o+td,n+Jh);if(this.warn("skipping hole, adjusting currentTime from "+n+" to "+v),this.moved=!0,r.currentTime=v,null==t||!t.gap){var y=new Error("fragment loaded with buffer holes, seeking from "+n+" to "+v),E={type:P.MEDIA_ERROR,details:C.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?E.part=t:E.frag=t),this.hls.trigger(w.ERROR,E)}return v}}return 0},i._tryNudgeBuffer=function(t){var e=this.hls,i=this.media,r=this.nudgeRetry,s=null==e?void 0:e.config;if(!i||!s)return 0;var n=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){var a=n+(r+1)*s.nudgeOffset,o=new Error("Nudging 'currentTime' from "+n+" to "+a);this.warn(o.message),i.currentTime=a,e.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{var l=new Error("Playhead still not moving while enough data buffered @"+n+" after "+s.nudgeMaxRetry+" nudges");this.error(l.message),e.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:t.len,bufferInfo:t})}},s(e,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}(Ti);function rd(t,e){var i=sd(t.main);if(i&&i.start<=e)return i;var r=sd(t.audio);return r&&r.start<=e?r:null}function sd(t){if(!t)return null;switch(t.state){case jr.IDLE:case jr.STOPPED:case jr.ENDED:case jr.ERROR:return null}return t.frag}function nd(t,e){return e.getAppendedFrag(t,x.MAIN)||e.getPartialFragment(t)}var ad=.25;function od(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ld(t,e,i,r,s){var n=new t(e,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new t(e,i,Le(s?c({type:s},r):r))}return n}var hd=function(){var t=od();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),dd=function(){function t(t){var e=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){e.hls&&e.hls.trigger(w.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}var e=t.prototype;return e.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null},e._registerListeners=function(){var t=this.hls;t&&(t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(w.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},e._unregisterListeners=function(){var t=this.hls;t&&(t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(w.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},e.onMediaAttaching=function(t,e){var i;this.media=e.media,!1===(null==(i=e.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)},e.onMediaAttached=function(){var t,e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)},e.onMediaDetaching=function(t,e){this.media=null,e.transferMedia||(this.id3Track&&(this.removeCues&&Il(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},e.onManifestLoading=function(){this.dateRangeCuesAppended={}},e.createTrack=function(t){var e=this.getID3Track(t.textTracks);return e.mode="hidden",e},e.getID3Track=function(t){if(this.media){for(var e=0;e<t.length;e++){var i=t[e];if("metadata"===i.kind&&"id3"===i.label)return Ll(i,this.media),i}return this.media.addTextTrack("metadata","id3")}},e.onFragParsingMetadata=function(t,e){if(this.media&&this.hls){var i=this.hls.config,r=i.enableEmsgMetadataCues,s=i.enableID3MetadataCues;if(r||s){var n=e.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=od();if(a)for(var o=0;o<n.length;o++){var l=n[o].type;if((l!==ws.emsg||r)&&s){var h=Ds(n[o].data),d=n[o].pts,u=d+n[o].duration;u>hd&&(u=hd),u-d<=0&&(u=d+ad);for(var c=0;c<h.length;c++){var f=h[c];if(!_s(f)){this.updateId3CueEnds(d,l);var g=ld(a,d,u,f,l);g&&this.id3Track.addCue(g)}}}}}}},e.updateId3CueEnds=function(t,e){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var s=r.length;s--;){var n=r[s];n.type===e&&n.startTime<t&&n.endTime===hd&&(n.endTime=t)}},e.onBufferFlushing=function(t,e){var i=e.startOffset,r=e.endOffset,s=e.type,n=this.id3Track,a=this.hls;if(a){var o=a.config,l=o.enableEmsgMetadataCues,h=o.enableID3MetadataCues;n&&(l||h)&&bl(n,i,r,"audio"===s?function(t){return t.type===ws.audioId3&&h}:"video"===s?function(t){return t.type===ws.emsg&&l}:function(t){return t.type===ws.audioId3&&h||t.type===ws.emsg&&l})}},e.onLevelUpdated=function(t,e){var i=e.details;this.updateDateRangeCues(i,!0)},e.onLevelPtsUpdated=function(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)},e.updateDateRangeCues=function(t,e){var i=this;if(this.hls&&this.media){var r=this.hls.config,s=r.assetPlayerId,n=r.timelineOffset,a=r.enableDateRangeMetadataCues,o=r.interstitialsController;if(a){var l=od();if(s&&n&&!o){var h=t.fragmentStart,d=t.fragmentEnd,u=this.assetCue;u?(u.startTime=h,u.endTime=d):l&&(u=this.assetCue=ld(l,h,d,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(u.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(u),u.addEventListener("enter",this.onEventCueEnter))}if(t.hasProgramDateTime){var c,f=this.id3Track,g=t.dateRanges,m=Object.keys(g),p=this.dateRangeCuesAppended;if(f&&e)if(null!=(c=f.cues)&&c.length)for(var v=Object.keys(p).filter((function(t){return!m.includes(t)})),y=function(){var t,e=v[E],r=null==(t=p[e])?void 0:t.cues;delete p[e],r&&Object.keys(r).forEach((function(t){var e=r[t];if(e){e.removeEventListener("enter",i.onEventCueEnter);try{f.removeCue(e)}catch(t){}}}))},E=v.length;E--;)y();else p=this.dateRangeCuesAppended={};var T=t.fragments[t.fragments.length-1];if(0!==m.length&&k(null==T?void 0:T.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var t=m[A],e=g[t],r=e.startTime,s=p[t],n=(null==s?void 0:s.cues)||{},a=(null==s?void 0:s.durationKnown)||!1,h=hd,d=e.duration;if(e.endDate&&null!==d)h=r+d,a=!0;else if(e.endOnNext&&!a){var u=m.reduce((function(t,i){if(i!==e.id){var r=g[i];if(r.class===e.class&&r.startDate>e.startDate&&(!t||e.startDate<t.startDate))return r}return t}),null);u&&(h=u.startTime,a=!0)}for(var c=Object.keys(e.attr),f=0;f<c.length;f++){var v=c[f];if(xi(v)){var y=n[v];if(y)!a||null!=s&&s.durationKnown?Math.abs(y.startTime-r)>.01&&(y.startTime=r,y.endTime=h):y.endTime=h;else if(l){var E=e.attr[v];Mi(v)&&(E=z(E));var T=ld(l,r,h,{key:v,data:E},ws.dateRange);T&&(T.id=t,i.id3Track.addCue(T),n[v]=T,o&&("X-ASSET-LIST"!==v&&"X-ASSET-URL"!==v||T.addEventListener("enter",i.onEventCueEnter)))}}}p[t]={cues:n,dateRange:e,durationKnown:a}},A=0;A<m.length;A++)S()}}}}},t}(),ud=function(){function t(t){var e=this;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=function(){var t=e.media,i=e.levelDetails;if(t&&i){e.currentTime=t.currentTime;var r=e.computeLatency();if(null!==r){e._latency=r;var s=e.config,n=s.lowLatencyMode,a=s.maxLiveSyncPlaybackRate;if(n&&1!==a&&i.live){var o=e.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(e.maxLatency,o+i.targetduration)&&l>.05&&e.forwardBufferLength>1){var h=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*l-e.edgeStalled))*20)/20,u=Math.min(h,Math.max(1,d));e.changeMediaPlaybackRate(t,u)}else 1!==t.playbackRate&&0!==t.playbackRate&&e.changeMediaPlaybackRate(t,1)}}}}},this.hls=t,this.config=t.config,this.registerListeners()}var e=t.prototype;return e.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},e.registerListeners=function(){var t=this.hls;t&&(t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(w.ERROR,this.onError,this))},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(w.ERROR,this.onError,this))},e.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)},e.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},e.onManifestLoading=function(){this._latency=null,this.stallCount=0},e.onLevelUpdated=function(t,e){var i=e.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},e.onError=function(t,e){var i;e.details===C.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},e.changeMediaPlaybackRate=function(t,e){var i,r;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(r=this.targetLatency)?void 0:r.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+t.playbackRate+" to "+e),t.playbackRate=e)},e.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},e.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},s(t,[{key:"levelDetails",get:function(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;var e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t||null===this.hls)return null;var e=t.holdBack,i=t.partHoldBack,r=t.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&i||e;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*r);var d=r;return h+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)},set:function(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;var i=this.levelDetails;if(null===i)return null;var r=i.edge,s=t-e-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}}])}(),cd=function(t){function e(e,i){var r;return(r=t.call(this,e,"level-controller")||this)._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,r._registerListeners(),r}l(e,t);var i=e.prototype;return i._registerListeners=function(){var t=this.hls;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(w.LEVEL_LOADED,this.onLevelLoaded,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this),t.on(w.ERROR,this.onError,this)},i._unregisterListeners=function(){var t=this.hls;t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(w.LEVEL_LOADED,this.onLevelLoaded,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this),t.off(w.ERROR,this.onError,this)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),t.prototype.destroy.call(this)},i.stopLoad=function(){this._levels.forEach((function(t){t.loadError=0,t.fragmentError=0})),t.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(t,e){this.resetLevels()},i.onManifestLoaded=function(t,e){var i=this,r=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,h=!1;e.levels.forEach((function(t){var e=t.attrs,d=t.audioCodec,u=t.videoCodec;d&&(t.audioCodec=d=qt(d,r)||void 0),u&&(u=t.videoCodec=Zt(u));var c=t.width,f=t.height,g=t.unknownCodecs,m=g?g.length:0;if(g)for(var p=m;p--;){var v=g[p];i.isAudioSupported(v)?(t.audioCodec=d=d?d+","+v:v,m--,Ut.audio[d.substring(0,4)]=2):i.isVideoSupported(v)&&(t.videoCodec=u=u?u+","+v:v,m--,Ut.video[u.substring(0,4)]=2)}if(o||(o=!(!c||!f)),l||(l=!!u),h||(h=!!d),m||d&&!i.isAudioSupported(d)||u&&!i.isVideoSupported(u))i.log('Some or all CODECS not supported "'+e.CODECS+'"');else{var y=e.CODECS,E=e["FRAME-RATE"],T=e["HDCP-LEVEL"],S=e["PATHWAY-ID"],A=e.RESOLUTION,L=e["VIDEO-RANGE"],R=(S||".")+"-"+t.bitrate+"-"+A+"-"+E+"-"+y+"-"+L+"-"+T;if(n[R])if(n[R].uri===t.url||t.attrs["PATHWAY-ID"])n[R].addGroupId("audio",e.AUDIO),n[R].addGroupId("text",e.SUBTITLES);else{var I=a[R]+=1;t.attrs["PATHWAY-ID"]=new Array(I+1).join(".");var b=i.createLevel(t);n[R]=b,s.push(b)}else{var k=i.createLevel(t);n[R]=k,a[R]=1,s.push(k)}}})),this.filterAndSortMediaOptions(s,e,o,l,h)},i.createLevel=function(t){var e=new ye(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'+i.videoCodec+'"');this.log(r.message),e.supportedResult=re(r,[])}return e},i.isAudioSupported=function(t){return Gt(t,"audio",this.hls.config.preferManagedMediaSource)},i.isVideoSupported=function(t){return Gt(t,"video",this.hls.config.preferManagedMediaSource)},i.filterAndSortMediaOptions=function(t,e,i,r,s){var n=this,a=[],o=[],l=t;if((i||r)&&s&&(l=l.filter((function(t){var e=t.videoCodec,i=t.videoRange,r=t.width,s=t.height;return(!!e||!(!r||!s))&&ge(i)}))),0!==l.length){e.audioTracks&&fd(a=e.audioTracks.filter((function(t){return!t.audioCodec||n.isAudioSupported(t.audioCodec)}))),e.subtitles&&fd(o=e.subtitles);var h=l.slice(0);l.sort((function(t,e){if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&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 fe.indexOf(t.videoRange)-fe.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){var r=Vt(t.videoCodec),s=Vt(e.videoCodec);if(r!==s)return s-r}if(t.uri===e.uri&&t.codecSet!==e.codecSet){var n=Ht(t.codecSet),a=Ht(e.codecSet);if(n!==a)return a-n}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));var d=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==h.length)for(var u=0;u<h.length;u++)if(h[u].pathwayId===l[0].pathwayId){d=h[u];break}this._levels=l;for(var c=0;c<l.length;c++)if(l[c]===d){var f;this._firstLevel=c;var g=d.bitrate,m=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+l.length+" level(s) found, first bitrate: "+g),void 0===(null==(f=this.hls.userConfig)?void 0:f.abrEwmaDefaultEstimate)){var p=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);p>m&&m===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=p)}break}var v=s&&!r,y=this.hls.config,E=!(!y.audioStreamController||!y.audioTrackController),T={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:r,altAudio:E&&!v&&a.some((function(t){return!!t.url}))};this.hls.trigger(w.MANIFEST_PARSED,T)}else Promise.resolve().then((function(){if(n.hls){var t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i="one or more CODECS in variant not supported: "+Le(e.levels.map((function(t){return t.attrs.CODECS})).filter((function(t,e,i){return i.indexOf(t)===e}))),n.warn(i),t+=" ("+i+")");var r=new Error(t);n.hls.trigger(w.ERROR,{type:P.MEDIA_ERROR,details:C.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:r,reason:i})}}))},i.onError=function(t,e){!e.fatal&&e.context&&e.context.type===O.LEVEL&&e.context.level===this.level&&this.checkRetry(e)},i.onFragBuffered=function(t,e){var i=e.frag;if(void 0!==i&&i.type===x.MAIN){var r=i.elementaryStreams;if(!Object.keys(r).some((function(t){return!!r[t]})))return;var s=this._levels[i.level];null!=s&&s.loadError&&(this.log("Resetting level error count of "+s.loadError+" on frag buffered"),s.loadError=0)}},i.onLevelLoaded=function(t,e){var i,r,s=e.level,n=e.details,a=e.levelInfo;if(!a)return this.warn("Invalid level index "+s),void(null!=(r=e.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0));if(a===this.currentLevel||e.withoutMultiVariant){0===a.fragmentError&&(a.loadError=0);var o=a.details;o===e.details&&o.advanced&&(o=void 0),this.playlistLoaded(s,e,o)}else null!=(i=e.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0)},i.loadPlaylist=function(e){t.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)},i.loadingPlaylist=function(e,i){t.prototype.loadingPlaylist.call(this,e,i);var r=this.getUrlWithDirectives(e.uri,i),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=null==a?void 0:a.age;this.log("Loading level index "+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(n?" Pathway "+n:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type?" "+a.type||0:""):"")+" "+r),this.hls.trigger(w.LEVEL_LOADING,{url:r,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||null})},i.removeLevel=function(t){var e,i=this;if(1!==this._levels.length){var r=this._levels.filter((function(e,r){return r!==t||(i.steering&&i.steering.removeLevel(e),e===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((function(t){return t.level=-1}))),!1)}));Ur(r),this._levels=r,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var s=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(w.LEVELS_UPDATED,{levels:r})}},i.onLevelsUpdated=function(t,e){var i=e.levels;this._levels=i},i.checkMaxAutoUpdated=function(){var t=this.hls,e=t.autoLevelCapping,i=t.maxAutoLevel,r=t.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(w.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))},s(e,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e=this._levels;if(0!==e.length){if(t<0||t>=e.length){var i=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:i,reason:i.message}),r)return;t=Math.min(t,e.length-1)}var s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,o=e[t],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=o,s!==t||!n||a!==l){this.log("Switching to level "+t+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+s+(a?" with Pathway "+a:""));var h={level:t,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(w.LEVEL_SWITCHING,h);var d=o.details;if(!d||d.live){var u=this.switchParams(o.uri,null==n?void 0:n.details,d);this.loadPlaylist(u)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(t){if(this.steering){var e=this.steering.pathways(),i=t.filter((function(t){return-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=i}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])}(ua);function fd(t){var e={};t.forEach((function(t){var i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++}))}function gd(){return self.SourceBuffer||self.WebKitSourceBuffer}function md(){if(!W())return!1;var t=gd();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}function pd(){if(!md())return!1;var t=W();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(e){return t.isTypeSupported(Kt(e,"video"))}))||["mp4a.40.2","fLaC"].some((function(e){return t.isTypeSupported(Kt(e,"audio"))})))}function vd(){var t,e=gd();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}var yd=100,Ed=function(t){function e(e,i,r){var s;return(s=t.call(this,e,i,r,"stream-controller",x.MAIN)||this).audioCodecSwap=!1,s.level=-1,s._forceStartLoad=!1,s._hasEnoughToStart=!1,s.altAudio=0,s.audioOnly=!1,s.fragPlaying=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s.onMediaPlaying=function(){s.tick()},s.onMediaSeeked=function(){var t=s.media,e=t?t.currentTime:null;if(null!==e&&k(e)&&(s.log("Media seeked to "+e.toFixed(3)),s.getBufferedFrag(e))){var i=s.getFwdBufferInfoAtPos(t,e,x.MAIN,0);null!==i&&0!==i.len?s.tick():s.warn("Main forward buffer length at "+e+' on "seeked" event '+(i?i.len:"empty")+")")}},s.registerListeners(),s}l(e,t);var i=e.prototype;return i.registerListeners=function(){t.prototype.registerListeners.call(this);var e=this.hls;e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(w.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this),e.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){t.prototype.unregisterListeners.call(this);var e=this.hls;e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(w.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this),e.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this)},i.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),t.prototype.onHandlerDestroying.call(this)},i.startLoad=function(t,e){if(this.levels){var i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(yd),this.level=-1,!this.startFragRequested){var s=r.startLevel;-1===s&&(r.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=r.firstAutoLevel),r.nextLoadLevel=s,this.level=r.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),t=i),this.state=jr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=jr.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case jr.WAITING_LEVEL:var t=this.levels,e=this.level,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=jr.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=jr.IDLE;break}break;case jr.FRAG_LOADING_WAITING_RETRY:var s,n=self.performance.now(),a=this.retryDate;if(!a||n>=a||null!=(s=this.media)&&s.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=jr.IDLE}}this.state===jr.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){var e;t.prototype.onTickEnd.call(this),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},i.doTickIdle=function(){var t=this.hls,e=this.levelLastLoaded,i=this.levels,r=this.media;if(null!==e&&(r||this.primaryPrefetch||!this.startFragRequested&&t.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var s=this.buffering?t.nextLoadLevel:t.loadLevel;if(null!=i&&i[s]){var n=i[s],a=this.getMainFwdBufferInfo();if(null!==a){var o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(w.BUFFER_EOS,l),void(this.state=jr.ENDED)}if(this.buffering){t.loadLevel!==s&&-1===t.manualLevel&&this.log("Adapting to level "+s+" from level "+this.level),this.level=t.nextLoadLevel=s;var h=n.details;if(!h||this.state===jr.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=jr.WAITING_LEVEL,void(this.startFragRequested=!1);var d=a.len,u=this.getMaxBufferLength(n.maxBitrate);if(!(d>=u)){this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:a.end,f=this.getNextFragment(c,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&et(f)&&this.fragmentTracker.getState(f)!==ei.OK){var g,m=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,p=h.fragments[m-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var v=this.audioOnly&&!this.altAudio?J.AUDIO:J.VIDEO,y=(v===J.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,v,x.MAIN)}f=this.getNextFragmentLoopLoading(f,h,a,x.MAIN,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}}}}}},i.loadFragment=function(e,i,r){var s=this.fragmentTracker.getState(e);s===ei.NOT_LOADED||s===ei.PARTIAL?et(e)?this.bitrateTest?(this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e,i)):t.prototype.loadFragment.call(this,e,i,r):this._loadInitSegment(e,i):this.clearTrackerIfNeeded(e)},i.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,x.MAIN)},i.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var i,r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);var s=this.getLevelDetails();if(null!=s&&s.live){var n=this.getMainFwdBufferInfo();if(!n||n.len<2*s.targetduration)return}if(!e.paused&&t){var a=t[this.hls.nextLoadLevel],o=this.fragLastKbps;i=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(e.currentTime+i);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var d=h.maxStartPTS?h.maxStartPTS:h.start,u=h.duration,c=Math.max(l.end,d+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case jr.KEY_LOADING:case jr.FRAG_LOADING:case jr.FRAG_LOADING_WAITING_RETRY:case jr.PARSING:case jr.PARSED:this.state=jr.IDLE}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(e,i){t.prototype.flushMainBuffer.call(this,e,i,2===this.altAudio?"video":null)},i.onMediaAttached=function(e,i){t.prototype.onMediaAttached.call(this,e,i);var r=i.media;Zo(r,"playing",this.onMediaPlaying),Zo(r,"seeked",this.onMediaSeeked)},i.onMediaDetaching=function(e,i){var r=this.media;r&&(Jo(r,"playing",this.onMediaPlaying),Jo(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,t.prototype.onMediaDetaching.call(this,e,i),i.transferMedia||(this._hasEnoughToStart=!1)},i.onManifestLoading=function(){t.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(w.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},i.onManifestParsed=function(t,e){for(var i=!1,r=!1,s=0;s<e.levels.length;s++){var n=e.levels[s].audioCodec;n&&(i=i||-1!==n.indexOf("mp4a.40.2"),r=r||-1!==n.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&r&&!vd(),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},i.onLevelLoading=function(t,e){if(this.levels&&this.state===jr.IDLE){var i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=jr.WAITING_LEVEL)}},i.onLevelLoaded=function(t,e){var i,r=this.levels,s=this.startFragRequested,n=e.level,a=e.details,o=a.totalduration;if(r){this.log("Level "+n+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+", cc ["+a.startCC+", "+a.endCC+"] duration:"+o);var l=e.levelInfo,h=this.fragCurrent;!h||this.state!==jr.FRAG_LOADING&&this.state!==jr.FRAG_LOADING_WAITING_RETRY||h.level!==e.level&&h.loader&&this.abortCurrentFrag();var d=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,d),this.hls.trigger(w.LEVEL_UPDATED,{details:a,level:n}),this.state===jr.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=jr.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+n)},i.synchronizeToLiveEdge=function(t){var e=this.config,i=this.media;if(i){var r=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){var l=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn("Playback: "+s.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+r.toFixed(3)),"buffered"===this.config.liveSyncMode){var h,d=Ri.bufferInfo(i,r,0);if(null==(h=d.buffered)||!h.length)return void(i.currentTime=r);if(d.start<=s)return void(i.currentTime=r);var u=Ri.bufferedInfo(d.buffered,s,0).nextStart;u&&(i.currentTime=u)}else i.currentTime=r}}},i._handleFragmentLoadProgress=function(t){var e,i=t.frag,r=t.part,s=t.payload,n=this.levels;if(n){var a=n[i.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+i.sn+" of level "+i.level+" after level details were reset"),void this.fragmentTracker.removeFragment(i);var l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new la(this.hls,x.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Si(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];c.push(s,d,u,l,i,r,o.totalduration,h,m,p)}else this.warn("Level "+i.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i.onAudioTrackSwitching=function(t,e){var i=this,r=this.hls,s=2===this.altAudio;if(Fe(e.url,r))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;var n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),r.once(w.BUFFER_FLUSHED,(function(){i.hls&&i.hls.trigger(w.AUDIO_TRACK_SWITCHED,e)})),void r.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(w.AUDIO_TRACK_SWITCHED,e)}},i.onAudioTrackSwitched=function(t,e){var i=Fe(e.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()},i.onBufferCreated=function(t,e){var i,r,s=e.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(r=a,i=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.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},i.onFragBuffered=function(t,e){var i=e.frag,r=e.part,s=i.type===x.MAIN;if(s){if(this.fragContextChanged(i))return this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===jr.PARSED&&(this.state=jr.IDLE));var n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),et(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var a=this.media;a&&(!this._hasEnoughToStart&&Ri.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())},i.onError=function(t,e){var i;if(e.fatal)this.state=jr.ERROR;else switch(e.details){case C.FRAG_GAP:case C.FRAG_PARSING_ERROR:case C.FRAG_DECRYPT_ERROR:case C.FRAG_LOAD_ERROR:case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_ERROR:case C.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(x.MAIN,e);break;case C.LEVEL_LOAD_ERROR:case C.LEVEL_LOAD_TIMEOUT:case C.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==jr.WAITING_LEVEL||(null==(i=e.context)?void 0:i.type)!==O.LEVEL||(this.state=jr.IDLE);break;case C.BUFFER_ADD_CODEC_ERROR:case C.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case C.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 C.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}},i.onFragLoadEmergencyAborted=function(){this.state=jr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},i.onBufferFlushed=function(t,e){var i=e.type;if(i!==J.AUDIO||!this.altAudio){var r=(i===J.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,x.MAIN),this.tick())}},i.onLevelsUpdated=function(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var t=this.media;if(t){var e=t.currentTime,i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log("could not seek to "+i+", already seeking at "+e);var r=this.timelineOffset;r&&i&&(i+=r);var s=this.getLevelDetails(),n=Ri.getBuffered(t),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log("adjusting start position by "+o+" to match buffer start"),i+=o,this.startPosition=i),e<i&&(this.log("seek to target start position "+i+" from current time "+e+" buffer start "+a),t.currentTime=i)}}},i._getAudioCodec=function(t){var 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},i._loadBitrateTestFrag=function(t,e){var i=this;t.bitrateTest=!0,this._doFragLoad(t,e).then((function(t){var r=i.hls,s=null==t?void 0:t.frag;if(s&&!i.fragContextChanged(s)){e.fragmentError=0,i.state=jr.IDLE,i.startFragRequested=!1,i.bitrateTest=!1;var n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(w.FRAG_LOADED,t),s.bitrateTest=!1}}))},i._handleTransmuxComplete=function(t){var e=this.playlistType,i=this.hls,r=t.remuxResult,s=t.chunkMeta,n=this.getCurrentContext(s);if(n){var a=n.frag,o=n.part,l=n.level,h=r.video,d=r.text,u=r.id3,c=r.initSegment,f=l.details,g=this.altAudio?void 0:r.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=jr.PARSING,c){var m=c.tracks;if(m){var p=a.initSegment||a;if(this.unhandledEncryptionError(c,a))return;this._bufferInitSegment(l,m,p,s),i.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:e,tracks:m})}var v=c.initPTS,y=c.timescale,E=this.initPTS[a.cc];if(k(v)&&(!E||E.baseTime!==v||E.timescale!==y)){var T=c.trackId;this.initPTS[a.cc]={baseTime:v,timescale:y,trackId:T},i.trigger(w.INIT_PTS_FOUND,{frag:a,id:e,initPTS:v,timescale:y,trackId:T})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);var S=f.fragments[a.sn-1-f.startSN],A=a.sn===f.startSN,L=!S||a.cc>S.cc;if(!1!==r.independent){var R=h.startPTS,I=h.endPTS,b=h.startDTS,D=h.endDTS;if(o)o.elementaryStreams[h.type]={startPTS:R,endPTS:I,startDTS:b,endDTS:D};else if(h.firstKeyFrame&&h.independent&&1===s.id&&!L&&(this.couldBacktrack=!0),h.dropped&&h.independent){var _=this.getMainFwdBufferInfo(),P=(_?_.end:this.getLoadPosition())+this.config.maxBufferHole,C=h.firstKeyFramePTS?h.firstKeyFramePTS:R;if(!A&&P<C-this.config.maxBufferHole&&!L)return void this.backtrack(a);L&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,I,a.start,D,!0)}else A&&R-(f.appliedTimelineOffset||0)>Zh&&(a.gap=!0);a.setElementaryStreamInfo(h.type,R,I,b,D),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,s,A||L)}else{if(!A&&!L)return void this.backtrack(a);a.gap=!0}}if(g){var O=g.startPTS,x=g.endPTS,M=g.startDTS,F=g.endDTS;o&&(o.elementaryStreams[J.AUDIO]={startPTS:O,endPTS:x,startDTS:M,endDTS:F}),a.setElementaryStreamInfo(J.AUDIO,O,x,M,F),this.bufferFragmentData(g,a,o,s)}if(f&&null!=u&&u.samples.length){var N={id:e,frag:a,details:f,samples:u.samples};i.trigger(w.FRAG_PARSING_METADATA,N)}if(f&&d){var U={id:e,frag:a,details:f,samples:d.samples};i.trigger(w.FRAG_PARSING_USERDATA,U)}}}else this.resetWhenMissingContext(s)},i.logMuxedErr=function(t){this.warn((et(t)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+t.url)},i._bufferInitSegment=function(t,e,i,r){var s=this;if(this.state===jr.PARSING){this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));var n=e.audio,a=e.video,o=e.audiovideo;if(n){var l=t.audioCodec,h=Qt(n.codec,l);"mp4a"===h&&(h="mp4a.40.5");var d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h=-1!==h.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var u=n.metadata;u&&"channelCount"in u&&1!==(u.channelCount||1)&&-1===d.indexOf("firefox")&&(h="mp4a.40.5")}h&&-1!==h.indexOf("mp4a.40.5")&&-1!==d.indexOf("android")&&"audio/mpeg"!==n.container&&(h="mp4a.40.2",this.log("Android: force audio codec to "+h)),l&&l!==h&&this.log('Swapping manifest audio codec "'+l+'" for "'+h+'"'),n.levelCodec=h,n.id=x.MAIN,this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(h||"")+"/"+(l||"")+"/"+n.codec+"]"),delete e.audiovideo}if(a){a.levelCodec=t.videoCodec,a.id=x.MAIN;var c=a.codec;if(4===(null==c?void 0:c.length))switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e"}this.log("Init video buffer, container:"+a.container+", codecs[level/parsed]=["+(t.videoCodec||"")+"/"+c+"]"+(a.codec!==c?" parsed-corrected="+a.codec:"")+(a.supplemental?" supplemental="+a.supplemental:"")),delete e.audiovideo}o&&(this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+t.codecs+"/"+o.codec+"]"),delete e.video,delete e.audio);var f=Object.keys(e);if(f.length){if(this.hls.trigger(w.BUFFER_CODECS,e),!this.hls)return;f.forEach((function(t){var n=e[t].initSegment;null!=n&&n.byteLength&&s.hls.trigger(w.BUFFER_APPENDING,{type:t,data:n,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}},i.getMainFwdBufferInfo=function(){var t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,x.MAIN)},i.backtrack=function(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=jr.IDLE},i.checkFragmentChanged=function(){var t=this.media,e=null;if(t&&t.readyState>1&&!1===t.seeking){var i=t.currentTime;if(Ri.isBuffered(t,i)?e=this.getAppendedFrag(i):Ri.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;var r=this.fragPlaying,s=e.level;r&&e.sn===r.sn&&r.level===s||(this.fragPlaying=e,this.hls.trigger(w.FRAG_CHANGED,{frag:e}),r&&r.level===s||this.hls.trigger(w.LEVEL_SWITCHED,{level:s}))}}},s(e,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var t=this.levels,e=this.level,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentFrag",get:function(){var t;if(this.fragPlaying)return this.fragPlaying;var e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return k(e)?this.getAppendedFrag(e):null}},{key:"currentProgramDateTime",get:function(){var t,e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(k(e)){var i=this.getLevelDetails(),r=this.currentFrag||(i?Ge(null,i.fragments,e):null);if(r){var s=r.programDateTime;if(null!==s){var n=s+1e3*(e-r.start);return new Date(n)}}}return null}},{key:"currentLevel",get:function(){var t=this.currentFrag;return t?t.level:-1}},{key:"nextBufferedFrag",get:function(){var t=this.currentFrag;return t?this.followingBufferedFrag(t):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(qr),Td=function(){function t(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}var e=t.prototype;return e.abort=function(t){for(var e in this.keyUriToKeyInfo){var i=this.keyUriToKeyInfo[e].loader;if(i){var r;if(t&&t!==(null==(r=i.context)?void 0:r.frag.type))return;i.abort()}}},e.detach=function(){for(var t in this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}},e.destroy=function(){for(var t in this.detach(),this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}},e.createKeyLoadError=function(t,e,i,r,s){return void 0===e&&(e=C.KEY_LOAD_ERROR),new Ei({type:P.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:i,networkDetails:r})},e.loadClear=function(t,e,i){var r=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(var s,n=function(){var s=e[a];if(t.cc<=s.cc&&(!et(t)||!et(s)||t.sn<s.sn)||!i&&a==o-1)return{v:r.emeController.selectKeySystemFormat(s).then((function(t){if(r.emeController){s.setKeyFormat(t);var e=Xi(t);return e?r.emeController.getKeySystemAccess([e]):void 0}}))}},a=0,o=e.length;a<o;a++)if(s=n())return s.v;if(this.config.requireKeySystemAccessOnStart){var l=zi(this.config);if(l.length)return this.emeController.getKeySystemAccess(l)}}return null},e.load=function(t){var e=this;return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then((function(i){return e.loadInternal(t,i)})):this.loadInternal(t)},e.loadInternal=function(t,e){var i,r;e&&t.setKeyFormat(e);var s=t.decryptdata;if(!s){var n=new Error(e?"Expected frag.decryptdata to be defined after setting format "+e:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,C.KEY_LOAD_ERROR,n))}var a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,C.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+a+'"')));var o,l=this.keyUriToKeyInfo[a];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:t,keyInfo:l});if(null!=(r=l)&&r.keyLoadPromise)switch(null==(o=l.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return l.keyLoadPromise.then((function(e){return s.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:l}}))}switch(l=this.keyUriToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,t):this.loadKeyEME(l,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,t);default:return Promise.reject(this.createKeyLoadError(t,C.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+s.method+'"')))}},e.loadKeyEME=function(t,e){var i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var r=this.emeController.loadKey(i);if(r)return(t.keyLoadPromise=r.then((function(e){return t.mediaKeySessionContext=e,i}))).catch((function(e){throw t.keyLoadPromise=null,e}))}return Promise.resolve(i)},e.loadKeyHTTP=function(t,e){var i=this,r=this.config,s=new(0,r.loader)(r);return e.keyLoader=t.loader=s,t.keyLoadPromise=new Promise((function(n,a){var o={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,e,r,s){var o=r.frag,l=r.keyInfo,h=r.url;if(!o.decryptdata||l!==i.keyUriToKeyInfo[h])return a(i.createKeyLoadError(o,C.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(t.data),o.keyLoader=null,l.loader=null,n({frag:o,keyInfo:l})},onError:function(t,r,s,n){i.resetLoader(r),a(i.createKeyLoadError(e,C.KEY_LOAD_ERROR,new Error("HTTP Error "+t.code+" loading key "+t.text),s,c({url:o.url,data:void 0},t)))},onTimeout:function(t,r,s){i.resetLoader(r),a(i.createKeyLoadError(e,C.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:function(t,r,s){i.resetLoader(r),a(i.createKeyLoadError(e,C.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,h,d)}))},e.resetLoader=function(t){var e=t.frag,i=t.keyInfo,r=t.url,s=i.loader;e.keyLoader===s&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()},t}();function Sd(t){switch(t.type){case O.AUDIO_TRACK:return x.AUDIO;case O.SUBTITLE_TRACK:return x.SUBTITLE;default:return x.MAIN}}function Ad(t,e){var i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}var Ld=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}var e=t.prototype;return e.startLoad=function(t){},e.stopLoad=function(){this.destroyInternalLoaders()},e.registerListeners=function(){var t=this.hls;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_LOADING,this.onLevelLoading,this),t.on(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this)},e.unregisterListeners=function(){var t=this.hls;t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_LOADING,this.onLevelLoading,this),t.off(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this)},e.createInternalLoader=function(t){var e=this.hls.config,i=e.pLoader,r=e.loader,s=new(i||r)(e);return this.loaders[t.type]=s,s},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var i=e.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:O.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})},e.onLevelLoading=function(t,e){var i=e.id,r=e.level,s=e.pathwayId,n=e.url,a=e.deliveryDirectives,o=e.levelInfo;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:O.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})},e.onAudioTrackLoading=function(t,e){var i=e.id,r=e.groupId,s=e.url,n=e.deliveryDirectives,a=e.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:O.AUDIO_TRACK,url:s,deliveryDirectives:n,levelOrTrack:a})},e.onSubtitleTrackLoading=function(t,e){var i=e.id,r=e.groupId,s=e.url,n=e.deliveryDirectives,a=e.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:O.SUBTITLE_TRACK,url:s,deliveryDirectives:n,levelOrTrack:a})},e.onLevelsUpdated=function(t,e){var i=this.loaders[O.LEVEL];if(i){var r=i.context;r&&!e.levels.some((function(t){return t===r.levelOrTrack}))&&(i.abort(),delete this.loaders[O.LEVEL])}},e.load=function(t){var e,i,r,s=this,n=this.hls.config,o=this.getInternalLoader(t);if(o){var l=this.hls.logger,h=o.context;if(h&&h.levelOrTrack===t.levelOrTrack&&(h.url===t.url||h.deliveryDirectives&&!t.deliveryDirectives))return void(h.url===t.url?l.log("[playlist-loader]: ignore "+t.url+" ongoing request"):l.log("[playlist-loader]: ignore "+t.url+" in favor of "+h.url));l.log("[playlist-loader]: aborting previous loader for type: "+t.type),o.abort()}if(i=t.type===O.MANIFEST?n.manifestLoadPolicy.default:a({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),o=this.createInternalLoader(t),k(null==(e=t.deliveryDirectives)?void 0:e.part)&&(t.type===O.LEVEL&&null!==t.level?r=this.hls.levels[t.level].details:t.type===O.AUDIO_TRACK&&null!==t.id?r=this.hls.audioTracks[t.id].details:t.type===O.SUBTITLE_TRACK&&null!==t.id&&(r=this.hls.subtitleTracks[t.id].details),r)){var d=r.partTarget,u=r.targetduration;if(d&&u){var c=1e3*Math.max(3*d,.8*u);i=a({},i,{maxTimeToFirstByteMs:Math.min(c,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,i.maxTimeToFirstByteMs)})}}var f=i.errorRetry||i.timeoutRetry||{},g={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},m={onSuccess:function(t,e,i,r){var n=s.getInternalLoader(i);s.resetInternalLoader(i.type);var a=t.data;0===a.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),cr.isMediaPlaylist(a)||i.type!==O.MANIFEST?s.handleTrackOrLevelPlaylist(t,e,i,r||null,n):s.handleMasterPlaylist(t,e,i,r)):s.handleManifestParsingError(t,i,new Error("no EXTM3U delimiter"),r||null,e)},onError:function(t,e,i,r){s.handleNetworkError(e,i,!1,t,r)},onTimeout:function(t,e,i){s.handleNetworkError(e,i,!0,void 0,t)}};o.load(t,g,m)},e.checkAutostartLoad=function(){if(this.hls){var t=this.hls,e=t.config,i=e.autoStartLoad,r=e.startPosition,s=t.forceStartLoad;(i||s)&&(this.hls.logger.log((i?"auto":"force")+" startLoad with configured startPosition "+r),this.hls.startLoad(r))}},e.handleMasterPlaylist=function(t,e,i,r){var s=this.hls,n=t.data,a=Ad(t,i),o=cr.parseMasterPlaylist(n,a);if(o.playlistParsingError)this.handleManifestParsingError(t,i,o.playlistParsingError,r,e);else{var l=o.contentSteering,h=o.levels,d=o.sessionData,u=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=cr.parseMasterPlaylistMedia(n,a,o),m=g.AUDIO,p=void 0===m?[]:m,v=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];p.length&&(p.some((function(t){return!t.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new wi({}),bitrate:0,url:""}))),s.trigger(w.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:v,captions:y,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f})}},e.handleTrackOrLevelPlaylist=function(t,e,i,r,s){var n=this.hls,a=i.id,o=i.level,l=i.type,h=Ad(t,i),d=k(o)?o:k(a)?a:0,u=Sd(i),c=cr.parseLevelPlaylist(t.data,h,d,u,0,this.variableList);if(l===O.MANIFEST){var f={attrs:new wi({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=e.loading.start+xr(c,0),n.trigger(w.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,t,e,i,r,s)},e.handleManifestParsingError=function(t,e,i,r,s){this.hls.trigger(w.ERROR,{type:P.NETWORK_ERROR,details:C.MANIFEST_PARSING_ERROR,fatal:e.type===O.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:r,stats:s})},e.handleNetworkError=function(t,e,i,r,s){void 0===i&&(i=!1);var n="A network "+(i?"timeout":"error"+(r?" (status "+r.code+")":""))+" occurred while loading "+t.type;t.type===O.LEVEL?n+=": "+t.level+" id: "+t.id:t.type!==O.AUDIO_TRACK&&t.type!==O.SUBTITLE_TRACK||(n+=" id: "+t.id+' group-id: "'+t.groupId+'"');var a=new Error(n);this.hls.logger.warn("[playlist-loader]: "+n);var o=C.UNKNOWN,l=!1,h=this.getInternalLoader(t);switch(t.type){case O.MANIFEST:o=i?C.MANIFEST_LOAD_TIMEOUT:C.MANIFEST_LOAD_ERROR,l=!0;break;case O.LEVEL:o=i?C.LEVEL_LOAD_TIMEOUT:C.LEVEL_LOAD_ERROR,l=!1;break;case O.AUDIO_TRACK:o=i?C.AUDIO_TRACK_LOAD_TIMEOUT:C.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case O.SUBTITLE_TRACK:o=i?C.SUBTITLE_TRACK_LOAD_TIMEOUT:C.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);var d={type:P.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:s};if(r){var u=(null==e?void 0:e.url)||t.url;d.response=c({url:u,data:void 0},r)}this.hls.trigger(w.ERROR,d)},e.handlePlaylistLoaded=function(t,e,i,r,s,n){var a=this.hls,o=r.type,l=r.level,h=r.id,d=r.groupId,u=r.deliveryDirectives,c=Ad(e,r),f=Sd(r),g="number"==typeof r.level&&f===x.MAIN?l:void 0;if(t.fragments.length){t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));var m=t.playlistParsingError;if(m){if(this.hls.logger.warn(m+" "+t.url),!a.config.ignorePlaylistParsingErrors)return void a.trigger(w.ERROR,{type:P.NETWORK_ERROR,details:C.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:e,context:r,level:g,parent:f,networkDetails:s,stats:i});t.playlistParsingError=null}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case O.MANIFEST:case O.LEVEL:a.trigger(w.LEVEL_LOADED,{details:t,levelInfo:r.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:u,withoutMultiVariant:o===O.MANIFEST});break;case O.AUDIO_TRACK:a.trigger(w.AUDIO_TRACK_LOADED,{details:t,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u});break;case O.SUBTITLE_TRACK:a.trigger(w.SUBTITLE_TRACK_LOADED,{details:t,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u})}}else{var p=t.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(w.ERROR,{type:P.NETWORK_ERROR,details:C.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:e,context:r,level:g,parent:f,networkDetails:s,stats:i})}},t}(),Rd=function(){function t(e){void 0===e&&(e={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new L,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;var i=this.logger=H(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=Xh(t.DefaultConfig,e,i);this.userConfig=e,r.progressive&&zh(r,i);var s=r.abrController,n=r.bufferController,a=r.capLevelController,o=r.errorController,l=r.fpsController,h=new o(this),d=this.abrController=new s(this),u=new ii(this),c=r.interstitialsController,f=c?this.interstitialsController=new c(this,t):null,g=this.bufferController=new n(this,u),m=this.capLevelController=new a(this),p=new l(this),v=new Ld(this),y=r.contentSteeringController,E=y?new y(this):null,T=this.levelController=new cd(this,E),S=new dd(this),A=new Td(this.config),R=this.streamController=new Ed(this,u,A),I=this.gapController=new id(this,u);m.setStreamController(R),p.setStreamController(R);var b=[v,T,R];f&&b.splice(1,0,f),E&&b.splice(1,0,E),this.networkControllers=b;var k=[d,g,I,m,p,S,u];this.audioTrackController=this.createController(r.audioTrackController,b);var D=r.audioStreamController;D&&b.push(this.audioStreamController=new D(this,u,A)),this.subtitleTrackController=this.createController(r.subtitleTrackController,b);var _=r.subtitleStreamController;_&&b.push(this.subtititleStreamController=new _(this,u,A)),this.createController(r.timelineController,k),A.emeController=this.emeController=this.createController(r.emeController,k),this.cmcdController=this.createController(r.cmcdController,k),this.latencyController=this.createController(ud,k),this.coreComponents=k,b.push(h);var P=h.onErrorOut;"function"==typeof P&&this.on(w.ERROR,P,h),this.on(w.MANIFEST_LOADED,v.onManifestLoaded,v)}t.isMSESupported=function(){return md()},t.isSupported=function(){return pd()},t.getMediaSource=function(){return W()};var e=t.prototype;return e.createController=function(t,e){if(t){var i=new t(this);return e&&e.push(i),i}return null},e.on=function(t,e,i){void 0===i&&(i=this),this._emitter.on(t,e,i)},e.once=function(t,e,i){void 0===i&&(i=this),this._emitter.once(t,e,i)},e.removeAllListeners=function(t){this._emitter.removeAllListeners(t)},e.off=function(t,e,i,r){void 0===i&&(i=this),this._emitter.off(t,e,i,r)},e.listeners=function(t){return this._emitter.listeners(t)},e.emit=function(t,e,i){return this._emitter.emit(t,e,i)},e.trigger=function(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;var i=t===w.ERROR;this.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1},e.listenerCount=function(t){return this._emitter.listenerCount(t)},e.destroy=function(){this.logger.log("destroy"),this.trigger(w.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((function(t){return t.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(t){return t.destroy()})),this.coreComponents.length=0;var t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null},e.attachMedia=function(t){if(!t||"media"in t&&!t.media){var e=new Error("attachMedia failed: invalid argument ("+t+")");this.trigger(w.ERROR,{type:P.OTHER_ERROR,details:C.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var i="media"in t,r=i?t.media:t,s=i?t:{media:r};this._media=r,this.trigger(w.MEDIA_ATTACHING,s)}},e.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(w.MEDIA_DETACHING,{}),this._media=null},e.transferMedia=function(){this._media=null;var t=this.bufferController.transferMedia();return this.trigger(w.MEDIA_DETACHING,{transferMedia:t}),t},e.loadSource=function(t){this.stopLoad();var e=this.media,i=this._url,r=this._url=b.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+r),e&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(w.MANIFEST_LOADING,{url:t})},e.startLoad=function(t,e){void 0===t&&(t=-1),this.logger.log("startLoad("+t+(e?", <skip seek to start>":"")+")"),this.started=!0,this.resumeBuffering();for(var i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);},e.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);},e.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((function(t){t.resumeBuffering&&t.resumeBuffering()})))},e.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((function(t){t.pauseBuffering&&t.pauseBuffering()})))},e.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.recoverMediaError=function(){this.logger.log("recoverMediaError");var t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))},e.removeLevel=function(t){this.levelController.removeLevel(t)},e.setAudioOption=function(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null},e.setSubtitleOption=function(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null},e.getMediaDecodingInfo=function(t,e){return void 0===e&&(e=this.allAudioTracks),ne(t,be(e),navigator.mediaCapabilities)},s(t,[{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"inFlightFragments",get:function(){var t,e=((t={})[x.MAIN]=this.streamController.inFlightFrag,t);return this.audioStreamController&&(e[x.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[x.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}},{key:"sessionId",get:function(){var t=this._sessionId;return t||(t=this._sessionId=v()),t}},{key:"levels",get:function(){var t=this.levelController.levels;return t||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){this.logger.log("set currentLevel:"+t),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){this.logger.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){this.logger.log("set loadLevel:"+t),this.levelController.manualLevel=t}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(t){this.levelController.nextLoadLevel=t}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(t){this.logger.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){var t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t},set:function(t){this.logger.log("set startLevel:"+t),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(t){var e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(t){this._autoLevelCapping!==t&&(this.logger.log("set autoLevelCapping:"+t),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimate():NaN},set:function(t){this.abrController.resetEstimator(t)}},{key:"abrEwmaDefaultEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(t){ce(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var t=this.levels,e=this.config.minAutoBitrate;if(!t)return 0;for(var i=t.length,r=0;r<i;r++)if(t[r].maxBitrate>=e)return r;return 0}},{key:"maxAutoLevel",get:function(){var t,e=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(t=-1===i&&null!=e&&e.length?e.length-1:i,r)for(var s=t;s--;){var n=e[s].attrs["HDCP-LEVEL"];if(n&&n<=r)return s}return t}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(t){this.abrController.nextAutoLevel=t}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"allAudioTracks",get:function(){var t=this.audioTrackController;return t?t.allAudioTracks:[]}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"allSubtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(t){this.latencyController.targetLatency=t}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(t){this.levelController.pathwayPriority=t}},{key:"bufferedToEnd",get:function(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}}],[{key:"version",get:function(){return ea}},{key:"Events",get:function(){return w}},{key:"MetadataSchema",get:function(){return ws}},{key:"ErrorTypes",get:function(){return P}},{key:"ErrorDetails",get:function(){return C}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:jh},set:function(e){t.defaultConfig=e}}])}();return Rd.defaultConfig=void 0,Rd}()}(!1)},66787:(t,e,i)=>{"use strict";i.d(e,{F:()=>v});var r=i(94581),s=i(25775),n=i(75768),a=i(33694),o=i(45984),l=i(15867),h=i.n(l),d=i(94406),u=i(29183),c=function(t,e,i){for(var r=arguments.length>2,s=0;s<e.length;s++)i=r?e[s].call(t,i):e[s].call(t);return r?i:void 0},f=function(t,e,i,r,s,n){function a(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!e&&t?r.static?t:t.prototype:null,u=e||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(t){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(t||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},g=function(t,e,i){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:i?"".concat(i," ",e):e})},m=function(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)},p=function(t,e,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,i):s?s.value=i:e.set(t,i),i};let v=(()=>{var t,e,i,l,v,y,E,T,S,A,L,R,I,b,k,D,_,P,C,w;let O,x,M,F,N,U,B,G=[d.JW],$=[],K=[];x=class{get executionContextProvider(){var t;return null!==(t=this.player)&&void 0!==t?t:null}get model(){return this.player.model}get pc(){return this.model.playerConfig}get mc(){return this.model.mediaCollection}get vc(){return this.player.viewCtrl}get videoScale(){return this.model.videoScaleMode}set videoScale(t){this.model.videoScaleMode!==t&&(this.model.videoScaleMode=t,this.applyVideoScale(t))}set remotePlaybackDevice(e){m(this,t,"f")!==e&&(this.player.loop.dispatchEvent(r.a.REMOTE_PLAYBACK_CHANGED,(0,u.cl)(e)?{isRemote:!1}:{isRemote:!0,device:e}),this.player.isLive&&!this.player.isAudio&&this.vc.setLiveInitialBufferState()),p(this,t,e,"f")}get remotePlaybackDevice(){return m(this,t,"f")}get isRemotePlayback(){return!(0,u.cl)(m(this,t,"f"))}get isPlayingSpatialAudio(){return!1}get playbackStalled(){return m(this,v,"f")}get __cumulativeDrift(){return m(this,I,"f")}constructor(s,a){this.minDisplayedLiveOffset=(c(this,K),7),this.subtitleListeners=[],this.audioTrackListeners=[],this.audioTracks=[],this.audioTrack=null,t.set(this,null),e.set(this,0),i.set(this,0),l.set(this,!1),v.set(this,!1),y.set(this,0),E.set(this,!1),T.set(this,!1),this._duration=0,this._dvrModeEnabled=!1,S.set(this,-1),A.set(this,-1),L.set(this,0),R.set(this,0),I.set(this,0),this.isAtEnd=!1,this._useAndroidInitialSeekFallback=!1,b.set(this,-1),k.set(this,-1),D.set(this,!1),this._ready=!1,this._pendingSeek=0,_.set(this,-1),P.set(this,!1),this._dvrEnabled=!1,this._dvrIsLive=!1,this._dvrWindow=0,this.expectedAudios=[],C.set(this,!1),this.pinnedDvrSync=null,this.dvrWindowUnstable=!1,this[w]=this.getClassTypeString(),this.player=s,this.mediaElement=a,this.applyVideoScale(this.videoScale),this.player.loop.dispatchEvent(r.a.EVENT_INIT,{}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"init"}),this.emap=new(h()),this.addEventListeners(),n.x.for(this.player).storageListeners.add(this),a instanceof HTMLMediaElement&&(a.textTracks.onaddtrack=t=>{this.onTextTracksChanged(t)},a.textTracks.onremovetrack=t=>{this.onTextTracksChanged(t)}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"ready"})}debugString(){return"none"}debugQualityLevel(){return[-1,1]}debugResolution(){return this.isRemotePlayback||this.player.isAudio?"-":`${this.mediaElement.videoWidth}x${this.mediaElement.videoHeight}`}debugFrames(){if(this.mediaElement instanceof HTMLVideoElement){const t=this.mediaElement.getVideoPlaybackQuality();return`${t.droppedVideoFrames} dropped of ${t.totalVideoFrames}`}return"no video info available"}get subQualities(){return this.error("using base implementation for subQuality listing!"),[{level:-1,label:"Auto",width:-1,height:-1}]}selectSubQuality(t){this.error("using base implementation for subQuality selection!")}get currentSubQuality(){return this.error("using base implementation for currentSubQuality!"),-1}log(...t){this.player.console.log(`[${this.getClassTypeString()}]`,...t)}info(...t){this.player.console.info(`[${this.getClassTypeString()}]`,...t)}warn(...t){this.player.console.warn(`[${this.getClassTypeString()}]`,...t)}error(...t){this.player.console.error(`[${this.getClassTypeString()}]`,...t)}onTextTracksChanged(t){this.subtitleListeners.forEach((e=>{e.onTextTracksChanged(t)}))}addSubtitleListener(t){this.subtitleListeners.includes(t)||this.subtitleListeners.push(t)}removeSubtitleListener(t){const e=this.subtitleListeners.indexOf(t);-1!==e&&(this.subtitleListeners=this.subtitleListeners.splice(e,1))}onAudioTracksChanged(){1===this.audioTracks.length&&1===this.expectedAudios.length&&"audio-description"===this.expectedAudios[0].kind&&(this.audioTracks[0].isAudioDescription=!0),this.player.loop.dispatchEvent(r.a.AUDIO_TRACK_LIST_CHANGED,{audioTracks:this.audioTracks}),this.audioTrackListeners.forEach((t=>{t.onAudioTracksChanged(this.audioTracks)}))}addAudioTrackListener(t){this.audioTrackListeners.includes(t)||this.audioTrackListeners.push(t)}removeAudioTrackListener(t){const e=this.audioTrackListeners.indexOf(t);-1!==e&&(this.audioTrackListeners=this.audioTrackListeners.splice(e,1))}addEventListeners(){this.emap.map(this.mediaElement,"loadstart",this.onLoadStart,this),this.emap.map(this.mediaElement,"canplay",this.onCanPlay,this),this.emap.map(this.mediaElement,"play",this.onPlay,this),this.emap.map(this.mediaElement,"pause",this.onPause,this),this.emap.map(this.mediaElement,"error",this.onError,this),this.emap.map(this.mediaElement,"waiting",this.onWaiting,this),this.emap.map(this.mediaElement,"ended",this.onEnded,this),this.emap.map(this.mediaElement,"timeupdate",this.onTimeUpdate,this),this.emap.map(this.mediaElement,"seeking",this.onSeeking,this),this.emap.map(this.mediaElement,"seeked",this.onSeekEnd,this),this.emap.map(this.mediaElement,"loadedmetadata",this.onLoadedMetadata,this),this.emap.map(this.mediaElement,"loadeddata",this.onLoadedData,this),this.emap.map(this.mediaElement,"durationchange",this.onDurationChange,this),this.emap.map(this.mediaElement,"progress",this.onProgress,this),this.emap.map(this.mediaElement,"stalled",this.onStalled,this),this.emap.map(this.mediaElement,"volumechange",this.onLocalVolumeChange,this)}onLoadStart(){var t,e;s.O.isAndroidDevice&&(null!==(e=null===(t=this.mediaElement)||void 0===t?void 0:t.currentSrc)&&void 0!==e?e:"").toLowerCase().indexOf(".m3u8")>0&&(this._useAndroidInitialSeekFallback=!0)}onCanPlay(){this.mediaElement instanceof HTMLMediaElement&&!(this.mediaElement.readyState>=this.mediaElement.HAVE_FUTURE_DATA)||this.bufferingEventHandler(!1),p(this,v,!1,"f"),this.setPlaybackRate(this.model.playbackRate)}onPlay(){this.startTicker(),this.playEventHandler(),this.bufferingEventHandler(!1),this.vc.setOutDelayed()}onPause(t){this.pauseEventHandler(t,!isNaN(this.mediaElement.currentTime)&&!isNaN(this.mediaElement.duration)&&this.mediaElement.currentTime>=this.mediaElement.duration&&("ios"!==s.O.platform||!this.player.isLive))}onError(t){this.handleError(t)}onWaiting(t){this.mediaElement instanceof HTMLMediaElement&&this.bufferingEventHandler(this.mediaElement.readyState<this.mediaElement.HAVE_FUTURE_DATA),p(this,v,!0,"f")}onEnded(t){this.stopTicker(),this.mediaElement.pause(),this.endEventHandler(t),this.onTimeChange(this._duration,0)}onTimeUpdate(t){if(this.onProgress(null),this.updateTicker(),this.isSeeking()&&!m(this,D,"f")){const t=this.getCurrentTime();Math.abs(m(this,k,"f")-t)<Math.abs(m(this,b,"f")-t)&&this.onSeekEnd(null)}}onSeeking(){p(this,D,!0,"f"),m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_START,{from:m(this,b,"f"),to:m(this,k,"f")}),this.bufferingEventHandler(!0)}onSeekEnd(t){this.isSeeking()&&(m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_END,{lastPosition:m(this,b,"f"),position:this.getCurrentTime()}),p(this,E,!1,"f"),p(this,b,-1,"f"),p(this,k,-1,"f"),m(this,D,"f")||this.bufferingEventHandler(!1),p(this,D,!1,"f"),this.bufferingEventHandler(!1),this.player.clearExecutionContext(r.a.EVENT_SEEK_START,r.a.EVENT_SEEK_START_INTENT,r.a.EVENT_SEEK_END,r.a.EVENT_BUFFERING))}isSeeking(){return m(this,D,"f")||-1!==m(this,k,"f")&&-1!==m(this,b,"f")}onLoadedMetadata(){this._ready=!0,this.evalInitialSeek()}onLoadedData(){this.evalInitialSeek(),this.onProgress(null)}onDurationChange(t){const e=this.mediaElement.duration;isNaN(e)||(this._duration=e),this._ready=!0,this.onProgress(null)}onLocalVolumeChange(t){const e=this.mediaElement.muted,i=this.mediaElement.volume;this.getVolume()/100===i&&m(this,C,"f")===e||(this.player.setMutedInternal(e,!0,!1,!0,!0),this.player.setVolumeInternal(100*i,!0,!1,!1))}onProgress(t){var e;if(!this.mediaElement||"waiting"===(null==t?void 0:t.type)&&this.isSeeking())return;const i=this.getCurrentTime(),r=this.getDuration();let s=-1;const n=null===(e=this.mediaElement)||void 0===e?void 0:e.buffered;if(n)for(let t=0;t<n.length;t++)if(n.start(t)<=i&&n.end(t)>=i){s=n.end(t);break}if(-1===s)return;const a=Math.round(s/r*100);this.bufferProgressHandler(a)}onStalled(t){this.onProgress(t)}onSourceError(t){this.stopTicker(),this.handleError(t)}onTimeChange(t,e){this.model.duration!==t&&t>0&&this.model.duration>0&&null!=this.pinnedDvrSync&&(this.pinnedDvrSync=null,this.dvrWindowUnstable=!0,this.warn("DVR window unstable, disabled sync info pinning")),this.updateDuration(t),this.updateTime(Math.max(e,0))}bufferingEventHandler(t){this.onProgress(null),t&&!this.isAtEnd?this.vc.showBufferingIndicator():this.vc.hideBufferingIndicator(),t!==m(this,l,"f")&&(p(this,l,t,"f"),this.player.loop.dispatchEvent(r.a.EVENT_BUFFERING,{isBuffering:t}))}bufferProgressHandler(t){var e;null===(e=this.vc.timeline)||void 0===e||e.setBufferProgress(t),p(this,y,t,"f")}playEventHandler(){var t;if(this.stopOtherPlayingPlayers(),this.model.playstate=o.R.PLAYSTATE_PLAYING,this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"play"}),this.isAtEnd){const e=this.getCurrentTimeWithoutSeek();null===(t=this.executionContextProvider)||void 0===t||t.preserveExecutionContext(r.a.EVENT_INITIAL_FRAME,500);const i=t=>{t.currentTime!==e&&(this.player.loop.dispatchEvent(r.a.EVENT_INITIAL_FRAME,{}),m(this,l,"f")||this.bufferingEventHandler(!1))},s=()=>{this.player.loop.removeEventListener(r.a.EVENT_UPDATE_STREAM_TIME,i),this.player.loop.removeEventListener(r.a.EVENT_INITIAL_FRAME,s)};this.player.loop.addEventListener(r.a.EVENT_UPDATE_STREAM_TIME,i),this.player.loop.addEventListener(r.a.EVENT_INITIAL_FRAME,s)}this.isAtEnd=!1,this.player.pixelController.replayTrigger(),this.player.pixelController.initialPlayTrigger(),this.player.loop.dispatchEvent(r.a.EVENT_PLAY_STREAM,{})}pauseEventHandler(t,e=!1){this.model.playstate=o.R.PLAYSTATE_PAUSED,this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"pause"}),this.player.loop.dispatchEvent(r.a.EVENT_PAUSE_STREAM,{ended:e})}endEventHandler(t){this.isAtEnd=!0,this.player.loop.dispatchEvent(r.a.EVENT_END_STREAM,{}),this.player.pixelController.triggerPixel(a.k.CLIP_ENDED),this.jumpToStart(),this.pauseEventHandler(t,!0),this.vc.hidePosterFrame(),this.mc.isLive||this.vc.showPlayAgain(),this.vc.hideBufferingIndicator(),"web"===s.O.platform&&this.player.setFullscreenInternal(!1),this.player.pixelController&&(this.player.pixelController._isReplay=!0)}evalInitialSeek(){if(this._pendingSeek>0){if(this.canSeek()){p(this,E,!0,"f");const t=this._pendingSeek;this._pendingSeek=0,this.setCurrentTime(t,m(this,T,"f"),!1,!0),m(this,T,"f")||this.play()}}else m(this,T,"f")||this.play()}updateDuration(t){this.model.duration!==t&&(this.model.duration=t,this.player.loop.dispatchEvent(r.a.EVENT_UPDATE_STREAM_DURATION,{duration:t}))}restartMedia(){this.jumpToStart(),this.play()}resetStartAndEndTime(){this.pc.generic.vodStartSeconds=0,this.pc.generic.vodEndSeconds=0}updateTime(t){this.model.time=t,this.vc.updateTime(t),this.vc.updateTimeline(t,this.model.duration);const s=Date.now();if(s>=m(this,i,"f")+1e3){p(this,i,s,"f");let e=0;const r=Math.round(this.model.duration),n=Math.round(t);this.vc.dvrState.enabledAndRequested&&!this.vc.dvrState.isLive&&(e=Math.min(Math.round(r-t),r)),this.player.pixelController.triggerCustomPixel(a.k.SUPER_PLAYHEAD_POSITION,!1,{currentTime:n,duration:r,dvrRelativeTime:-e})}const l=this.pc.generic.vodStartSeconds,h=this.pc.generic.vodEndSeconds;if(l>0&&t<l){const i=Math.round(t);Math.abs(m(this,e,"f")-i)>3&&(this.setCurrentTime(l,!1,!1,!0),p(this,e,i,"f"))}else h>0&&t>h&&(this.setCurrentTime(l,!1,!1,!0),this.pause());this.player.loop.dispatchEvent(r.a.EVENT_UPDATE_STREAM_TIME,{currentTime:t}),window.parent!==window&&n.x.AVAILABLE&&this.model.playstate===o.R.PLAYSTATE_PLAYING&&n.x.get(n.x.SUFFIX_GLOBAL,n.x.CURRENT_PLAYERID,!0)!==this.player.getId()&&this.pause()}removeEventListeners(){this.emap.all()}dispose(){this.log("dispose()"),this.removeEventListeners(),n.x.for(this.player).storageListeners.delete(this),this.mediaElement instanceof HTMLMediaElement&&(this.mediaElement.textTracks.onaddtrack=null,this.mediaElement.textTracks.onremovetrack=null),this.mediaElement.pause(),this.subtitleListeners=[],this.audioTrackListeners=[],this.stopTicker(),this.player.loop.dispatchEvent(r.a.EVENT_STOP_STREAM,{}),m(this,T,"f")&&0===this.model.playstate&&(this.model.playstate=3),this.audioTracks=[],this.audioTrack=null}stopOtherPlayingPlayers(){n.x.add(n.x.SUFFIX_GLOBAL,n.x.CURRENT_PLAYERID,this.player.getId(),!0,!0),o.R.autoPlayerAlreadyActive=this.player.getId()}onStorageValueChanged(t,e){t===n.x.CURRENT_PLAYERID&&"string"==typeof e&&this.isPlaying()&&e!==this.player.getId()&&this.pause()}loadStream(t){if(p(this,T,1===this.model.playstate||3===this.model.playstate,"f"),this.model.playstate=o.R.PLAYSTATE_UNSPECIFIED,m(this,T,"f")||this.stopOtherPlayingPlayers(),this.player.preserveExecutionContext(r.a.EVENT_LOAD_STREAM,5e3),this.player.loop.dispatchEvent(r.a.EVENT_LOAD_STREAM,{mediaStream:t}),this._pendingSeek=this.model.time,0===this._pendingSeek&&!this.mc.isLive){let t=this.pc.generic.vodInitialPlayheadSeconds;t<=0&&(t=this.pc.generic.vodStartSeconds),this._pendingSeek=t}if(this.mediaElement instanceof HTMLMediaElement)for(;this.mediaElement.children.length>0;)this.mediaElement.removeChild(this.mediaElement.children[0]);if(this.expectedAudios=t.audios,this.addSource(t),!s.O.isEmbedded){const t=n.x.volume(this.player),e=this.pc.generic.isMuted||n.x.muted(this.player);this.player.setVolumeInternal(t,!1,!0,!0),this.player.setMutedInternal(e,!1,!0,!1,!1)}if(m(this,T,"f")){const t=()=>{this.pause(),this.mediaElement.removeEventListener("canplay",t)};this.mediaElement.addEventListener("canplay",t)}this.mediaElement.load()}startTicker(){this.stopTicker(),this.updateTicker(),p(this,_,this.player.safeInterval((()=>{this.updateTicker()}),500),"f")}stopTicker(){clearInterval(m(this,_,"f")),p(this,_,-1,"f")}updateTicker(){this.onTimeChange(this.getDuration(),this.getCurrentTime())}play(){var t;this.player.preserveExecutionContext(r.a.EVENT_PLAY_STREAM),p(this,T,!1,"f"),m(this,P,"f")?this.handleError():null===(t=this.mediaElement.play())||void 0===t||t.then((()=>{var t;try{this.player.checkState()}catch(t){return void this.warn("aborting async",t)}null===(t=this.vc)||void 0===t||t.hidePosterFrame(),this.startTicker()})).catch((t=>{var e,i,s;try{this.player.checkState()}catch(t){return void this.warn("aborting async",t)}this.error("playback failure",t),null===(e=this.player)||void 0===e||e.loop.dispatchEvent(r.a.EVENT_AUTOPLAY_STREAM_PROHIBITED,{}),null===(i=this.vc)||void 0===i||i.showPlayBtn(),null===(s=this.vc)||void 0===s||s.showPosterFrame(),this.stopTicker()}))}pause(){this.player.preserveExecutionContext(r.a.EVENT_PAUSE_STREAM),this.model.playstate=o.R.PLAYSTATE_PAUSED,this.mediaElement.pause(),this.mc.isLive&&this.mc.isDvrEnabled||(this.updateTicker(),this.stopTicker())}togglePlay(){m(this,P,"f")?this.handleError():this.isPlaying()?this.pause():this.play()}isPlaying(){return this.model.playstate===o.R.PLAYSTATE_PLAYING}setVolume(t){t>=0&&t<=100&&(this.mediaElement.volume=t/100)}getVolume(){return n.x.volume(this.player)}setMuted(t){p(this,C,t,"f"),this.mediaElement.muted=t,this.mediaElement instanceof HTMLMediaElement&&(t?this.mediaElement.setAttribute("muted","muted"):this.mediaElement.removeAttribute("muted"))}setCurrentTime(t,e=!1,i=!1,s=!1){this.player.preserveExecutionContext(r.a.EVENT_SEEK_START);let n=-1;this.canCalculateDvrUnixTime()&&t>=this.dvrRelToUnix(0)&&(n=t,t=this.dvrUnixToRel(t));const a=this.getDuration()>0?Math.min(t,this.getDuration()-.1):t;this.setSeekEventTimestamps(this.getCurrentTime(),a),this.setCurrentTimeRaw(a,n,e,i,s),this.player.model.time=a}setSeekEventTimestamps(t,e){p(this,b,t,"f"),p(this,k,e,"f")}setCurrentTimeRaw(t,e,i=!1,s=!1,n=!1){p(this,L,0,"f"),p(this,R,0,"f"),p(this,I,0,"f");const a=this.pc.generic.vodStartSeconds,o=this.pc.generic.vodEndSeconds;if(!n&&(a>0&&t<a||o>0&&t>o)&&this.resetStartAndEndTime(),this._ready){if(!this.canSeek())return;t=Math.max(0,t),this._pendingSeek=0,this.isAtEnd&&p(this,E,!0,"f");try{this.player.preserveExecutionContextAlias(r.a.EVENT_SEEK_START,-1,r.a.EVENT_SEEK_START_INTENT,r.a.EVENT_SEEK_END,r.a.EVENT_BUFFERING),m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_START_INTENT,{from:m(this,b,"f"),to:m(this,k,"f")}),s||(this.canSeekToUnixTime&&e>0?this.setCurrentUnixTime(e):this.mediaElement.currentTime=t)}catch(e){this._pendingSeek=t}}else this._pendingSeek=t;this.updateTicker(),this.isAtEnd&&!i&&this.play()}setCurrentUnixTime(t){throw new Error("method not implemented")}seekToLive(){this.canSeek()&&this.setCurrentTime(this.getDuration())}setPlaybackRate(t){const e=this.model.playbackRate!==t||this.mediaElement.playbackRate!==t;this.model.playbackRate=t,this.mediaElement.playbackRate!==t&&(this.mediaElement.playbackRate=t),e&&this.player.loop.dispatchEvent(r.a.PLAYBACK_RATE_CHANGE,{rate:t})}getDvrToDateSync(){return null}getSmoothDvrToDateSync(t){var e,i,r;return!this.dvrWindowUnstable&&t&&this.canCalculateDvrUnixTime()?(null==this.pinnedDvrSync&&(this.pinnedDvrSync=this.getDvrToDateSync(),0!==(null===(e=this.pinnedDvrSync)||void 0===e?void 0:e.rel)&&0!==(null===(i=this.pinnedDvrSync)||void 0===i?void 0:i.real)&&0!==(null===(r=this.pinnedDvrSync)||void 0===r?void 0:r.at)||(this.pinnedDvrSync=null)),this.pinnedDvrSync):this.getDvrToDateSync()}dvrRelToUnix(t,e=!1){const i=this.getSmoothDvrToDateSync(e);if(null!==i){if(e&&!this.dvrWindowUnstable)return this.__dvrRelToUnixRaw(t,i)|0;let r=m(this,I,"f");if(this.isPlaying()&&!this.playbackStalled){if(0!==m(this,L,"f")){const t=this.getCurrentTime();if(isFinite(t)&&t>0){const e=this.__dvrRelToUnixRaw(t,i)-m(this,L,"f");p(this,I,m(this,I,"f")+e,"f"),r+=e,this.info("PAUSE DRIFT",e)}p(this,L,0,"f"),p(this,R,0,"f")}const t=performance.now(),e=1e3*this.__dvrRelToUnixRaw(100,i);if(-1!==m(this,S,"f")&&-1!==m(this,A,"f")){const i=e-(m(this,A,"f")+(t-m(this,S,"f")));Math.abs(i)>=10&&(p(this,I,m(this,I,"f")+i/1e3,"f"),r+=i/1e3)}p(this,S,t,"f"),p(this,A,e,"f")}else p(this,S,-1,"f"),p(this,A,-1,"f"),0===m(this,R,"f")?(p(this,R,this.getCurrentTime(),"f"),p(this,L,this.__dvrRelToUnixRaw(m(this,R,"f"),i),"f")):r+=this.__dvrRelToUnixRaw(this.getCurrentTime(),i)-m(this,L,"f");return this.__dvrRelToUnixRaw(t,i)-r|0}return e&&!this.dvrWindowUnstable||(p(this,L,0,"f"),p(this,R,0,"f"),p(this,I,0,"f")),0}__dvrRelToUnixRaw(t,e){const i=e.rel-t,r=Date.now()-e.at;return(e.real+r)/1e3-i}dvrUnixToRel(t){return t-this.dvrRelToUnix(0)}canCalculateDvrUnixTime(){const t=this.getDvrToDateSync();return null!=t&&0!==t.real&&0!==t.rel&&0!==t.at}dvrUnixToRelNullable(t){const e=this.dvrRelToUnixNullable(0);return null==e?null:t-e}dvrRelToUnixNullable(t,e=!1){return null==this.getSmoothDvrToDateSync(e)?null:this.dvrRelToUnix(t,e)}get canSeekToUnixTime(){return!1}getPercentBuffered(){return m(this,y,"f")}getCurrentUnixTime(){return this._dvrEnabled&&this.canCalculateDvrUnixTime()?this.dvrRelToUnix(this.getCurrentTime()):-1}getCurrentUnixTimeWindowStart(){return this._dvrEnabled&&this.canCalculateDvrUnixTime()?this.dvrRelToUnix(0):-1}getCurrentUnixTimeWindowEnd(){return this._dvrEnabled&&this.canCalculateDvrUnixTime()?this.dvrRelToUnix(this.getDuration()):-1}getCurrentTime(){if(this._pendingSeek>0)return this._pendingSeek;const t=this.mediaElement.currentTime;return isNaN(t)?this.model.time:t}getCurrentTimeWithoutSeek(){return!m(this,E,"f")&&m(this,b,"f")>=0?m(this,b,"f"):this.getCurrentTime()}setTimeByPercent(t){const e=t/100*this.getDuration();return this.setCurrentTime(e),e}getDuration(){const t=this.mediaElement.duration;return isNaN(t)?0!==this._duration?this._duration:this.model.duration:t}stop(t){if(!this.isAtEnd){this.model.playstate=o.R.PLAYSTATE_STOPPED,this.isAtEnd=!0,this.player.loop.dispatchEvent(r.a.EVENT_STOP_STREAM,{}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"stop"});try{this.player.checkStateStrict(),this.pause(),s.O.isEmbedded||this.jumpToStart(),this.bufferingEventHandler(!1),this.updateTicker(),this.stopTicker()}catch(t){}}}jumpToStart(){this.setCurrentTime(0,!0)}onDVRCallback(t,e,i){this._dvrEnabled=t&&e>=120,this._dvrWindow=e,this._dvrIsLive=i,this.player.viewCtrl.onDVRCallback(this._dvrEnabled,this._dvrWindow,this._dvrIsLive),this.updateTicker(),this.player.loop.dispatchEvent(r.a.EVENT_DVR_CHANGE,{dvrEnabled:this._dvrEnabled,dvrIsLive:this._dvrIsLive,dvrWindow:this._dvrWindow})}getAudioTracks(){return[]}setAudioTrack(t){}setAudioTrackById(t){}getAudioTrack(){return null}getAudioTracksInitialized(){return null!=this.getAudioTrack()}handleError(t){var e;this.stopTicker(),p(this,P,!0,"f");let i=[];t&&(this.error(t),"string"==typeof t?i=[t]:"object"==typeof t&&("type"in t&&(0,u.Ed)(t.type)&&"error"!==t.type&&i.push(String(t.type)),"name"in t&&(0,u.Ed)(t.name)&&"error"!==t.name&&i.push(String(t.name)),(0,u.Ed)(t.message)&&i.push(String(t.message)))),null===(e=this.player.errorCtrl)||void 0===e||e.throwStreamError(...i)}toJSON(){return toString()}};return t=new WeakMap,e=new WeakMap,i=new WeakMap,l=new WeakMap,v=new WeakMap,y=new WeakMap,E=new WeakMap,T=new WeakMap,S=new WeakMap,A=new WeakMap,L=new WeakMap,R=new WeakMap,I=new WeakMap,b=new WeakMap,k=new WeakMap,D=new WeakMap,_=new WeakMap,P=new WeakMap,C=new WeakMap,M=[(0,d.C6)(r.a.EVENT_PAUSE_STREAM,{type:"other",initiator:"external-playback-pause"})],F=[(0,d.C6)(r.a.EVENT_PLAY_STREAM)],N=[(0,d.kF)({type:"lifecycle",initiator:"playback-end"})],U=[(0,d.C6)(r.a.EVENT_LOAD_STREAM)],B=[(0,d.kF)({type:"other",initiator:"dvrUpdate"})],w=Symbol.toStringTag,g(x,"AbstractPlayerCtrl"),(()=>{const t="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;f(x,null,M,{kind:"method",name:"onPause",static:!1,private:!1,access:{has:t=>"onPause"in t,get:t=>t.onPause},metadata:t},null,K),f(x,null,F,{kind:"method",name:"playEventHandler",static:!1,private:!1,access:{has:t=>"playEventHandler"in t,get:t=>t.playEventHandler},metadata:t},null,K),f(x,null,N,{kind:"method",name:"endEventHandler",static:!1,private:!1,access:{has:t=>"endEventHandler"in t,get:t=>t.endEventHandler},metadata:t},null,K),f(x,null,U,{kind:"method",name:"evalInitialSeek",static:!1,private:!1,access:{has:t=>"evalInitialSeek"in t,get:t=>t.evalInitialSeek},metadata:t},null,K),f(x,null,B,{kind:"method",name:"onDVRCallback",static:!1,private:!1,access:{has:t=>"onDVRCallback"in t,get:t=>t.onDVRCallback},metadata:t},null,K),f(null,O={value:x},G,{kind:"class",name:x.name,metadata:t},null,$),x=O.value,t&&Object.defineProperty(x,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t}),c(x,$)})(),x})()},71047:(t,e,i)=>{"use strict";i.r(e),i.d(e,{default:()=>dl});var r=i(94581),s=i(45984),n=i(66787),a=i(94406),o=i(29183);const l=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},h=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=d},d=Number.MAX_SAFE_INTEGER||9007199254740991;let u=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}({}),c=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}({}),f=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var g="manifest",m="level",p="audioTrack",v="subtitleTrack",y="main",E="audio",T="subtitle";class S{constructor(t,e=0,i=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_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class A{constructor(t,e,i,r=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_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new S(t),this.fast_=new S(e),this.defaultTTFB_=r,this.ttfb_=new S(t)}update(t,e){const{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==t&&(this.slow_=new S(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.fast_=new S(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new S(t,s.getEstimate(),s.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function L(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e);if("object"!=typeof r)return r;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:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function R(){return R=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},R.apply(null,arguments)}function I(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function b(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?I(Object(i),!0).forEach((function(e){L(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):I(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}class k{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 i=`[${t}]:`;this.trace=D,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const D=function(){},_={trace:D,debug:D,log:D,warn:D,info:D,error:D};function P(){return R({},_)}function C(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):D}(t,i)}const w=P();const O=w;function x(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function M(t,e){const i=Object.keys(t),r=Object.keys(e),s=i.length,n=r.length;return!s||!n||s===n&&!i.some((t=>-1===r.indexOf(t)))}function F(t,e=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let r,s,n,a="",o=0;for(;o<i;){if(r=t[o++],0===r&&e)return a;if(0!==r&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(r);break;case 12:case 13:s=t[o++],a+=String.fromCharCode((31&r)<<6|63&s);break;case 14:s=t[o++],n=t[o++],a+=String.fromCharCode((15&r)<<12|(63&s)<<6|63&n)}}return a}const N=function(t){let e="";for(let i=0;i<t.length;i++){let r=t[i].toString(16);r.length<2&&(r="0"+r),e+=r}return e};function U(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function B(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var G,$={exports:{}};var K,V,H,Y,W,j=(G||(G=1,K=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,V=/^(?=([^\/?#]*))\1([^]*)$/,H=/(?:\/|^)\.(?=\/)/g,Y=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,$.exports=W={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=W.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=W.normalizePath(r.path),W.buildURLFromParts(r)}var s=W.parseURL(e);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=W.normalizePath(s.path),W.buildURLFromParts(s)):e;var n=W.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=V.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=W.normalizePath(h)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=i.alwaysNormalize?W.normalizePath(s.path):s.path),W.buildURLFromParts(o)},parseURL:function(t){var e=K.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(H,"");t.length!==(t=t.replace(Y,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}}),$.exports);class q{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var X="audio",Q="video",z="audiovideo";class Z{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=it(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let r;r=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}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={[X]:null,[Q]:null,[z]: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 q),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=j.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[X]=null,t[Q]=null,t[z]=null}}function J(t){return"initSegment"!==t.sn}class tt 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(l(t)&&l(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(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length){const e=this._decryptdata=this.levelkeys[t[0]]||null;if(e)return e.getDecryptData(this.sn)}}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=l(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),i=t.length;if(i>1||1===i&&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){l(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return J(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,r,s,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:i,startDTS:r,endDTS:s,partial:n}}}class et extends Z{constructor(t,e,i,r,s){super(i),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=r;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function it(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||it(i,e)}}const rt=Math.pow(2,32)-1,st=[].push,nt={video:1,audio:2,id3:3,text:4};function at(t){return String.fromCharCode.apply(null,t)}function ot(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function lt(t,e){const i=dt(t,e);return i<0?4294967296+i:i}function ht(t,e){let i=lt(t,e);return i*=Math.pow(2,32),i+=lt(t,e+4),i}function dt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function ut(t,e){const i=[];if(!e.length)return i;const r=t.byteLength;for(let s=0;s<r;){const n=lt(t,s),a=n>1?s+n:r;if(at(t.subarray(s+4,s+8))===e[0])if(1===e.length)i.push(t.subarray(s+8,a));else{const r=ut(t.subarray(s+8,a),e.slice(1));r.length&&st.apply(i,r)}s=a}return i}function ct(t){const e=[],i=t[0];let r=8;const s=lt(t,r);r+=4;let n=0,a=0;0===i?(n=lt(t,r),a=lt(t,r+4),r+=8):(n=ht(t,r),a=ht(t,r+8),r+=16),r+=2;let o=t.length+a;const l=ot(t,r);r+=2;for(let i=0;i<l;i++){let i=r;const n=lt(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return O.warn("SIDX has hierarchical references (not supported)"),null;const l=lt(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:e}}function ft(t){const e=[],i=ut(t,["moov","trak"]);for(let t=0;t<i.length;t++){const r=i[t],s=ut(r,["tkhd"])[0];if(s){let t=s[0];const i=lt(s,0===t?12:20),n=ut(r,["mdia","mdhd"])[0];if(n){t=n[0];const s=lt(n,0===t?12:20),a=ut(r,["mdia","hdlr"])[0];if(a){const t=at(a.subarray(8,12)),n={soun:X,vide:Q}[t],o=gt(ut(r,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:s,type:n,stsd:o},e[n]=b({timescale:s,id:i},o)):e[i]={timescale:s,type:t,stsd:o}}}}}return ut(t,["moov","mvex","trex"]).forEach((t=>{const i=lt(t,4),r=e[i];r&&(r.default={duration:lt(t,12),flags:lt(t,20)})})),e}function gt(t){const e=t.subarray(8),i=e.subarray(86),r=at(e.subarray(4,8));let s,n=r;const a="enca"===r||"encv"===r;if(a){const t=ut(e,[r])[0];ut(t.subarray("enca"===r?28:78),["sinf"]).forEach((t=>{const e=ut(t,["schm"])[0];if(e){const i=at(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=ut(t,["frma"])[0];e&&(n=at(e))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=ut(i,["avcC"])[0];t&&t.length>3&&(n+="."+vt(t[1])+vt(t[2])+vt(t[3]),s=mt("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=ut(e,[r])[0],i=ut(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=pt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=pt(i,t);const r=i[t++];if(64!==r)break;if(n+="."+vt(r),t+=12,5!==i[t++])break;t=pt(i,t);const s=i[t++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=ut(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],r=31&e,s=lt(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+i+r,n+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(s).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let t=l.length;t--;){const e=l[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}n+=h}s=mt("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=mt(n,i)||n;break;case"vp09":{const t=ut(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],r=t[6]>>4&15;n+="."+yt(e)+"."+yt(i)+"."+yt(r)}break}case"av01":{const t=ut(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,r=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,h=2===e&&o?l?12:10:o?10:8,d=(16&t[2])>>4,u=(8&t[2])>>3,c=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+yt(r)+a+"."+yt(h)+"."+d+"."+u+c+f+"."+yt(g)+"."+yt(m)+"."+yt(p)+"."+v,s=mt("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:s}}function mt(t,e){const i=ut(e,["dvvC"]),r=i.length?i[0]:ut(e,["dvcC"])[0];if(r){const e=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return t+"."+yt(e)+"."+yt(i)}}function pt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function vt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function yt(t){return(t<10?"0":"")+t}function Et(t){const e=ut(t,["schm"])[0];if(e){const i=at(e.subarray(4,8));if("cbcs"===i||"cenc"===i)return ut(t,["schi","tenc"])[0]}return null}function Tt(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function St(t,e){const i=[],r=e.samples,s=e.timescale,n=e.id;let a=!1;return ut(r,["moof"]).map((o=>{const l=o.byteOffset-8;ut(o,["traf"]).map((o=>{const h=ut(o,["tfdt"]).map((t=>{const e=t[0];let i=lt(t,4);return 1===e&&(i*=Math.pow(2,32),i+=lt(t,8)),i/s}))[0];return void 0!==h&&(t=h),ut(o,["tfhd"]).map((h=>{const d=lt(h,4),u=16777215&lt(h,0);let c=0;const f=!!(16&u);let g=0;const m=!!(32&u);let p=8;d===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=lt(h,p),p+=4),f&&(g=lt(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=At(e.codec)),ut(o,["trun"]).map((n=>{const o=n[0],h=16777215&lt(n,0),d=!!(1&h);let u=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const A=lt(n,4);let L=8;d&&(u=lt(n,L),L+=4),f&&(L+=4);let R=u+l;for(let l=0;l<A;l++){if(m?(p=lt(n,L),L+=4):p=c,v?(y=lt(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?lt(n,L):dt(n,L),L+=4),e.type===Q){let e=0;for(;e<y;){const n=lt(r,R);if(R+=4,Lt(a,r[R])){Rt(r.subarray(R,R+n),a?2:1,t+S/s,i)}R+=n,e+=n+4}}t+=p/s}})))}))}))})),i}function At(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Lt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Rt(t,e,i,r){const s=It(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const t=s.length-n;let e=n;if(o<t)n+=o;else if(o>t){O.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===s[e++]){const t=ot(s,e);if(e+=2,49===t){const t=lt(s,e);if(e+=4,1195456820===t){const t=s[e++];if(3===t){const n=s[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t<l;t++)h[t]=s[e++]}r.push({type:t,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const r=s[e++].toString(16);t.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=s[e++];r.push({payloadType:a,pts:i,uuid:t.join(""),userData:F(l),userDataBytes:l})}}}function It(t){const e=t.byteLength,i=[];let r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return t;const s=e-i.length,n=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=t[a];return n}function bt(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let r,s,n;r=0,s=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let r=8,s=i;for(;s--;)r+=e[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),s=0,r=8;s<i;s++)n.set(e[s],r),r+=e[s].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,s,a,i)}const kt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Dt={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function _t(t,e){const i=Dt[e];return!!i&&!!i[t.slice(0,4)]}function Pt(t,e,i=!0){return!t.split(",").some((t=>!Ct(t,e,i)))}function Ct(t,e,i=!0){var r;const s=x(i);return null!=(r=null==s?void 0:s.isTypeSupported(wt(t,e)))&&r}function wt(t,e){return`${e}/mp4;codecs=${t}`}function Ot(t){if(t){const e=t.substring(0,4);return Dt.video[e]}return 2}function xt(t){const e=kt();return t.split(",").reduce(((t,i)=>{const r=e&&At(i)?9:Dt.video[i];return r?(2*r+t)/(t?3:2):(Dt.audio[i]+t)/(t?2:1)}),0)}const Mt={};const Ft=/flac|opus|mp4a\.40\.34/i;function Nt(t,e=!0){return t.replace(Ft,(t=>function(t,e=!0){if(Mt[t])return Mt[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let s=0;s<i.length;s++){var r;if(Ct(i[s],"audio",e))return Mt[t]=i[s],i[s];if("mp3"===i[s]&&null!=(r=x(e))&&r.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e)))}function Ut(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Bt(t,"audio")||Bt(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function Bt(t,e){return _t(t,e)&&Ct(t,e)}function Gt(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function $t(t){const e=x(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 Kt(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Vt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ht(t,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:t}}function Yt(t,e,i,r,s,n){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,h=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,u=d?parseInt(d):h?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,i)=>{if(i){const r=e.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((e=>{t[e]=(t[e]||0)+r.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==a&&(a.split(",").some((t=>At(t)))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(s,8e6))||!!c&&l(u)&&Object.keys(c).some((t=>parseInt(t)>u))}function Wt(t,e,i,r={}){const s=t.videoCodec;if(!s&&!t.audioCodec||!i)return Promise.resolve(Vt);const n=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),r=qt(t),s=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map((t=>{const e={contentType:wt(Gt(t),"video"),width:s,height:n,bitrate:r,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e})):[]}(t),o=a.length,l=function(t,e,i){var r;const s=null==(r=t.audioCodec)?void 0:r.split(","),n=qt(t);if(s&&t.audioGroups)return t.audioGroups.reduce(((t,r)=>{var a;const o=r?null==(a=e.groups[r])?void 0:a.tracks:null;return o?o.reduce(((t,e)=>{if(e.groupId===r){const r=parseFloat(e.channels||"");s.forEach((e=>{const s={contentType:wt(e,"audio"),bitrate:i?jt(e,n):n};r&&(s.channels=""+r),t.push(s)}))}return t}),t):t}),[]);return[]}(t,e,o>0),h=l.length;for(let t=o||1*h||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),h){e.audio=l[t%h];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}n.push(e)}if(s){const t=navigator.userAgent;if(s.split(",").some((t=>At(t)))&&kt())return Promise.resolve(Ht(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:i,video:r}=t;if(r){e+=`${Kt(r.contentType)}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(i){e+=`${r?"_":""}${Kt(i.contentType)}_c${i.channels}`}return e}(t);return r[e]||(r[e]=i.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:n,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t})))}function jt(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function qt(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const Xt=["NONE","TYPE-0","TYPE-1",null];const Qt=["SDR","PQ","HLG"];var zt="",Zt="YES",Jt="v2";function te(t){const{canSkipUntil:e,canSkipDateRanges:i,age:r}=t;return e&&r<e/2?i?Jt:Zt:zt}class ee{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}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}}class ie{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 i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.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 re(this._audioGroups,t)}hasSubtitleGroup(t){return re(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(){}}function re(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function se(t,e){let i=!1,r=[];if(t&&(i="SDR"!==t,r=[t]),e){r=e.allowedVideoRanges||Qt.slice(0);const t="SDR"!==r.join("")&&!e.videoCodec;i=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}(),i||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}const ne=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,r)=>{if(t&&(r=t(i,r)),"object"==typeof r&&null!==r){if(e.has(r))return;e.add(r)}return r}})(e));function ae(t,e){O.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function oe(t){return t.reduce(((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const r=e.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function le(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:r,channels:s,audioCodec:n}=t;return{lang:e,assocLang:i,characteristics:r,channels:s,audioCodec:n}}function he(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let r=0;r<e.length;r++){if(de(t,e[r],i))return r}return-1}function de(t,e,i){const{groupId:r,name:s,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===r||e.groupId===r)&&(void 0===s||e.name===s)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return 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 i=t.split(","),r=e.split(",");return i.length===r.length&&!i.some((t=>-1===r.indexOf(t)))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function ue(t,e){const{audioCodec:i,channels:r}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function ce(t,e,i){for(let r=e;r>-1;r--)if(i(t[r]))return r;for(let r=e+1;r<t.length;r++)if(i(t[r]))return r;return-1}function fe(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}const ge=function(t,e){let i=0,r=t.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=t[s];const a=e(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function me(t,e,i=0,r=0,s=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const r=t.endDTS-i;r>0&&r<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===pe(i,r,n)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const r=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),i);return t.start<=r}return!1}(n,t,Math.min(s,r))))return n;const a=ge(e,pe.bind(null,i,r));return!a||a===t&&n?n:a}function pe(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const r=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=t?1:i.start-r>t&&i.start?-1:0}function ve(t,e,i){const r=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>t}function ye(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let r=t.fragments;const{fragmentHint:s}=t;let n;return s&&(r=r.concat(s)),ge(r,(t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=i?1:t.start>i?-1:0))),n||null}return null}function Ee(t){switch(t.details){case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_TIMEOUT:case c.LEVEL_LOAD_TIMEOUT:case c.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Te(t,e){const i=Ee(e);return t.default[(i?"timeout":"error")+"Retry"]}function Se(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function Ae(t){return b(b({},t),{errorRetry:null,timeoutRetry:null})}function Le(t,e,i,r){if(!t)return!1;const s=null==r?void 0:r.code,n=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(s)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,r,n):n}var Re=0,Ie=2,be=3,ke=5,De=0,_e=1,Pe=2;function Ce(t){const e={action:Re,flags:De};return t&&(e.resolved=!0),e}var we="NOT_LOADED",Oe="APPENDING",xe="PARTIAL",Me="OK";class Fe{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(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.BUFFER_APPENDED,this.onBufferAppended,this),t.on(f.FRAG_BUFFERED,this.onFragBuffered,this),t.on(f.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.BUFFER_APPENDED,this.onBufferAppended,this),t.off(f.FRAG_BUFFERED,this.onFragBuffered,this),t.off(f.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const r=i[e];if(!r)break;if(r.start<=t&&t<=r.end&&r.loaded)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:r}=this,s=Object.keys(r);for(let n=s.length;n--;){const a=r[s[n]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,r,s){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const a=this.fragments[r];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||s))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some((t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(a.body),i})):this.removeFragment(a.body))}))}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const i=t.frag,r=Ue(i),s=this.fragments[r];if(!s||s.buffered&&i.gap)return;const n=!i.relurl;if(Object.keys(e).forEach((r=>{const a=i.elementaryStreams[r];if(!a)return;const o=e[r],l=n||!0===a.partial;s.range[r]=this.getBufferedTimes(i,t.part,l,o)})),s.loaded=null,Object.keys(s.range).length){s.buffered=!0;(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),Ne(s)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(s.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Be(i,(e=>e.fragment.sn>=t)))}fragBuffered(t,e){const i=Ue(t);let r=this.fragments[i];!r&&e&&(r=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(t,e,i,r){const s={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<r.length;t++){const e=r.start(t)-this.bufferPadding,i=r.end(t)+this.bufferPadding;if(l>=e&&o<=i){s.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});break}if(n<i&&a>e){const e=Math.max(n,r.start(t)),i=Math.min(a,r.end(t));i>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return s}getPartialFragment(t){let e,i,r,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&Ne(h)&&(i=h.body.start-a,r=h.body.end+a,t>=i&&t<=r&&(e=Math.min(t-i,r-t),n<=e&&(s=h.body,n=e)))})),s}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Ne(e))}getState(t){const e=Ue(t),i=this.fragments[e];return i?i.buffered?Ne(i)?xe:Me:Oe:we}isTimeBuffered(t,e,i){let r,s;for(let n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,t>=r&&e<=s)return!0;if(e<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const i=e.frag,r=e.part?null:e,s=Ue(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:r,timeRanges:s,type:n}=e;if("initSegment"===i.sn)return;const a=i.type;if(r){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(r)}this.timeRanges=s;const o=s[n];this.detectEvictedFragments(n,o,a,r)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ue(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let r=i.length;r--;){const s=e[i[r]];if((null==s?void 0:s.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.start<e&&o.end>t&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(t){const e=Ue(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Be(i,(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()))}}function Ne(t){var e,i,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(r=t.range.audiovideo)&&r.partial)}function Ue(t){return`${t.type}_${t.level}_${t.sn}`}function Be(t,e){return t.filter((t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i}))}var Ge=0,$e=1;class Ke{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case Ge:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case $e:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Ve{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),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=c[f],m=c[o],p=c[m];let v=257*c[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,u[i]=v,f?(f=o^c[c[c[p^o]]],g^=c[c[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,r=0;for(;r<e.length&&i;)i=e[r]===this.key[r],r++;if(i)return;this.key=e;const s=this.keySize=e.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,u=this.rcon,c=this.invSubMix,f=c[0],g=c[1],m=c[2],p=c[3];let v,y;for(a=0;a<n;a++)a<s?v=l[a]=e[a]:(y=v,a%s==0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=u[a/s|0]<<24):s>6&&a%s==4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-s]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const r=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],u=this.uint8ArrayToUint32Array_(i);let c=u[0],f=u[1],g=u[2],m=u[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,A,L,R,I,b,k,D,_,P,C;const w=this.networkToHostOrderSwap;for(;e<p.length;){for(b=w(p[e]),k=w(p[e+1]),D=w(p[e+2]),_=w(p[e+3]),A=b^s[0],L=_^s[1],R=D^s[2],I=k^s[3],P=4,C=1;C<r;C++)y=o[A>>>24]^l[L>>16&255]^h[R>>8&255]^d[255&I]^s[P],E=o[L>>>24]^l[R>>16&255]^h[I>>8&255]^d[255&A]^s[P+1],T=o[R>>>24]^l[I>>16&255]^h[A>>8&255]^d[255&L]^s[P+2],S=o[I>>>24]^l[A>>16&255]^h[L>>8&255]^d[255&R]^s[P+3],A=y,L=E,R=T,I=S,P+=4;y=n[A>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&I]^s[P],E=n[L>>>24]<<24^n[R>>16&255]<<16^n[I>>8&255]<<8^n[255&A]^s[P+1],T=n[R>>>24]<<24^n[I>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^s[P+2],S=n[I>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^s[P+3],v[e]=w(y^c),v[e+1]=w(S^f),v[e+2]=w(T^g),v[e+3]=w(E^m),c=b,f=k,g=D,m=_,e+=4}return v.buffer}}class He{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case Ge:return"AES-CBC";case $e:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Ye{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(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,r){return this.useSoftware?new Promise(((s,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,r);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,i,r)}softwareDecrypt(t,e,i,r){const{currentIV:s,currentResult:n,remainderData:a}=this;if(r!==Ge||16!==e.byteLength)return O.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Tt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ve),l.expandKey(e);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(t,e,i,r){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,r));this.key=e,this.fastAesKey=new He(this.subtle,e,r)}return this.fastAesKey.expandKey().then((e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ke(this.subtle,new Uint8Array(i),r).decrypt(t.buffer,e)})).catch((s=>(O.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,i,r))))}onWebCryptoError(t,e,i,r){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,r);const s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(O.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const We=Math.pow(2,17);class je{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 i=t.url;if(!i)return Promise.reject(new Qe({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,s=r.fLoader,n=r.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(Xe(t));t.gap=!1}const l=this.loader=s?new s(r):new n(r),h=qe(t);t.loader=l;const d=Ae(r.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:We};t.stats=l.stats;const g={onSuccess:(e,i,r,s)=>{this.resetLoader(t,l);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:s})},onError:(e,r,s,n)=>{this.resetLoader(t,l),o(new Qe({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:b({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:s,stats:n}))},onAbort:(e,i,r)=>{this.resetLoader(t,l),o(new Qe({type:u.NETWORK_ERROR,details:c.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,i,r)=>{this.resetLoader(t,l),o(new Qe({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:r,stats:e}))}};e&&(g.onProgress=(i,r,s,n)=>e({frag:t,part:null,payload:s,networkDetails:n})),l.load(h,f,g)}))}loadPart(t,e,i){this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Xe(t,e));const l=this.loader=s?new s(r):new n(r),h=qe(t,e);t.loader=l;const d=Ae(r.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:We};e.stats=l.stats,l.load(h,f,{onSuccess:(r,s,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:r.data,networkDetails:o};i(h),a(h)},onError:(i,r,s,n)=>{this.resetLoader(t,l),o(new Qe({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:b({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new Qe({type:u.NETWORK_ERROR,details:c.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(t,l),o(new Qe({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(t,e){const i=t.stats,r=e.stats,s=r.total;if(i.loaded+=r.loaded,s){const r=Math.round(t.duration/e.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=r.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()}}function qe(t,e=null){const i=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(l(s)&&l(n)){var a;let e=s,i=n;if("initSegment"===t.sn&&("AES-128"===(o=null==(a=t.decryptdata)?void 0:a.method)||"AES-256"===o)){const t=n-s;t%16&&(i=n+(16-t%16)),0!==s&&(r.resetIV=!0,e=s-16)}r.rangeStart=e,r.rangeEnd=i}var o;return r}function Xe(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:u.MEDIA_ERROR,details:c.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new Qe(r)}class Qe extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class ze 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(){}}class Ze{constructor(t,e,i,r=0,s=-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=i,this.size=r,this.part=s,this.partial=n}}const Je={length:0,start:()=>0,end:()=>0};class ti{static isBuffered(t,e){if(t){const i=ti.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=ti.getBuffered(t);return ti.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const r=ti.bufferedRanges(t);if(r.length)return ti.bufferedInfo(r,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort(((t,e)=>t.start-e.start||e.end-t.end));let r=-1,s=[];if(i)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(r=n);const a=s.length;if(a){const e=s[a-1].end;t[n].start-e<i?t[n].end>e&&(s[a-1].end=t[n].end):s.push(t[n])}else s.push(t[n])}else s=t;let n,a=0,o=e,l=e;for(let t=0;t<s.length;t++){const h=s[t].start,d=s[t].end;if(-1===r&&e>=h&&e<=d&&(r=t),e+i>=h&&e<d)o=h,l=d,a=l-e;else if(e+i<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:r}}static getBuffered(t){try{return t.buffered||Je}catch(t){return O.log("failed to get media.buffered",t),Je}}}const ei=/\{\$([a-zA-Z0-9-_]+)\}/g;function ii(t){return ei.test(t)}function ri(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(ei,(e=>{const r=e.substring(2,e.length-1),s=null==i?void 0:i[r];return void 0===s?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),e):s}))}return e}function si(t,e,i){let r,s,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=t.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else r=e.NAME,s=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function ni(t,e,i){const r=e.IMPORT;if(i&&r in i){let e=t.variableList;e||(t.variableList=e={}),e[r]=i[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const ai=/^(\d+)x(\d+)$/,oi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class li{constructor(t,e){"string"==typeof t&&(t=li.parseAttrList(t,e)),R(this,t)}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 i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}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 i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce(((t,e)=>(t[e.toLowerCase()]=!0,t)),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=ai.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const r={};for(oi.lastIndex=0;null!==(i=oi.exec(t));){const s=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=ri(e,n);else if(!o&&!a)switch(s){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":O.warn(`${t}: attribute ${s} is missing quotes`)}r[s]=n}return r}}function hi(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class di{constructor(t,e,i=0){var r;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!=(r=null==e?void 0:e.tagOrder)?r:i,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){O.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=R(new li({}),i,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"]);l(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?(O.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(l(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&&l(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class ui{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,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}get hasProgramDateTime(){return!!this.fragments.length&&l(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 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 i=t.length;i--;)if(t[i].index>e)return t[i].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}}function ci(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function fi(t){switch(t){case"AES-128":case"AES-256":return Ge;case"AES-256-CTR":return $e;default:throw new Error(`invalid full segment method ${t}`)}}function gi(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function mi(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}function pi(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){const e="base64"===r[0],s=r[1];e?(t.splice(-1,1),i=gi(s)):i=function(t){const e=mi(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(s)}}return i}const vi="undefined"!=typeof self?self:void 0;var yi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ei="org.w3.clearkey",Ti="com.apple.streamingkeydelivery",Si="com.microsoft.playready",Ai="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Li(t){switch(t){case Ti:return yi.FAIRPLAY;case Si:return yi.PLAYREADY;case Ai:return yi.WIDEVINE;case Ei:return yi.CLEARKEY}}function Ri(t){switch(t){case yi.FAIRPLAY:return Ti;case yi.PLAYREADY:return Si;case yi.WIDEVINE:return Ai;case yi.CLEARKEY:return Ei}}function Ii(t){const{drmSystems:e,widevineLicenseUrl:i}=t,r=e?[yi.FAIRPLAY,yi.WIDEVINE,yi.PLAYREADY,yi.CLEARKEY].filter((t=>!!e[t])):[];return!r[yi.WIDEVINE]&&i&&r.push(yi.WIDEVINE),r}const bi=null!=vi&&null!=(ki=vi.navigator)&&ki.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ki;let Di={};class _i{static clearKeyUriToKeyIdMap(){Di={}}constructor(t,e,i,r=[1],s=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=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ci(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(U(n)))}matches(t){var e,i;return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&t.keyFormatVersions.join(",")===this.keyFormatVersions.join(",")&&(null==(e=t.iv)?void 0:e.join(","))===(null==(i=this.iv)?void 0:i.join(","))}isSupported(){if(this.method){if(ci(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ti:case Ai:case Si:case Ei:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(ci(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(O.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t);return new _i(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.pssh&&this.keyId)return this;const e=pi(this.uri);if(e)switch(this.keyFormat){case Ai:if(this.pssh=e,!this.keyId&&e.length>=22){const t=e.length-22;this.keyId=e.subarray(t,t+16)}break;case Si:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=bt(t,0,e),this.keyId=function(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),r=i.substring(i.indexOf("<"),i.length),s=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){const t=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(t){const e=gi(t).subarray(0,16);return function(t){const e=function(t,e,i){const r=t[e];t[e]=t[i],t[i]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),e}}return null}(e);break}default:{let t=e.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 t=Di[this.uri];if(!t){const e=Object.keys(Di).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),Di[this.uri]=t}this.keyId=t}return this}}const Pi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Ci=/#EXT-X-MEDIA:(.*)/g,wi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Oi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),xi=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Mi{static findGroup(t,e){for(let i=0;i<t.length;i++){const r=t[i];if(r.id===e)return r}}static resolve(t,e){return j.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return wi.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:ii(t)},r=[];let s;for(Pi.lastIndex=0;null!=(s=Pi.exec(t));)if(s[1]){var n;const t=new li(s[1],i),a=ri(i,s[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Mi.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Gi(t.CODECS,o);const h=t["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},Gi(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||r.push(o),i.levels.push(o)}else if(s[3]){const t=s[3],r=s[4];switch(t){case"SESSION-DATA":{const t=new li(r,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ui(r,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):O.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":si(i,new li(r,i),e);break;case"CONTENT-STEERING":{const t=new li(r,i);i.contentSteering={uri:Mi.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Bi(r)}}const a=r.length>0&&r.length<i.levels.length;return i.levels=a?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let r;const s={},n=i.levels,a={AUDIO:n.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Ci.lastIndex=0;null!==(r=Ci.exec(t));){const t=new li(r[1],i),n=t.TYPE;if(n){const i=a[n],r=s[n]||[];s[n]=r;const l=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],d=t.CHANNELS,u=t.CHARACTERISTICS,c=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Mi.resolve(t.URI,e):""};if(h&&(f.assocLang=h),d&&(f.channels=d),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=i&&i.length){const t=Mi.findGroup(i,f.groupId)||i[0];$i(f,t,"audioCodec"),$i(f,t,"textCodec")}r.push(f)}}return s}static parseLevelPlaylist(t,e,i,r,s,n){var a;const o={url:e},h=new ui(e),d=h.fragments,u=[];let c,f,g,m,p=null,v=0,y=0,E=0,T=0,S=0,A=null,L=new tt(r,o),I=-1,b=!1,k=null;if(Oi.lastIndex=0,h.m3u8=t,h.hasVariableRefs=ii(t),"#EXTM3U"!==(null==(a=Oi.exec(t))?void 0:a[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(c=Oi.exec(t));){b&&(b=!1,L=new tt(r,o),L.playlistOffset=E,L.setStart(E),L.sn=v,L.cc=T,S&&(L.bitrate=S),L.level=i,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),k&&(L.setByteRange(k),k=null)));const t=c[1];if(t){L.duration=parseFloat(t);const e=(" "+c[2]).slice(1);L.title=e||null,L.tagList.push(e?["INF",t,e]:["INF",t])}else if(c[3]){if(l(L.duration)){L.playlistOffset=E,L.setStart(E),g&&Hi(L,g,h),L.sn=v,L.level=i,L.cc=T,d.push(L);const t=(" "+c[3]).slice(1);L.relurl=ri(h,t),Ki(L,A,u),A=L,E+=L.duration,v++,y=0,b=!0}}else{if(c=c[0].match(xi),!c){O.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<c.length&&void 0===c[f];f++);const t=(" "+c[f]).slice(1),s=(" "+c[f+1]).slice(1),a=c[f+2]?(" "+c[f+2]).slice(1):null;switch(t){case"BYTERANGE":A?L.setByteRange(s,A):L.setByteRange(s);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=s,L.tagList.push(["PROGRAM-DATE-TIME",s]),-1===I&&(I=d.length);break;case"PLAYLIST-TYPE":h.type&&Yi(h,t,c),h.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Yi(h,t,c):d.length>0&&Wi(h,t,c),v=h.startSN=parseInt(s);break;case"SKIP":{h.skippedSegments&&Yi(h,t,c);const e=new li(s,h),i=e.decimalInteger("SKIPPED-SEGMENTS");if(l(i)){h.skippedSegments+=i;for(let t=i;t--;)d.push(null);v+=i}const r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==h.targetduration&&Yi(h,t,c),h.targetduration=Math.max(parseInt(s),1);break;case"VERSION":null!==h.version&&Yi(h,t,c),h.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Yi(h,t,c),h.live=!1;break;case"#":(s||a)&&L.tagList.push(a?[s,a]:[s]);break;case"DISCONTINUITY":T++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([t]);break;case"BITRATE":L.tagList.push([t,s]),S=1e3*parseInt(s),l(S)?L.bitrate=S:S=0;break;case"DATERANGE":{const t=new li(s,h),e=new di(t,h.dateRanges[t.ID],h.dateRangeTagCount);h.dateRangeTagCount++,e.isValid||h.skippedSegments?h.dateRanges[e.id]=e:O.warn(`Ignoring invalid DATERANGE tag: "${s}"`),L.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const t=new li(s,h);"IMPORT"in t?ni(h,t,n):si(h,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?Yi(h,t,c):d.length>0&&Wi(h,t,c),h.startCC=T=parseInt(s);break;case"KEY":{const t=Ui(s,e,h);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=R({},g)),g[t.keyFormat]=t)}else O.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":h.startTimeOffset=Bi(s);break;case"MAP":{const t=new li(s,h);if(L.duration){const e=new tt(r,o);Vi(e,t,i,g),p=e,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{const e=L.byteRangeEndOffset;if(e){const t=L.byteRangeStartOffset;k=`${e-t}@${t}`}else k=null;Vi(L,t,i,g),p=L,b=!0}p.cc=T;break}case"SERVER-CONTROL":m&&Yi(h,t,c),m=new li(s),h.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),h.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{h.partTarget&&Yi(h,t,c);const e=new li(s);h.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=h.partList;t||(t=h.partList=[]);const e=y>0?t[t.length-1]:void 0,i=y++,r=new li(s,h),n=new et(r,L,o,i,e);t.push(n),L.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new li(s,h);h.preloadHint=t;break}case"RENDITION-REPORT":{const t=new li(s,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(t);break}default:O.warn(`line parsed but not handled: ${c}`)}}}A&&!A.relurl?(d.pop(),E-=A.duration,h.partList&&(h.fragmentHint=A)):h.partList&&(Ki(L,A,u),L.cc=T,h.fragmentHint=L,g&&Hi(L,g,h)),h.targetduration||(h.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const D=d.length,_=d[0],P=d[D-1];if(E+=h.skippedSegments*h.targetduration,E>0&&D&&P){h.averagetargetduration=E/D;const t=P.sn;h.endSN="initSegment"!==t?t:0,h.live||(P.endList=!0),I>0&&(!function(t,e){let i=t[e];for(let r=e;r--;){const e=t[r];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(d,I),_&&u.unshift(_))}return h.fragmentHint&&(E+=h.fragmentHint.duration),h.totalduration=E,u.length&&h.dateRangeTagCount&&_&&Fi(u,h),h.endCC=T,h}}function Fi(t,e){const i=t.length;if(!i)return;const r=t[i-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=r.ref;for(let r=i;r--;){var a;if((null==(a=t[r])?void 0:a.sn)<e.startSN)break;const i=Ni(e,h,t,r,s);if(-1!==i){l.tagAnchor=e.fragments[i].ref;break}}}}function Ni(t,e,i,r,s){const n=i[r];if(n){const o=n.programDateTime;if(e>=o||0===r){var a;if(e<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||s)-n.start)){const s=i[r].sn-t.startSN;if(s<0)return-1;const n=t.fragments;if(n.length>i.length){for(let a=(i[r+1]||n[n.length-1]).sn-t.startSN;a>s;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}}return s}}}return-1}function Ui(t,e,i){var r,s;const n=new li(t,i),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&O.error(`Invalid IV: ${n.IV}`);const u=o?Mi.resolve(o,e):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new _i(a,u,d,c,l,n.KEYID)}function Bi(t){const e=new li(t).decimalFloatingPoint("TIME-OFFSET");return l(e)?e:null}function Gi(t,e){let i=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const r=i.filter((e=>_t(e,t)));r.length&&(e[`${t}Codec`]=r.map((t=>t.split("/")[0])).join(","),i=i.filter((t=>-1===r.indexOf(t))))})),e.unknownCodecs=i}function $i(t,e,i){const r=e[i];r&&(t[i]=r)}function Ki(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Vi(t,e,i,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function Hi(t,e,i){t.levelkeys=e;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||r.push(t)}function Yi(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function Wi(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function ji(t,e){const i=e.startPTS;if(l(i)){let r,s=0;e.sn>t.sn?(s=i-t.start,r=t):(s=t.start-i,r=e),r.duration!==s&&r.setDuration(s)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function qi(t,e,i,r,s,n,a){r-i<=0&&(a.warn("Fragment should have a positive duration",e),r=i+e.duration,n=s+e.duration);let o=i,h=r;const d=e.startPTS,u=e.endPTS;if(l(d)){const c=Math.abs(d-i);t&&c>t.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${e.level} ${t.url}`):l(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,o=Math.max(i,d),i=Math.min(i,d),s=void 0!==e.startDTS?Math.min(s,e.startDTS):s,h=Math.min(r,u),r=Math.max(r,u),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}const c=i-e.start;0!==e.start&&e.setStart(i),e.setDuration(r-e.start),e.startPTS=i,e.maxStartPTS=o,e.startDTS=s,e.endPTS=r,e.minEndPTS=h,e.endDTS=n;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const m=f-t.startSN,p=t.fragments;for(p[m]=e,g=m;g>0;g--)ji(p[g],p[g-1]);for(g=m;g<p.length-1;g++)ji(p[g],p[g+1]);return t.fragmentHint&&ji(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function Xi(t,e,i){if(t===e)return;let r=null;const s=t.fragments;for(let t=s.length-1;t>=0;t--){const e=s[t].initSegment;if(e){r=e;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){const r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?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 h=s;h<=n;h++){const s=l[a+h];let n=o[h];if(r&&!n&&s&&(n=e.fragments[h]=s),s&&n){if(i(s,n,h,o),s.url&&s.url!==n.url)return void(e.playlistParsingError=Qi(`media sequence mismatch ${n.sn}:`,t,e,s,n));if(s.cc!==n.cc)return void(e.playlistParsingError=Qi(`discontinuity sequence mismatch (${s.cc}!=${n.cc})`,t,e,s,n))}}}(t,e,((t,i,s,a)=>{if((!e.startCC||e.skippedSegments)&&i.cc!==t.cc){const r=t.cc-i.cc;for(let t=s;t<a.length;t++)a[t].cc+=r;e.endCC=a[a.length-1].cc}l(t.startPTS)&&l(t.endPTS)&&(i.setStart(i.startPTS=t.startPTS),i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.setDuration(t.endPTS-t.startPTS),i.duration&&(n=i),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(i.elementaryStreams=t.elementaryStreams),i.loader=t.loader,t.hasStats&&(i.stats=t.stats),t.initSegment&&(i.initSegment=t.initSegment,r=t.initSegment)}));const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(r&&o.forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=r)?void 0:e.relurl)||(t.initSegment=r)})),e.skippedSegments){if(e.deltaUpdateFailed=a.some((t=>!t)),e.deltaUpdateFailed){i.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,i){const{dateRanges:r,recentlyRemovedDateranges:s}=e,n=R({},t);s&&s.forEach((t=>{delete n[t]}));const a=Object.keys(n).length;a&&Object.keys(r).forEach((t=>{const e=n[t],s=new di(r[t].attr,e);s.isValid?(n[t]=s,e||(s.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ne(r[t].attr)}"`)}));return n}(t.dateRanges,e,i));const r=t.fragments.filter((t=>t.rawProgramDateTime));if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&Ki(o[t],o[t-1],r);Fi(r,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var h;const i=tr(t,e.startSN-1);e.startCC=null!=(h=null==i?void 0:i.cc)?h:a[0].cc}!function(t,e,i){if(t&&e){let r=0;for(let s=0,n=t.length;s<=n;s++){const n=t[s],a=e[s+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):r--}}}(t.partList,e.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),n?qi(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,i):zi(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 Qi(t,e,i,r,s){return new Error(`${t} ${s.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function zi(t,e,i=!0){const r=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,n=r>=0;let a=0;if(n&&r<s.length)a=s[r].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&i)a=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}Zi(e,a)}function Zi(t,e){if(e){const i=t.fragments;for(let r=t.skippedSegments;r<i.length;r++)i[r].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function Ji(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const r=t.fragments,s=4;if(r.length&&i*s>e){const t=1e3*r[r.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function tr(t,e,i){if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,r&&r.sn===e?r:e<t.startSN&&i&&i.sn===e?i:null)}function er(t,e,i){return t?ir(t.partList,e,i):null}function ir(t,e,i){if(t)for(let r=t.length;r--;){const s=t[r];if(s.index===i&&s.fragment.sn===e)return s}return null}function rr(t){t.forEach(((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach((t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)}))}))}function sr(t,e){for(let r=0,s=t.length;r<s;r++){var i;if((null==(i=t[r])?void 0:i.cc)===e)return t[r]}return null}function nr(t,e){const i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function ar(t,e){const i=e.fragments;for(let e=0,r=i.length;e<r;e++)nr(i[e],t);e.fragmentHint&&nr(e.fragmentHint,t),e.alignedSliding=!0}function or(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),r=sr(e.fragments,i),s=sr(t.fragments,i);if(!r||!s)return;O.log(`Aligning playlist at start of dicontinuity sequence ${i}`);ar(r.start-s.start,t)}function lr(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,r=e.fragments;if(!i.length||!r.length)return;let s,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=sr(r,a),n=sr(i,a)),s&&n||(s=r[Math.floor(r.length/2)],n=sr(i,s.cc)||i[Math.floor(i.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;ar((l-o)/1e3-(n.start-s.start),t)}const hr=function(t){let e="";const i=t.length;for(let r=0;r<i;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e},dr={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ur extends ze{constructor(t,e,i,r,s){super(r,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=dr.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:i,mediaBuffer:r,state:s}=this,n=i?i.currentTime:0,a=ti.bufferInfo(r||i,n,t.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${l(n)?n.toFixed(3):n}, state: ${s}, ${o?"out of":"in"} buffer`),this.state===dr.ENDED)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,r=e.start-i,s=e.start+e.duration+i;if(o||s<a.start||r>a.end){const t=n>s;(n<r||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(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)),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=t,this.fragmentLoader=new je(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Ye(t.config)}registerListeners(){const{hls:t}=this;t.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(f.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===dr.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=dr.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 i=t.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;const s=t.buffered;this.config.maxBufferHole&&s&&s.length>1&&(t=ti.bufferedInfo(s,t.start,0));const n=t.nextStart;if(n&&n>r&&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 ti.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 i=this.media=this.mediaBuffer=e.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===dr.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)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=dr.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,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,(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,i=t.frag;this.fragContextChanged(i)?(e===dr.FRAG_LOADING||!this.fragCurrent&&e===dr.PARSING)&&(this.fragmentTracker.removeFragment(i),this.state=dr.IDLE):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(f.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((e=>{this.state!==dr.STOPPED&&this.state!==dr.ERROR&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===Oe){const e=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,e),s=Math.max(t.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(s,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===xe&&i.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,i=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:i};this.hls.trigger(f.BUFFER_FLUSHING,r)}_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:i,payload:r}=t,s=i.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&ci(s.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,fi(s.method)).catch((t=>{throw e.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((r=>{const s=self.performance.now();return e.trigger(f.FRAG_DECRYPTED,{frag:i,payload:r,stats:{tstart:n,tdecrypt:s}}),t.payload=r,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((e=>{this.state!==dr.STOPPED&&this.state!==dr.ERROR&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state!==dr.STOPPED&&(this.state=dr.IDLE),t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var i,r;const s=t.tracks;if(s&&!e.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(f.ERROR,{type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,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 i=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:${i?hr(ti.getBuffered(i)):"(detached)"})`),J(t)){var r;if(t.type!==T){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=dr.IDLE)}const e=null==(r=this.levels)?void 0:r[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=dr.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:r,partsLoaded:s}=t,n=!s||0===s.length||s.some((t=>!t)),a=new Ze(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,r){var s;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;!t.encrypted||null!=(s=t.decryptdata)&&s.key?t.encrypted||(a=this.keyLoader.loadClear(t,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired")):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=dr.KEY_LOADING,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(f.KEY_LOADED,t),this.state===dr.KEY_LOADING&&(this.state=dr.IDLE),t})),this.hls.trigger(f.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const o=this.fragPrevious;if(J(t)&&(!o||t.sn!==o.sn)){const i=this.shouldLoadParts(e.details,t.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=i)}if(i=Math.max(t.start,i||0),this.loadingParts&&J(t)){const s=n.partList;if(s&&r){i>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(s,t,i);if(o>-1){const l=s[o];let h;return t=this.fragCurrent=l.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${s.length-1}) of ${this.fragInfo(t,!1,l)}) cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=dr.FRAG_LOADING,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,l,e,r))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,r).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(f.FRAG_LOADING,{frag:t,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}var h;if(J(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(h=n.partList)?void 0:h.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(i.toFixed(3))}`),l(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=dr.FRAG_LOADING;const d=this.config.progressive;let u;return u=d&&a?a.then((e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,r))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,d?r:void 0),a]).then((([t])=>(!d&&r&&r(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(f.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(t,e,i,r){return new Promise(((s,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,r).then((r=>{o[e.index]=r;const n=r.part;this.hls.trigger(f.FRAG_LOADED,r);const a=er(i.details,t.sn,e.index+1)||ir(l,t.sn,e.index+1);if(!a)return s({frag:t,part:n,partsLoaded:o});h(a)})).catch(n)};h(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;e&&e.details===c.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(f.ERROR,e)}else this.hls.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==dr.PARSING)return void(this.fragCurrent||this.state===dr.STOPPED||this.state===dr.ERROR||(this.state=dr.IDLE));const{frag:i,part:r,level:s}=e,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,r,s,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i;const s=t.partList[0];if(e>=s.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)){var r;if((this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:r,sn:s,part:n}=t;if(null==e||!e[r])return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const a=e[r],o=a.details,l=n>-1?er(o,s,n):null,h=l?l.fragment:tr(o,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(t,e,i,r,s){if(this.state!==dr.PARSING)return;const{data1:n,data2:a}=t;let o=n;if(a&&(o=Tt(n,a)),!o.length)return;const l=this.initPTS[e.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:t.type,frag:e,part:i,chunkMeta:r,offset:h,parent:e.type,data:o};if(this.hls.trigger(f.BUFFER_APPENDING,d),t.dropped&&t.independent&&!i){if(s)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ti.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,r=ti.bufferInfo(e,i,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,r.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const r=this.getLoadPosition();if(!l(r))return null;const s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,r,e,s)}getFwdBufferInfoAtPos(t,e,i,r){const s=ti.bufferInfo(t,e,r);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(s.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(s.nextStart,n.end)-e,r);return ti.bufferInfo(t,e,i)}}return s}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const i=this.config,r=Math.max(Math.min(t-e,i.maxBufferLength),e),s=Math.max(t-3*e,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(t,e=y){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,r=i.length;if(!r)return null;const{config:s}=this,n=i[0].start,a=s.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=s.initialLiveManifestSize;if(r<i)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${i})`),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 i=this.hls.startPosition,r=this.hls.liveSyncPosition,s=o?(-1!==i&&i>=n?i:r)||o.start:t;this.log(`Setting startPosition to ${s} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${r} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=s}}else t<=n&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let h=this.filterReplacedPrimary(o,e);if(!h&&o){const t=o.sn-e.startSN;h=this.filterReplacedPrimary(i[t+1]||null,e)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===Me||i===xe&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,r,s){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==t&&i.len+t.len>=s){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(cr(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(cr(this.config)&&t.type!==T){const i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){const i=r.event;if(i){if(i.appendInPlace||Math.abs(t.start-r.start)>1||0===r.start)return null}else{if(t.end<=r.start&&!1===(null==e?void 0:e.live))return null;if(t.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||t.start-r.end>1))return null}}const s=null==i?void 0:i.playerQueue;if(s)for(let e=s.length;e--;){const i=s[e].interstitial;if(i.appendInPlace&&t.start>=i.startTime&&t.end<=i.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let r=-1,s=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,r>-1&&i<o.start)break;const l=o.loaded;l?r=-1:(s||(o.independent||n)&&o.fragment===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),r=a),s=l}return r}loadedEndOfParts(t,e){let i;for(let r=t.length;r--;){if(i=t[r],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,i=this.fragPrevious;let r=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!l(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let r=0;r<t.length;++r){const s=t[r];if(ve(e,i,s))return s}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const s=i.sn+1;if(s>=t.startSN&&s<=t.endSN){const n=e[s-t.startSN];i.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=ye(t,i.cc,i.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,i){const{config:r}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,h=i.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let u;if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),t<e){var c;u=me(s,n,t,t<this.lastCurrentTime||t>e-l||null!=(c=this.media)&&c.paused||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const t=u.sn-i.startSN,e=this.fragmentTracker.getState(u);if((e===Me||e===xe&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!d||h[0].fragment.sn>u.sn||!i.live)){if(u.level===s.level){const e=n[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==Me?e:null}}}return u}alignPlaylists(t,e,i){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const s=t.fragmentStart,n=!e,a=t.alignedSliding&&l(s);if(n||!a&&!s){!function(t,e){t&&(or(e,t),e.alignedSliding||lr(e,t),e.alignedSliding||e.skippedSegments||zi(t,e,!1))}(i,t);const s=t.fragmentStart;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${r}`),s}return s}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let i=this.startPosition;i<e&&(i=-1);const r=this.timelineOffset;if(-1===i){const s=null!==this.startTimeOffset,n=s?this.startTimeOffset:t.startTimeOffset;null!==n&&l(n)?(i=e+n,n<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i):t.live?(i=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&J(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===dr.FRAG_LOADING_WAITING_RETRY)||(this.state=dr.IDLE)}onFragmentOrKeyLoadError(t,e){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 s=e.details===c.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const n=e.errorAction,{action:a,flags:o,retryCount:l=0,retryConfig:h}=n||{},d=!!n&&!!h,u=d&&a===ke,f=d&&!n.resolved&&o===_e;if(!u&&f&&J(i)&&!i.endList)this.resetFragmentErrors(t),this.treatAsGap(i),n.resolved=!0;else if((u||f)&&l<h.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=Se(h,l);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${l+1}/${h.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=dr.FRAG_LOADING_WAITING_RETRY}else if(h&&n){if(this.resetFragmentErrors(t),!(l<h.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${l})`);s||a===be||(n.resolved=!0)}else this.state=a===Ie?dr.WAITING_LEVEL:dr.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===dr.PARSING||this.state===dr.PARSED){const e=t.frag,i=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==e?void 0:e.duration)||10);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===E&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==dr.STOPPED&&(this.state=dr.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;const r=ti.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,i),this.state===dr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==dr.STOPPED&&(this.state=dr.IDLE)}resetStartWhenNotLoaded(t){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const 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.warn(`The loading context changed while buffering fragment ${t.sn} of ${this.playlistLabel()} ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,r){const s=i.details;if(!s)return void this.warn("level.details undefined");var n;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=r?0:qi(s,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(f.LEVEL_PTS_UPDATED,{details:s,level:i,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&(0===i.fragmentError&&this.treatAsGap(t,i),null===(null==(n=this.transmuxer)?void 0:n.error))){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(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=dr.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(f.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===y?"level":"track"}fragInfo(t,e=!0,i){var r,s;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${(null!=(r=e&&!i?t.startPTS:(i||t).start)?r:NaN).toFixed(3)}-${(null!=(s=e&&!i?t.endPTS:(i||t).end)?s:NaN).toFixed(3)}]${i&&"main"===t.type?"INDEPENDENT="+(i.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.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function cr(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class fr{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const s=t[e];i.set(s,r),r+=s.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var gr,mr={exports:{}};var pr=(gr||(gr=1,function(module){var t=Object.prototype.hasOwnProperty,e="~";function i(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function s(t,i,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=e?e+i:i;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 n(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(e=!1)),a.prototype.eventNames=function(){var i,r,s=[];if(0===this._eventsCount)return s;for(r in i=this._events)t.call(i,r)&&s.push(e?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(i)):s},a.prototype.listeners=function(t){var i=e?e+t:t,r=this._events[i];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},a.prototype.listenerCount=function(t){var i=e?e+t:t,r=this._events[i];return r?r.fn?1:r.length:0},a.prototype.emit=function(t,i,r,s,n,a){var o=e?e+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,r),!0;case 4:return d.fn.call(d.context,i,r,s),!0;case 5:return d.fn.call(d.context,i,r,s,n),!0;case 6:return d.fn.call(d.context,i,r,s,n,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,i);break;case 3:d[h].fn.call(d[h].context,i,r);break;case 4:d[h].fn.call(d[h].context,i,r,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return s(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return s(this,t,e,i,!0)},a.prototype.removeListener=function(t,i,r,s){var a=e?e+t:t;if(!this._events[a])return this;if(!i)return n(this,a),this;var o=this._events[a];if(o.fn)o.fn!==i||s&&!o.once||r&&o.context!==r||n(this,a);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==i||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},a.prototype.removeAllListeners=function(t){var r;return t?(r=e?e+t:t,this._events[r]&&n(this,r)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,module.exports=a}(mr)),mr.exports),vr=B(pr);const yr="1.6.9",Er={};function Tr(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 Sr(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 Ar(t,e){let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i}function Lr(t,e){const i=e;let r=0;for(;Sr(t,e);){r+=10;r+=Ar(t,e+6),Tr(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(i,i+r)}function Rr(t,e){return 255===t[e]&&240==(246&t[e+1])}function Ir(t,e){return 1&t[e+1]?7:9}function br(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function kr(t,e){return e+1<t.length&&Rr(t,e)}function Dr(t,e){if(kr(t,e)){const i=Ir(t,e);if(e+i>=t.length)return!1;const r=br(t,e);if(r<=i)return!1;const s=e+r;return s===t.length||kr(t,s)}return!1}function _r(t,e,i,r,s){if(!t.samplerate){const n=function(t,e,i,r){const s=e[i+2],n=s>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(f.ERROR,f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(s>>6&3),o=e[i+3]>>6&3|(1&s)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d=n;5!==a&&29!==a||(d-=3);const g=[a<<3|(14&d)>>1,(1&d)<<7|o<<3];return O.log(`manifest codec:${r}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:g,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:r}}(e,i,r,s);if(!n)return;R(t,n)}}function Pr(t){return 9216e4/t}function Cr(t,e,i,r,s){const n=r+s*Pr(t.samplerate),a=function(t,e){const i=Ir(t,e);if(e+i<=t.length){const r=br(t,e)-i;if(r>0)return{headerLength:i,frameLength:r}}}(e,i);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,h=Math.max(0,i+l-e.length);h?(o=new Uint8Array(l-s),o.set(e.subarray(i+s,e.length),0)):o=e.subarray(i+s,i+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function wr(t,e){return Sr(t,e)&&Ar(t,e+6)+10<=t.length-e}function Or(t,e=0,i=1/0){return function(t,e,i,r){const s=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);const a=(u=t,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0),o=(a+t.byteLength)/n,l=(a+e)/n,h=Math.floor(Math.max(0,Math.min(l,o))),d=Math.floor(Math.min(h+Math.max(i,0),o));var u;return new r(s,h,d-h)}(t,e,i,Uint8Array)}function xr(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 i=t.data.subarray(1).indexOf(0);if(-1===i)return;const r=F(Or(t.data,1,i)),s=t.data[2+i],n=t.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=F(Or(t.data,3+i,n));let o;return o="--\x3e"===r?F(Or(t.data,4+i+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+i+n)),e.mimeType=r,e.pictureType=s,e.description=a,e.data=o,e}function Mr(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=F(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=F(t.data.subarray(e),!0);e+=i.length+1;const r=F(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=F(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?xr(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=F(t.data.subarray(e),!0);e+=i.length+1;const r=F(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=F(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function Fr(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=Ar(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}const Nr=10,Ur=10;function Br(t){let e=0;const i=[];for(;Sr(t,e);){const r=Ar(t,e+6);t[e+5]>>6&1&&(e+=Nr),e+=Nr;const s=e+r;for(;e+Ur<s;){const r=Fr(t.subarray(e)),s=Mr(r);s&&i.push(s),e+=r.size+Nr}Tr(t,e)&&(e+=Nr)}return i}function Gr(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function $r(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Kr(t){const e=Br(t);for(let t=0;t<e.length;t++){const i=e[t];if(Gr(i))return $r(i)}}let Vr=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Hr(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Yr{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,i,r){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,i){}demux(t,e){this.cachedData&&(t=Tt(this.cachedData,t),this.cachedData=null);let i,r=Lr(t,0),s=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?Kr(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&l(o))&&(this.basePTS=Wr(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Vr.audioId3,duration:Number.POSITIVE_INFINITY});s<h;){if(this.canParse(t,s)){const e=this.appendFrame(n,t,s);e?(this.frameIndex++,this.lastPTS=e.sample.pts,s+=e.length,i=s):s=h}else wr(t,s)?(r=Lr(t,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Vr.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++;if(s===h&&i!==h){const e=t.slice(i);this.cachedData?this.cachedData=Tt(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:Hr(),id3Track:a,textTrack:Hr()}}demuxSampleAes(t,e,i){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:Hr(),id3Track:this._id3Track,textTrack:Hr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Wr=(t,e,i)=>{if(l(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)};let jr=null;const qr=[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],Xr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Qr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],zr=[0,1,1,4];function Zr(t,e,i,r,s){if(i+24>e.length)return;const n=Jr(e,i);if(n&&i+n.frameLength<=e.length){const a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+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 Jr(t,e){const i=t[e+1]>>3&3,r=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*qr[14*(3===i?3-r:3===r?3:4)+s-1],h=Xr[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,u=Qr[i][r],c=zr[r],f=8*u*c,g=Math.floor(u*l/h+a)*c;if(null===jr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);jr=t?parseInt(t[1]):0}return!!jr&&jr<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function ts(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function es(t,e){return e+1<t.length&&ts(t,e)}function is(t,e){if(e+1<t.length&&ts(t,e)){const i=4,r=Jr(t,e);let s=i;null!=r&&r.frameLength&&(s=r.frameLength);const n=e+s;return n===t.length||es(t,n)}return!1}const rs=(t,e)=>{let i=0,r=5;e+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],e+=1,r-=o}return i};class ss extends Yr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const r=ns(t,e,i,this.basePTS,this.frameIndex);if(-1!==r){return{sample:t.samples[t.samples.length-1],length:r,missing:0}}}static probe(t){if(!t)return!1;const e=Lr(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==Kr(e)&&rs(t,i)<16}}function ns(t,e,i,r,s){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[i+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(i+l>e.length)return-1;const h=e[i+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const u=(e[i+6]<<8|e[i+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][h]+u,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=c,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const as=/\/emsg[-/]ID3/i;function os(t,e){return l(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class ls{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ye(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Ge)}decryptAacSample(t,e,i){const r=t[e].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}))}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)i.set(t.subarray(e,e+16),r);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(i.subarray(r,r+16),e);return t}decryptAvcSample(t,e,i,r,s){const n=It(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,r)}))}decryptAvcSamples(t,e,i,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void r();const s=t[e].units;for(;!(i>=s.length);i++){const n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,r,n),this.decrypter.isSync())))return}}}}class hs{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){const t=r.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,r=i.length;if(!r)return void e.dropped++;{const e=i[r-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const r=e.byteLength;let s=t.naluState||0;const n=s,a=[];let o,l,h,d=0,u=-1,c=0;for(-1===s&&(u=0,c=this.getNALuType(e,0),s=0,d=1);d<r;)if(o=e[d++],s)if(1!==s)if(o)if(1===o){if(l=d-s-1,u>=0){const t={data:e.subarray(u,l),type:c};a.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(n&&d<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=Tt(i.data,e.subarray(0,l)),i.state=0))}d<r?(h=this.getNALuType(e,d),u=d,c=h,s=0):s=-1}else s=0;else s=3;else s=o?0:2;else s=o?0:1;if(u>=0&&s>=0){const t={data:e.subarray(u,r),type:c,state:s};a.push(t)}if(0===a.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=Tt(i.data,e))}return t.naluState=s,a}}class ds{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,i=t.byteLength-e,r=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");r.set(t.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}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 i=this.word>>>32-e;if(t>32&&O.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?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class us extends hs{parsePES(t,e,i,r){const s=this.parseNALu(t,i.data,r);let n,a=this.VideoSample,o=!1;i.data=null,a&&s.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach((r=>{var s,l;switch(r.type){case 1:{let e=!1;n=!0;const s=r.data;if(o&&s.length>4){const t=this.readSliceType(s);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Rt(r.data,1,i.pts,e.samples);break;case 7:{var d,u;n=!0,o=!0;const e=r.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(d=t.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const r=e.subarray(1,4);let s="avc1.";for(let t=0;t<3;t++){let e=r[t].toString(16);e.length<2&&(e="0"+e),s+=e}t.codec=s}break}case 8:n=!0,t.pps=[r.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,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new ds(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,r=8,s=8;for(let n=0;n<t;n++)0!==s&&(i=e.readEG(),s=(r+i+256)%256),r=0===s?r:s}readSPS(t){const e=new ds(t);let i,r,s,n=0,a=0,o=0,l=0;const h=e.readUByte.bind(e),d=e.readBits.bind(e),u=e.readUEG.bind(e),c=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=u();if(3===t&&f(1),m(),m(),f(1),c())for(r=3!==t?8:12,s=0;s<r;s++)c()&&p(s<6?16:64,e)}m();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),i=u(),s=0;s<i;s++)g();m(),f(1);const E=u(),T=u(),S=d(1);0===S&&f(1),f(1),c()&&(n=u(),a=u(),o=u(),l=u());let A=[1,1];if(c()&&c()){switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class cs extends hs{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,r){const s=this.parseNALu(t,i.data,r);let n,a=this.VideoSample,o=!1;i.data=null,a&&s.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach((r=>{var s,l;switch(r.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,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Rt(r.data,2,i.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=R(t.params,this.readVPS(r.data)),this.initVPS=r.data),t.vps=[r.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],r.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(r.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 i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,r.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(r.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,r.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,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let r=0;r<t.byteLength;r++)r>=2&&3===t[r]&&0===t[r-1]&&0===t[r-2]||(e[i]=t[r],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ds(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new ds(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const r=e.readBits(2),s=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),d=e.readUByte(),u=e.readUByte(),c=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&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,R=0,I=0,b=0;A&&(L+=e.readUEG(),R+=e.readUEG(),I+=e.readUEG(),b+=e.readUEG());const k=e.readUEG(),D=e.readUEG(),_=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let C=0;for(let t=0;t<P;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===P&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=C;t++){const t=e.readBoolean();let r=!1;t||(r=e.readBoolean()),(t||r)&&i++}C=i}else{const t=e.readUEG(),i=e.readUEG();C=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<_+4;t++)e.readBits(1);e.readBits(1)}}let w=0,O=1,x=1,M=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let U=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(O=e.readBits(16),x=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(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(),U=e.readBoolean(),U&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),r=e.readBoolean();let s=!1;(t||r)&&(s=e.readBoolean(),s&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){M=e.readBoolean();let i=!1;M||e.readBoolean()?e.readEG():i=e.readBoolean();const n=i?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),s&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(r)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),s&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),w=e.readUEG())}let B=T,G=S;if(A){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),B=T-t*R-t*L,G=S-e*b-e*I}const $=r?["A","B","C"][r]:"",K=a<<24|o<<16|l<<8|h;let V=0;for(let t=0;t<32;t++)V=(V|(K>>t&1)<<31-t)>>>0;let H=V.toString(16);1===n&&"2"===H&&(H="6");return{codecString:`hvc1.${$}${n}.${H}.${s?"H":"L"}${p}.B0`,params:{general_tier_flag:s,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,u,c,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:w,chroma_format_idc:E,frame_rate:{fixed:M,fps:N/F}},width:B,height:G,pixelRatio:[O,x]}}readPPS(t){const e=new ds(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 i=e.readBoolean(),r=e.readBoolean();let s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const fs=188;class gs{constructor(t,e,i,r){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=i,this.logger=r,this.videoParser=null}static probe(t,e){const i=gs.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-fs)+1,r=0;for(;r<i;){let s=!1,n=-1,a=0;for(let o=r;o<e;o+=fs){if(71!==t[o]||e-o!==fs&&71!==t[o+fs]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-fs)+1)),s||(s=0===ms(t,o)),s&&a>1&&(0===n&&a>2||o+fs>i))return n}r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:nt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=gs.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=gs.createTrack("audio",r),this._id3Track=gs.createTrack("id3"),this._txtTrack=gs.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i=!1,r=!1){let s;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,u=a.pid,c=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=Tt(this.remainderData,t)).length,this.remainderData=null),y<fs&&!r)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,gs.syncOffset(t));y-=(y-E)%fs,y<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=E;e<y;e+=fs)if(71===t[e]){const r=!!(64&t[e+1]),y=ms(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+fs)continue}else T=e+4;switch(y){case h:r&&(d&&(s=Ts(d,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,s,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(T,e+fs)),d.size+=e+fs-T);break;case u:if(r){if(f&&(s=Ts(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+fs)),f.size+=e+fs-T);break;case c:r&&(g&&(s=Ts(g,this.logger))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+fs)),g.size+=e+fs-T);break;case 0:r&&(T+=t[T]+1),v=this._pmtId=ps(t,T);break;case v:{r&&(T+=t[T]+1);const s=vs(t,T,this.typeSupported,i,this.observer,this.logger);h=s.videoPid,h>0&&(n.pid=h,n.segmentCodec=s.segmentVideoCodec),u=s.audioPid,u>0&&(a.pid=u,a.segmentCodec=s.segmentAudioCodec),c=s.id3Pid,c>0&&(o.pid=c),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&ys(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}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:i,id3Track:r,textTrack:s}=t,n=i.pesData,a=e.pesData,o=r.pesData;let l;if(n&&(l=Ts(n,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,s,l,!0),i.pesData=null)):i.pesData=n,a&&(l=Ts(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=Ts(o,this.logger))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(t,e,i){const r=this.demux(t,i,!0,!this.config.progressive),s=this.sampleAes=new ls(this.observer,this.config,e);return this.decrypt(r,s)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new us:"hevc"===t&&(this.videoParser=new cs))}decrypt(t,e){return new Promise((i=>{const{audioTrack:r,videoTrack:s}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,(()=>{s.samples?e.decryptAvcSamples(s.samples,0,0,(()=>{i(t)})):i(t)})):s.samples&&e.decryptAvcSamples(s.samples,0,0,(()=>{i(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 i=0;const r=this.aacOverFlow;let s,n,a,o=e.data;if(r){this.aacOverFlow=null;const e=r.missing,s=r.sample.unit.byteLength;if(-1===e)o=Tt(r.sample.unit,o);else{const n=s-e;r.sample.unit.set(o.subarray(0,e),n),t.samples.push(r.sample),i=r.missing}}for(s=i,n=o.length;s<n-1&&!kr(o,s);s++);if(s!==i){let t;const e=s<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",ys(this.observer,new Error(t),e,this.logger),!e)return}if(_r(t,this.observer,o,s,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Pr(t.samplerate);a=r.sample.pts+e}}let l,h=0;for(;s<n;){if(l=Cr(t,o,s,a,h),s+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;s<n-1&&!kr(o,s);s++);}}parseMPEGPES(t,e){const i=e.data,r=i.length;let s=0,n=0;const a=e.pts;if(void 0!==a)for(;n<r;)if(es(i,n)){const e=Zr(t,i,n,a,s);if(!e)break;n+=e.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,r=e.pts;if(void 0===r)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const s=i.length;let n,a=0,o=0;for(;o<s&&(n=ns(t,i,o,r,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=R({},e,{type:this._videoTrack?Vr.emsg:Vr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function ms(t,e){return((31&t[e+1])<<8)+t[e+2]}function ps(t,e){return(31&t[e+10])<<8|t[e+11]}function vs(t,e,i,r,s,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=ms(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){Es("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(!r){Es("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){Es("AC-3",n);break}case 129:i.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 r=e+5,s=l;for(;s>2;){if(106===t[r])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[r+1]+2;r+=e,s-=e}}break;case 194:case 135:return ys(s,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 ys(t,e,i,r){r.warn(`parsing error: ${e.message}`),t.emit(f.ERROR,f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function Es(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ts(t,e){let i,r,s,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]=Tt(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(r=(i[4]<<8)+i[5],r&&r>t.size-6)return null;const h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=i[8];let d=s+9;if(t.size<=d)return null;t.size-=d;const u=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(d){if(d>e){d-=e;continue}i=i.subarray(d),e-=d,d=0}u.set(i,o),o+=e}return r&&(r-=s+3),{data:u,pts:n,dts:a,len:r}}return null}class Ss{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])}}}const As=Math.pow(2,32)-1;class Ls{static init(){let t;for(t in Ls.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:[]},Ls.types)Ls.types.hasOwnProperty(t)&&(Ls.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]),i=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]);Ls.HDLR_TYPES={video:e,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Ls.STTS=Ls.STSC=Ls.STCO=s,Ls.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ls.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ls.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ls.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Ls.FTYP=Ls.box(Ls.types.ftyp,n,o,n,a),Ls.DINF=Ls.box(Ls.types.dinf,Ls.box(Ls.types.dref,r))}static box(t,...e){let i=8,r=e.length;const s=r;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}static hdlr(t){return Ls.box(Ls.types.hdlr,Ls.HDLR_TYPES[t])}static mdat(t){return Ls.box(Ls.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(As+1)),r=Math.floor(e%(As+1));return Ls.box(Ls.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,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(t){return Ls.box(Ls.types.mdia,Ls.mdhd(t.timescale||0,t.duration||0),Ls.hdlr(t.type),Ls.minf(t))}static mfhd(t){return Ls.box(Ls.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Ls.box(Ls.types.minf,Ls.box(Ls.types.smhd,Ls.SMHD),Ls.DINF,Ls.stbl(t)):Ls.box(Ls.types.minf,Ls.box(Ls.types.vmhd,Ls.VMHD),Ls.DINF,Ls.stbl(t))}static moof(t,e,i){return Ls.box(Ls.types.moof,Ls.mfhd(t),Ls.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Ls.trak(t[e]);return Ls.box.apply(null,[Ls.types.moov,Ls.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Ls.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Ls.trex(t[e]);return Ls.box.apply(null,[Ls.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(As+1)),r=Math.floor(e%(As+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,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 Ls.box(Ls.types.mvhd,s)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let r,s;for(r=0;r<e.length;r++)s=e[r].flags,i[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return Ls.box(Ls.types.sdtp,i)}static stbl(t){return Ls.box(Ls.types.stbl,Ls.stsd(t),Ls.box(Ls.types.stts,Ls.STTS),Ls.box(Ls.types.stsc,Ls.STSC),Ls.box(Ls.types.stsz,Ls.STSZ),Ls.box(Ls.types.stco,Ls.STCO))}static avc1(t){let e,i,r,s=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],r=i.byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));const a=Ls.box(Ls.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return Ls.box(Ls.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Ls.box(Ls.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ls.box(Ls.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}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(t){return Ls.box(Ls.types.mp4a,Ls.audioStsd(t),Ls.box(Ls.types.esds,Ls.esds(t)))}static mp3(t){return Ls.box(Ls.types[".mp3"],Ls.audioStsd(t))}static ac3(t){return Ls.box(Ls.types["ac-3"],Ls.audioStsd(t),Ls.box(Ls.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Ls.box(Ls.types.stsd,Ls.STSD,Ls.mp4a(t));if("ac3"===e&&t.config)return Ls.box(Ls.types.stsd,Ls.STSD,Ls.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Ls.box(Ls.types.stsd,Ls.STSD,Ls.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Ls.box(Ls.types.stsd,Ls.STSD,Ls.avc1(t));if("hevc"===e&&t.vps)return Ls.box(Ls.types.stsd,Ls.STSD,Ls.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),r=t.width||0,s=t.height||0,n=Math.floor(i/(As+1)),a=Math.floor(i%(As+1));return Ls.box(Ls.types.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,s>>8&255,255&s,0,0]))}static traf(t,e){const i=Ls.sdtp(t),r=t.id,s=Math.floor(e/(As+1)),n=Math.floor(e%(As+1));return Ls.box(Ls.types.traf,Ls.box(Ls.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Ls.box(Ls.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),Ls.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Ls.box(Ls.types.trak,Ls.tkhd(t),Ls.mdia(t))}static trex(t){const e=t.id;return Ls.box(Ls.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],r=i.length,s=12+16*r,n=new Uint8Array(s);let a,o,l,h,d,u;for(e+=8+s,n.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<r;a++)o=i[a],l=o.duration,h=o.size,d=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Ls.box(Ls.types.trun,n)}static initSegment(t){Ls.types||Ls.init();const e=Ls.moov(t);return Tt(Ls.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],r=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let s=r.length;for(let t=0;t<i.length;t+=1){s+=3;for(let e=0;e<i[t].length;e+=1)s+=2+i[t][e].length}const n=new Uint8Array(s);n.set(r,0),s=r.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),s),s+=3;for(let e=0;e<i[t].length;e+=1)n.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),s),s+=2,n.set(i[t][e],s),s+=i[t][e].length}const o=Ls.box(Ls.types.hvcC,n),l=t.width,h=t.height,d=t.pixelRatio[0],u=t.pixelRatio[1];return Ls.box(Ls.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,l>>8&255,255&l,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]),o,Ls.box(Ls.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ls.box(Ls.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))}}Ls.types=void 0,Ls.HDLR_TYPES=void 0,Ls.STTS=void 0,Ls.STSC=void 0,Ls.STCO=void 0,Ls.STSZ=void 0,Ls.VMHD=void 0,Ls.SMHD=void 0,Ls.STSD=void 0,Ls.FTYP=void 0,Ls.DINF=void 0;const Rs=9e4;function Is(t,e,i=1,r=!1){const s=t*e*i;return r?Math.round(s):s}function bs(t,e=!1){return Is(t,1e3,1/Rs,e)}let ks,Ds=null,_s=null;function Ps(t,e,i,r){return{duration:e,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class Cs extends k{constructor(t,e,i,r){if(super("mp4-remuxer",r),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=i,this.ISGenerated=!1,null===Ds){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ds=t?parseInt(t[1]):0}if(null===_s){const t=navigator.userAgent.match(/Safari\/(\d+)/i);_s=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){this.log("initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t[0].pts,r=t.reduce(((t,r)=>{let s=r.pts,n=s-t;return n<-4294967296&&(e=!0,s=ws(s,i),n=s-t),n>0?t:s}),i);return e&&this.debug("PTS rollover detected"),r}remux(t,e,i,r,s,n,a,o){let l,h,d,u,c,f,g=s,m=s;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,T=t.samples.length>0,S=a&&y>0||y>1;if((!p||T)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var A,L,R,I;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(A=e.pixelRatio)?void 0:A[0])!==(null==(L=t.pixelRatio)?void 0:L[0])||(null==(R=e.pixelRatio)?void 0:R[1])!==(null==(I=t.pixelRatio)?void 0:I[1]))||!t&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(t,e,s,n));const i=this.isVideoContiguous;let r,a=-1;if(S&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&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,r=m}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const i=this.getVideoStartPts(e.samples),r=(ws(t.samples[0].pts,i)-i)/e.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(T){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(t,e,s,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||S||o===E?m:void 0),S){const r=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(t,e,s,n)),l=this.remuxVideo(e,m,i,r)}}else S&&(l=this.remuxVideo(e,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=Os(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=xs(r,s,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:u,id3:c}}generateIS(t,e,i,r){const s=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,u,c=!l||r,f="audio/mp4",g=-1;if(c&&(h=d=1/0),t.config&&s.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):Ls.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(g=t.id,u=t.inputTimeScale,l&&u===l.timescale?c=!1:h=d=s[0].pts-Math.round(u*i))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Ls.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(g=e.id,u=e.inputTimeScale,l&&u===l.timescale)c=!1;else{const t=this.getVideoStartPts(n),e=Math.round(u*i);d=Math.min(d,ws(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,c?(l&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${h/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/u} (${h}/${u}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:u,trackId:g},this._initDTS={baseTime:d,timescale:u,trackId:g}):h=u=void 0,{tracks:o,initPTS:h,timescale:u,trackId:g}}remuxVideo(t,e,i,r){const s=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS,h=l.baseTime*s/l.timescale;let d,g,m=this.nextVideoTs,p=8,v=this.videoSampleDuration,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!i||null===m){const t=h+e*s,r=n[0].pts-ws(n[0].dts,n[0].pts);Ds&&null!==m&&Math.abs(t-r-(m+h))<15e3?i=!0:m=t-r-h}const S=m+h;for(let t=0;t<o;t++){const e=n[t];e.pts=ws(e.pts,S),e.dts=ws(e.dts,S),e.dts<n[t>0?t-1:t].dts&&(T=!0)}T&&n.sort((function(t,e){const i=t.dts-e.dts,r=t.pts-e.pts;return i||r})),d=n[0].dts,g=n[n.length-1].dts;const A=g-d,L=A?Math.round(A/(o-1)):v||t.inputTimeScale/30;if(i){const i=d-S,r=i>L,s=i<-1;if((r||s)&&(r?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${bs(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${bs(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!s||S>=n[0].pts||Ds)){d=S;const t=n[0].pts-i;if(r)n[0].dts=d,n[0].pts=t;else{let e=!0;for(let r=0;r<n.length&&!(n[r].dts>t&&e);r++){const t=n[r].pts;if(n[r].dts-=i,n[r].pts-=i,r<n.length-1){const i=n[r+1].pts;e=i<=n[r].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${bs(t,!0)}/${bs(d,!0)}, delta: ${bs(i,!0)} ms`)}}d=Math.max(0,d);let I=0,b=0,k=d;for(let t=0;t<o;t++){const e=n[t],i=e.units,r=i.length;let s=0;for(let t=0;t<r;t++)s+=i[t].data.length;b+=s,I+=r,e.length=s,e.dts<k?(e.dts=k,k+=L/4|0||1):k=e.dts,y=Math.min(e.pts,y),E=Math.max(e.pts,E)}g=n[o-1].dts;const D=b+4*I+8;let _;try{_=new Uint8Array(D)}catch(t){return void this.observer.emit(f.ERROR,f.ERROR,{type:u.MUX_ERROR,details:c.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:D,reason:`fail allocating video mdat ${D}`})}const P=new DataView(_.buffer);P.setUint32(0,D),_.set(Ls.types.mdat,4);let C=!1,w=Number.POSITIVE_INFINITY,O=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=n[t],i=e.units;let l,d=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],r=e.data,s=e.data.byteLength;P.setUint32(p,s),p+=4,_.set(r,p),p+=s,d+=4+s}if(t<o-1)v=n[t+1].dts-e.dts,l=n[t+1].pts-e.pts;else{const i=this.config,a=t>0?e.dts-n[t-1].dts:L;if(l=t>0?e.pts-n[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*s),n=(r?y+r*s:this.nextAudioTs+h)-e.pts;n>t?(v=n-a,v<0?v=a:C=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=a}else v=a}const u=Math.round(e.pts-e.dts);w=Math.min(w,v),x=Math.max(x,v),O=Math.min(O,l),M=Math.max(M,l),a.push(Ps(e.key,v,d,u))}if(a.length)if(Ds){if(Ds<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(_s&&M-O<x-w&&L/x<.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=d;for(let e=0,i=a.length;e<i;e++){const r=t+a[e].duration,s=t+a[e].cts;if(e<i-1){const t=r+a[e+1].cts;a[e].duration=t-s}else a[e].duration=e?a[e-1].duration:L;a[e].cts=0,t=r}}v=C||!v?L:v;const F=g+v;this.nextVideoTs=m=F-h,this.videoSampleDuration=v,this.isVideoContiguous=!0;const N={data1:Ls.moof(t.sequenceNumber++,d,R(t,{samples:a})),data2:_,startPTS:(y-h)/s,endPTS:(E+v-h)/s,startDTS:(d-h)/s,endDTS:m/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,r,s){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,h=this._initPTS,d="mp3"===t.segmentCodec&&this.typeSupported.mpeg,g=[],m=void 0!==s;let p=t.samples,v=d?0:8,y=this.nextAudioTs||-1;const E=h.baseTime*n/h.timescale,T=E+e*n;if(this.isAudioContiguous=i=i||p.length&&y>0&&(r&&Math.abs(T-(y+E))<9e3||Math.abs(ws(p[0].pts,T)-(y+E))<20*l),p.forEach((function(t){t.pts=ws(t.pts,T)})),!i||y<0){if(p=p.filter((t=>t.pts>=0)),!p.length)return;y=0===s?0:r&&!m?Math.max(0,T-E):p[0].pts-E}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,r=y+E;i<p.length;i++){const s=p[i],a=s.pts,o=a-r,h=Math.abs(1e3*o/n);if(o<=-e*l&&m)0===i&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=y=a-E,r=a);else if(o>=e*l&&h<1e4&&m){let e=Math.round(o/l);for(r=a-e*l;r<0&&e&&l;)e--,r+=l;0===i&&(this.nextAudioTs=y=r-E),this.warn(`Injecting ${e} audio frames @ ${((r-E)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){let e=Ss.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=s.unit.subarray()),p.splice(i,0,{unit:e,pts:r}),r+=l,i++}}s.pts=r,r+=l}}let S,A=null,L=null,I=0,b=p.length;for(;b--;)I+=p[b].unit.byteLength;for(let e=0,r=p.length;e<r;e++){const r=p[e],s=r.unit;let n=r.pts;if(null!==L){g[e-1].duration=Math.round((n-L)/a)}else{if(i&&"aac"===t.segmentCodec&&(n=y+E),A=n,!(I>0))return;I+=v;try{S=new Uint8Array(I)}catch(t){return void this.observer.emit(f.ERROR,f.ERROR,{type:u.MUX_ERROR,details:c.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:I,reason:`fail allocating audio mdat ${I}`})}if(!d){new DataView(S.buffer).setUint32(0,I),S.set(Ls.types.mdat,4)}}S.set(s,v);const l=s.byteLength;v+=l,g.push(Ps(!0,o,l,0)),L=n}const k=g.length;if(!k)return;const D=g[g.length-1];y=L-E,this.nextAudioTs=y+a*D.duration;const _=d?new Uint8Array(0):Ls.moof(t.sequenceNumber++,A/a,R({},t,{samples:g}));t.samples=[];const P=(A-E)/n,C=y/n,w={data1:_,data2:S,startPTS:P,endPTS:C,startDTS:P,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,w}}function ws(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function Os(t,e,i,r){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let a=0;a<s;a++){const s=t.samples[a];s.pts=ws(s.pts-i.baseTime*n/i.timescale,e*n)/n,s.dts=ws(s.dts-r.baseTime*n/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function xs(t,e,i){const r=t.samples.length;if(!r)return;const s=t.inputTimeScale;for(let n=0;n<r;n++){const r=t.samples[n];r.pts=ws(r.pts-i.baseTime*s/i.timescale,e*s)/s}t.samples.sort(((t,e)=>t.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}function Ms(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Fs(t,e,i){const r=t.codec;if(r&&r.length>4)return r;if(e===X){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r){return Nt(r,!1)}return i.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"}return i.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1"}try{ks=self.performance.now.bind(self.performance)}catch(t){ks=Date.now}const Ns=[{demux: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,i,r){const s=this.videoTrack=Hr("video",1),n=this.audioTrack=Hr("audio",1),a=this.txtTrack=Hr("text",1);if(this.id3Track=Hr("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=ft(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:r}=o.video;s.id=t,s.timescale=a.timescale=e,s.codec=i,s.supplemental=r}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=nt.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const r=lt(t,i);if(r>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=r>1?i+r:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Tt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=ut(t,["moof"]);if(i.length<2)return e.remainder=t,e;const r=i[i.length-1];return e.valid=t.slice(0,r.byteOffset-8),e.remainder=t.slice(r.byteOffset-8),e}(i);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=i;const n=this.extractID3Track(r,e);return s.samples=St(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(e,this.timeOffset);return i.samples=St(t,e),{videoTrack:e,audioTrack:Hr(),id3Track:r,textTrack:Hr()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const r=ut(t.samples,["emsg"]);r&&r.forEach((t=>{const r=function(t){const e=t[0];let i="",r="",s=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==at(t.subarray(d,d+1));)i+=at(t.subarray(d,d+1)),d+=1;for(i+=at(t.subarray(d,d+1)),d+=1;"\0"!==at(t.subarray(d,d+1));)r+=at(t.subarray(d,d+1)),d+=1;r+=at(t.subarray(d,d+1)),d+=1,s=lt(t,12),n=lt(t,16),o=lt(t,20),l=lt(t,24),d=28}else if(1===e){d+=4,s=lt(t,d),d+=4;const e=lt(t,d);d+=4;const n=lt(t,d);for(d+=4,a=2**32*e+n,h(a)||(a=Number.MAX_SAFE_INTEGER,O.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=lt(t,d),d+=4,l=lt(t,d),d+=4;"\0"!==at(t.subarray(d,d+1));)i+=at(t.subarray(d,d+1)),d+=1;for(i+=at(t.subarray(d,d+1)),d+=1;"\0"!==at(t.subarray(d,d+1));)r+=at(t.subarray(d,d+1)),d+=1;r+=at(t.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(as.test(r.schemeIdUri)){const t=os(r,e);let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Vr.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=os(r,e);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:t,pts:t,type:Vr.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends k{constructor(t,e,i,r){super("passthrough-remuxer",r),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,i,r){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,r),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:s,video:n}=this.initData=ft(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;i&&e.isCommonEncryption&&ut(t,["moov","trak"]).forEach((t=>{const e=ut(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=ut(e,["enca"]);const s=r.length>0;s||(r=ut(e,["encv"])),r.forEach((t=>{ut(s?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=Et(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(O.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${N(t)} -> ${N(i)}`),e.set(i,8))}}))}))}))}(t,e);else{const t=s||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}s&&(i=Fs(s,X,this)),n&&(r=Fs(n,Q,this));const a={};s&&n?a.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:s?a.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:r,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,i,r,s,n){var a,o;let{initPTS:h,lastEndTime:d}=this;const u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};l(d)||(d=this.lastEndTime=s||0);const c=e.samples;if(!c.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if(null!=(a=g)&&a.length||(this.generateInitSegment(c),g=this.initData),null==(o=g)||!o.length)return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e,i){const r={},s=ut(t,["moof","traf"]);for(let t=0;t<s.length;t++){const n=s[t],a=ut(n,["tfhd"])[0],o=lt(a,4),h=e[o];if(!h)continue;r[o]||(r[o]={start:NaN,duration:0,sampleCount:0,timescale:h.timescale,type:h.type});const d=r[o],u=ut(n,["tfdt"])[0];if(u){const t=u[0];let e=lt(u,4);1===t&&(e===rt?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=rt+1,e+=lt(u,8))),l(e)&&(!l(d.start)||e<d.start)&&(d.start=e)}const c=h.default,f=lt(a,0)|(null==c?void 0:c.flags);let g=(null==c?void 0:c.duration)||0;8&f&&(g=lt(a,2&f?12:8));const m=ut(n,["trun"]);let p=d.start||0,v=0,y=g;for(let t=0;t<m.length;t++){const e=m[t],i=lt(e,4),r=d.sampleCount;d.sampleCount+=i;const s=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],h=8&e[2];let u=8,c=i;for(s&&(u+=4),n&&i&&(1&e[u+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=r),u+=4,a?(y=lt(e,u),u+=4):y=g,o&&(u+=4),h&&(u+=4),p+=y,v+=y,c--);c--;)a?(y=lt(e,u),u+=4):y=g,o&&(u+=4),l&&(1&e[u+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(c+1),d.keyFrameStart=p),u+=4),h&&(u+=4),p+=y,v+=y;!v&&g&&(v+=g*i)}d.duration+=v}if(!Object.keys(r).some((t=>r[t].duration))){let e=1/0,i=0;const s=ut(t,["sidx"]);for(let t=0;t<s.length;t++){const r=ct(s[t]);if(null!=r&&r.references){e=Math.min(e,r.earliestPresentationTime/r.timescale);const t=r.references.reduce(((t,e)=>t+e.info.duration||0),0);i=Math.max(i,t+r.earliestPresentationTime/r.timescale)}}i&&l(i)&&Object.keys(r).forEach((t=>{r[t].duration||(r[t].duration=i*r[t].timescale-r[t].start)}))}return r}(c,g,this),p=g.audio?m[g.audio.id]:null,v=g.video?m[g.video.id]:null,y=Ms(v,1/0),E=Ms(p,1/0),T=Ms(v,0,!0),S=Ms(p,0,!0);let A=s,L=0;const R=p&&(!v||!h&&E<y||h&&h.trackId===g.audio.id),I=R?p:v;if(I){const t=I.timescale,e=I.start-s*t,i=R?g.audio.id:g.video.id;A=I.start/t,L=R?S-E:T-y,!n&&h||!function(t,e,i,r){if(null===t)return!0;const s=Math.max(r,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>s}(h,A,s,L)&&t===h.timescale||(h&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${s} ${e/t} != initPTS: ${h.baseTime/h.timescale} (${h.baseTime}/${h.timescale}) trackId: ${h.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${A-s} (${e}/${t}) trackId: ${i}`),h=null,f.initPTS=e,f.timescale=t,f.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${s}`);h?(f.initPTS=h.baseTime,f.timescale=h.timescale,f.trackId=h.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=A,f.timescale=1,f.trackId=-1),this.initPTS=h={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const b=A-h.baseTime/h.timescale,k=b+L;L>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const D=!!g.audio,_=!!g.video;let P="";D&&(P+="audio"),_&&(P+="video");const C={data1:c,startPTS:b,startDTS:b,endPTS:k,endDTS:k,type:P,hasAudio:D,hasVideo:_,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};u.audio=D&&!_?C:void 0,u.video=_?C:void 0;const w=null==v?void 0:v.sampleCount;if(w){const t=v.keyFrameIndex,e=-1!==t;C.nb=w,C.dropped=0===t||this.isVideoContiguous?0:e?t:w,C.independent=e,C.firstKeyFrame=t,e&&v.keyFrameStart&&(C.firstKeyFramePTS=(v.keyFrameStart-h.baseTime)/h.timescale),this.isVideoContiguous||(u.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),C.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${w} dropped: ${C.dropped} start: ${C.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=Os(i,s,h,h),r.samples.length&&(u.text=xs(r,s,h)),u}}},{demux:gs,remux:Cs},{demux:class extends Yr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=Lr(t,0);let r=(null==i?void 0:i.length)||0;if(is(t,r))return!1;for(let i=t.length;r<i;r++)if(Dr(t,r))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)&&Rr(t,e)&&br(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){_r(t,this.observer,e,i,t.manifestCodec);const r=Cr(t,e,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:Cs},{demux:class extends Yr{resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Lr(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==Kr(e)&&rs(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(is(t,i))return O.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return ts(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return Zr(t,e,i,this.basePTS,this.frameIndex)}},remux:Cs}];Ns.splice(2,0,{demux:ss,remux:Cs});class Us{constructor(t,e,i,r,s,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=i,this.id=s,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,r){const s=i.transmuxing;s.executeStart=ks();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=r||a,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=o,A=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(n,e);if(A&&ci(A.method)){const t=this.getDecrypter(),e=fi(A.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer,e).then((t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e})),this.decryptionPromise;{let r=t.softwareDecrypt(n,A.key.buffer,A.iv.buffer,e);if(i.part>-1){const e=t.flush();r=e?e.buffer:e}if(!r)return s.executeEnd=ks(),Bs(i);n=new Uint8Array(r)}}const L=this.needsProbing(h,d);if(L){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(f.ERROR,f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),s.executeEnd=ks(),Bs(i)}(h||d||p||L)&&this.resetInitSegment(S,v,y,T,e),(h||p||L)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const R=this.transmux(n,A,m,g,i);this.asyncResult=Gs(R);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,s.executeEnd=ks(),R}flush(t){const e=t.transmuxing;e.executeStart=ks();const{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then((()=>this.flush(t)));const n=[],{timeOffset:a}=r;if(i){const e=i.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=ks();const i=[Bs(t)];return this.asyncResult?Promise.resolve(i):i}const h=o.flush(a);return Gs(h)?(this.asyncResult=!0,h.then((e=>(this.flushRemux(n,e,t),n)))):(this.flushRemux(n,h,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,i){const{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===y?"level":"track"} ${i.level}`);const h=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=ks()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,r,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,i,r),a.resetInitSegment(t,e,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,r,s){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,r,s):this.transmuxUnencrypted(t,i,r,s),n}transmuxUnencrypted(t,e,i,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,e,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,i,r,s){return this.demuxer.demuxSampleAes(t,e,i).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:r}=this;let s;for(let e=0,i=Ns.length;e<i;e++){var n;if(null!=(n=Ns[e].demux)&&n.probe(t,this.logger)){s=Ns[e];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=s.remux,h=s.demux;o&&o instanceof l||(this.remuxer=new l(i,e,r,this.logger)),a&&a instanceof h||(this.demuxer=new h(i,e,r,this.logger),this.probe=h.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Ye(this.config)),t}}const Bs=t=>({remuxResult:{},chunkMeta:t});function Gs(t){return"then"in t&&t.then instanceof Function}class $s{constructor(t,e,i,r,s){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=i,this.duration=r,this.defaultInitPts=s||null}}class Ks{constructor(t,e,i,r,s,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=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}}let Vs=0;class Hs{constructor(t,e,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Vs++,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,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var r;const t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.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,i.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(f.ERROR,{type:u.OTHER_ERROR,details:c.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const s=t.config;this.hls=t,this.id=e,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===f.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new vr,this.observer.on(f.FRAG_DECRYPTED,n),this.observer.on(f.ERROR,n);const a=$t(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(i.log(`loading Web Worker ${s.workerPath} for "${e}"`),this.workerContext=function(t){const e=Er[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Er[t]=r,r}(s.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Er[yr];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"}),i=self.URL.createObjectURL(e),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return Er[yr]=r,r}());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:ne(s)})}catch(r){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new Us(this.observer,a,s,"",e,t.logger)}return}}this.transmuxer=new Us(this.observer,a,s,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Vs++;const e=this.hls.config,i=$t(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:ne(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=Er[t||yr];if(e&&1==e.clientCount--){const{worker:i,objectURL:r}=e;delete Er[t||yr],r&&self.URL.revokeObjectURL(r),i.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,i,r,s,n,a,o,l,h){var d,u;l.transmuxing.start=self.performance.now();const{instanceNo:c,transmuxer:f}=this,g=n?n.start:s.start,m=s.decryptdata,p=this.frag,v=!(p&&s.cc===p.cc),E=!(p&&l.level===p.level),T=p?l.sn-p.sn:-1,S=this.part?l.part-this.part.index:-1,A=0===T&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!E&&(1===T||0===T&&(1===S||A&&S<=0)),R=self.performance.now();(E||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=R),!n||!S&&L||(n.stats.parsing.start=R);const I=!(p&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=p.initSegment)?void 0:u.url)),b=new Ks(v,L,o,E,g,I);if(!L||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===y?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${E}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const t=new $s(i,r,e,a,h);this.configureTransmuxer(t)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,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);Gs(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:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);Gs(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,i){this.hls&&(this.error=t,this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class Ys 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,i){const r=null==e?void 0:e.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){const n=r[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){s=i;break}a===t.substring(0,a.length)&&(s=i)}if(-1!==s){const t=r[s],n=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=i&&te(i);return new ee(n,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(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:r,stats:s}=e,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;r.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){const t=Math.max(o||0,0);r.appliedTimelineOffset=t,r.fragments.forEach((e=>{e.setStart(e.playlistOffset+t)}))}if(r.live||null!=i&&i.live){const o="levelInfo"in e?e.levelInfo:e.track;if(r.reloaded(i),i&&r.fragments.length>0){Xi(i,r,this);const t=r.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=e;return void i.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(l=r.fragments[0])?void 0:l.type,networkDetails:n,stats:s})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,g=Ji(r,1e3*(r.edge-d));if(r.requestScheduled+g<n?r.requestScheduled=n:r.requestScheduled+=g,this.log(`live playlist ${t} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let m,p,v;if(r.canBlockReload&&r.endSN&&r.advanced){const t=this.hls.config.lowLatencyMode,s=r.lastPartSn,a=r.endSN,l=r.lastPartIndex,h=s===a;-1!==l?h?(p=a+1,v=t?0:l):(p=s,v=t?l+1:r.maxPartIndex):p=a+1;const d=r.age,u=d+r.ageHeader;let c=Math.min(u-r.partTarget,1.5*r.targetduration);if(c>0){if(u>3*r.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=i&&i.tuneInGoal&&u-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${c} with playlist age: ${r.age}`),c=0;else{const t=Math.floor(c/r.targetduration);if(p+=t,void 0!==v){v+=Math.round(c%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${c} skip sn ${t} to part ${v}`)}r.tuneInGoal=c}if(m=this.getDeliveryDirectives(r,e.deliveryDirectives,p,v),t||!h)return r.requestScheduled=n,void this.loadingPlaylist(o,m)}else(r.canBlockReload||r.canSkipUntil)&&(m=this.getDeliveryDirectives(r,e.deliveryDirectives,p,v));m&&void 0!==p&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(g-2*a,g/2)),this.scheduleLoading(o,m,r)}else this.clearTimer()}scheduleLoading(t,e,i){const r=i||t.details;if(!r)return void this.loadingPlaylist(t,e);const s=self.performance.now(),n=r.requestScheduled;if(s>=n)return void this.loadingPlaylist(t,e);const a=n-s;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,i,r){let s=te(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,r=e.part,s=zt),new ee(i,r,s)}checkRetry(t){const e=t.details,i=Ee(t),r=t.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===ke||!r.resolved&&s===Ie);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&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=Se(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,r.resolved=!0}return o}}function Ws(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!js(t[i].attrs,e[i].attrs))return!1;return!0}function js(t,e,i){const r=t["STABLE-RENDITION-ID"];return r&&!i?r===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i=>t[i]!==e[i]))}function qs(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class Xs{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const r=this.queues[e];r.push(t),1!==r.length||i||this.executeNext(e)}appendBlocker(t){return new Promise((e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)}))}prependBlocker(t){return new Promise((e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(t[0].execute(),t.splice(0,1))}))}unblockAudio(t){if(null===this.queues)return;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(e){var i;if(r.onError(e),null===this.queues||null===this.tracks)return;const s=null==(i=this.tracks[t])?void 0:i.buffer;null!=s&&s.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,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],r=null==i?void 0:i.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map((t=>t.label)).join(", "))||""}}const Qs=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,zs="HlsJsTrackRemovedError";class Zs extends Error{constructor(t){super(t),this.name=zs}}function Js(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}function tn(t){return"audio"===t?1:0}class en{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(f.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(f.MANIFEST_PARSED,this.onManifestParsed,this),t.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(f.BUFFER_CODECS,this.onBufferCodecs,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(f.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(f.MANIFEST_PARSED,this.onManifestParsed,this),t.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(f.BUFFER_CODECS,this.onBufferCodecs,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.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 i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&l(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,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter(((e,i)=>this.isLevelAllowed(e)&&i<=t));return this.clientRect=null,en.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 i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.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(t){}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,i){if(null==t||!t.length)return-1;let r=t.length-1;const s=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=s||i.height>=s)&&(n=i,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){r=e;break}}var n,a;return r}}const rn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},sn={HLS:"h"};class nn{constructor(t,e){Array.isArray(t)&&(t=t.map((t=>t instanceof nn?t:new nn(t)))),this.value=t,this.params=e}}const an="Dict";function on(t,e,i,r){return new Error(`failed to ${t} "${s=e,Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s)}" as ${i}`,{cause:r});var s}function ln(t,e,i){return on("serialize",t,e,i)}class hn{constructor(t){this.description=t}}const dn="Bare Item",un="Boolean";const cn="Byte Sequence";function fn(t){if(!1===ArrayBuffer.isView(t))throw ln(t,cn);return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}const gn="Integer";function mn(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw ln(t,gn);return t.toString()}function pn(t,e){if(t<0)return-pn(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}const vn="Decimal";function yn(t){const e=pn(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ln(t,vn);const i=e.toString();return i.includes(".")?i:`${i}.0`}const En="String",Tn=/[\x00-\x1f\x7f]+/;const Sn="Token";function An(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw ln(e,Sn);return e}function Ln(t){switch(typeof t){case"number":if(!l(t))throw ln(t,dn);return Number.isInteger(t)?mn(t):yn(t);case"string":return function(t){if(Tn.test(t))throw ln(t,En);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return An(t);case"boolean":return function(t){if("boolean"!=typeof t)throw ln(t,un);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${mn(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return fn(t);if(t instanceof hn)return An(t);default:throw ln(t,dn)}}const Rn="Key";function In(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw ln(t,Rn);return t}function bn(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${In(t)}`:`;${In(t)}=${Ln(e)}`)).join("")}function kn(t){return t instanceof nn?`${Ln(t.value)}${bn(t.params)}`:Ln(t)}function Dn(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw ln(t,an);const i=t instanceof Map?t.entries():Object.entries(t),r=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map((([t,e])=>{e instanceof nn==!1&&(e=new nn(e));let i=In(t);var r;return!0===e.value?i+=bn(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(r=e).value.map(kn).join(" ")})${bn(r.params)}`:i+=kn(e)),i})).join(`,${r}`)}function _n(t,e){return Dn(t,e)}const Pn="CMCD-Object",Cn="CMCD-Request",wn="CMCD-Session",On="CMCD-Status",xn={br:Pn,ab:Pn,d:Pn,ot:Pn,tb:Pn,tpb:Pn,lb:Pn,tab:Pn,lab:Pn,url:Pn,pb:Cn,bl:Cn,tbl:Cn,dl:Cn,ltc:Cn,mtp:Cn,nor:Cn,nrr:Cn,rc:Cn,sn:Cn,sta:Cn,su:Cn,ttfb:Cn,ttfbb:Cn,ttlb:Cn,cmsdd:Cn,cmsds:Cn,smrt:Cn,df:Cn,cs:Cn,ts:Cn,cid:wn,pr:wn,sf:wn,sid:wn,st:wn,v:wn,msd:wn,bs:On,bsd:On,cdn:On,rtp:On,bg:On,pt:On,ec:On,e:On},Mn={REQUEST:Cn};function Fn(t,e){const i={};if(!t)return i;const r=Object.keys(t),s=e?(n=e,Object.keys(n).reduce(((t,e)=>{var i;return null===(i=n[e])||void 0===i||i.forEach((i=>t[i]=e)),t}),{})):{};var n;return r.reduce(((e,i)=>{var r;const n=xn[i]||s[i]||Mn.REQUEST;return(null!==(r=e[n])&&void 0!==r?r:e[n]={})[i]=t[i],e}),i)}const Nn="event";const Un=t=>Math.round(t),Bn=(t,e)=>Array.isArray(t)?t.map((t=>Bn(t,e))):t instanceof nn&&"string"==typeof t.value?new nn(Bn(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const i=new URL(t),r=new URL(e);if(i.origin!==r.origin)return t;const s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),Gn=t=>100*Un(t/100),$n={br:Un,d:Un,bl:Gn,dl:Gn,mtp:Gn,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof nn&&"string"==typeof t.value?i=new nn([t]):"string"==typeof t&&(i=[t])),Bn(i,e)},rtp:Gn,tb:Un},Kn="request",Vn="response",Hn=["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"],Yn=["e"],Wn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function jn(t){return Wn.test(t)}const qn=["d","dl","nor","ot","rtp","su"];const Xn=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const Qn=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function zn(t){return Qn.includes(t)||jn(t)}const Zn={[Vn]:function(t){return Hn.includes(t)||qn.includes(t)||Xn.includes(t)||jn(t)},[Nn]:function(t){return Hn.includes(t)||Yn.includes(t)||jn(t)},[Kn]:function(t){return Hn.includes(t)||qn.includes(t)||jn(t)}};function Jn(t,e={}){const i={};if(null==t||"object"!=typeof t)return i;const r=e.version||t.v||1,s=e.reportingMode||Kn,n=1===r?zn:Zn[s];let a=Object.keys(t).filter(n);const o=e.filter;"function"==typeof o&&(a=a.filter(o));const h=s===Vn||s===Nn;h&&!a.includes("ts")&&a.push("ts"),r>1&&!a.includes("v")&&a.push("v");const d=R({},$n,e.formatters),u={version:r,reportingMode:s,baseUrl:e.baseUrl};return a.sort().forEach((e=>{let s=t[e];const n=d[e];if("function"==typeof n&&(s=n(s,u)),"v"===e){if(1===r)return;s=r}"pr"==e&&1===s||(h&&"ts"===e&&!l(s)&&(s=Date.now()),function(t){return"number"==typeof t?l(t):null!=t&&""!==t&&!1!==t}(s)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(e)&&"string"==typeof s&&(s=new hn(s)),i[e]=s))})),i}function ta(t,e,i){return R(t,function(t,e={}){const i={};if(!t)return i;const r=Fn(Jn(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(r).reduce(((t,[e,i])=>{const r=_n(i,{whitespace:!1});return r&&(t[e]=r),t}),i)}(e,i))}const ea="CMCD";function ia(t,e={}){if(!t)return"";const i=function(t,e={}){return t?_n(Jn(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(i)}const ra=/CMCD=[^&#]+/;function sa(t,e,i){const r=function(t,e={}){if(!t)return"";const i=ia(t,e);return`${ea}=${i}`}(e,i);if(!r)return t;if(ra.test(t))return t.replace(ra,r);const s=t.includes("?")?"&":"?";return`${t}${s}${r}`}function na(t,e,i,r){t&&Object.keys(e).forEach((s=>{const n=t.filter((t=>t.groupId===s)).map((t=>{const n=R({},t);return n.details=void 0,n.attrs=new li(n.attrs),n.url=n.attrs.URI=aa(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=r,n}));t.push(...n)}))}function aa(t,e,i,r){const{HOST:s,PARAMS:n,[i]:a}=r;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}function oa(t,e,i){la(t,e,i),t.addEventListener(e,i)}function la(t,e,i){t.removeEventListener(e,i)}class ha extends k{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=ha.CDMCleanupPromise?[ha.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,r=`"${t.type}" event: init data type: "${e}"`;if(this.debug(r),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Ii(this.config));const e=t.map(Ri).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then((s=>{const n=Li(s);if("sinf"!==e||n!==yi.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);let a;try{const t=at(new Uint8Array(i)),e=Et(gi(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(t){return void this.warn(`${r} Failed to parse sinf: ${t}`)}const o=N(a),{keyIdToKeySessionPromise:l,mediaKeySessions:h}=this;let d=l[o];for(let t=0;t<h.length;t++){const r=h[t],s=r.decryptdata;if(!s.keyId)continue;const n=N(s.keyId);if(o===n||-1!==s.uri.replace(/-/g,"").indexOf(o)){if(d=l[n],!d)continue;if(s.pssh)break;delete l[n],s.pssh=new Uint8Array(i),s.keyId=a,d=l[o]=d.then((()=>this.generateRequestWithPreferredKeySession(r,e,i,"encrypted-event-key-match"))),d.catch((t=>this.handleError(t)));break}}d||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${h.length}.`))})).catch((t=>this.handleError(t)))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onWaitingForKey=null}registerListeners(){this.hls.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(f.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(f.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(f.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(f.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(f.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(f.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,r=e[t];return r?r.licenseUrl:t===yi.WIDEVINE&&i?i: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,i=e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,r=e.map((t=>t.audioCodec)).filter(i),s=e.map((t=>t.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((e,i)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,r,s).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?n(t):i(e instanceof da?e:new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===bi&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){const r=function(t,e,i,r){let s;switch(t){case yi.FAIRPLAY:s=["cenc","sinf"];break;case yi.WIDEVINE:case yi.PLAYREADY:s=["cenc"];break;case yi.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs=${t}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((t=>({contentType:`video/mp4; codecs=${t}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,e,i,r)}(t,e,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[t];let n=null==s?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${ne(r)}`),n=this.requestMediaKeySystemAccess(t,r);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=i.createMediaKeys().then((i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,r.then((e=>e?this.setMediaKeysServerCertificate(i,t,e):i))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${N(t.keyId||[])}`);const r=i.createSession(),s={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return N(t.keyId)}updateKeySession(t,e){var i;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${N((null==(i=t.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),r.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map((t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys}))).filter((({hasMediaKeys:t})=>!!t)).map((({keySystem:t})=>Ri(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,i)=>this.getKeySystemSelectionPromise(t).then((({keySystem:t})=>{const r=Ri(t);r?e(r):i(new Error(`Unable to find format for key-system "${t}"`))})).catch(i)))}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=Ii(this.config),i=t.map(Li).filter((t=>!!t&&-1!==e.indexOf(t)));return this.selectKeySystem(i)}loadKey(t){const e=t.keyInfo.decryptdata,i=this.getKeyIdString(e),r=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];if(!s){s=this.getKeySystemForKeyPromise(e).then((({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:e})))))));(this.keyIdToKeySessionPromise[i]=s.then((t=>{const i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",i,"playlist-key")}))).catch((t=>this.handleError(t)))}return s}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof da?this.hls.trigger(f.ERROR,t.data):this.hls.trigger(f.ERROR,{type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=Li(t.keyFormat),i=e?[e]:Ii(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Ii(this.config)),0===t.length)throw new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(i).then((()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.mediaKeys=e,this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${t}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===i.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,i,r){var s;const n=null==(s=this.config.drmSystems)||null==(s=s[t.keySystem])?void 0:s.generateRequest;if(n)try{const r=n.call(this.hls,e,i,t);if(!r)throw new Error("Invalid response from configured generateRequest filter");e=r.initDataType,i=r.initData?r.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){var a;if(this.warn(t.message),null!=(a=this.hls)&&a.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const o=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${o} (init data type: ${e} length: ${i?i.byteLength:null})`);const l=new vr,h=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void l.emit("error",new Error("invalid state"));const{messageType:r,message:s}=e;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,s).catch((t=>{l.eventNames().length?l.emit("error",t):this.handleError(t)})):"license-release"===r?t.keySystem===yi.FAIRPLAY&&(this.updateKeySession(t,mi("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},d=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void l.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const i=t.keyStatus;l.emit("keyStatus",i),"expired"===i&&(this.warn(`${t.keySystem} expired for key ${o}`),this.renewKeySession(t))};oa(t.mediaKeysSession,"message",h),oa(t.mediaKeysSession,"keystatuseschange",d);const f=new Promise(((t,e)=>{l.on("error",e),l.on("keyStatus",(i=>{i.startsWith("usable")?t():"output-restricted"===i?e(new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?e(new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return t.mediaKeysSession.generateRequest(e,i).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${o}`)})).catch((t=>{throw new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>f)).catch((e=>{throw l.removeAllListeners(),this.removeSession(t),e})).then((()=>(l.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,i)=>{if("string"==typeof i&&"object"==typeof e){const t=i;i=e,e=t}this.log(`key status change "${e}" for keyStatuses keyId: ${N("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${N(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise(((s,n)=>{const a={responseType:"arraybuffer",url:r},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,r)=>{s(t.data)},onError:(e,i,s,o)=>{n(new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:b({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${r}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,s)=>{n(new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(t,e,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise(((r,s)=>{t.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${e}"`),r(t)})).catch((t=>{s(new da({type:u.KEY_SYSTEM_ERROR,details:c.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((t=>{throw new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let e;for(let i=0,r=s.length;i<r;i++){var n,a;e=s[i];const r=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;r&&o&&t.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return mi(atob(l))}setupLicenseXHR(t,e,i,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,t,e,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return t.open("POST",e,!0),s.call(this.hls,t,e,i,r)})).then((i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||r}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{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 s(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 i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,a,n,t)}catch(t){this.error(t)}r(e)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new da({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_LICENSE_REQUEST_FAILED,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 i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(r,s)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then((({xhr:e,licenseChallenge:i})=>{t.keySystem==yi.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}))}))}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,oa(i,"encrypted",this.onMediaEncrypted),oa(i,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media;t&&(la(t,"encrypted",this.onMediaEncrypted),la(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const e=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,_i.clearKeyUriToKeyIdMap();const r=i.length;ha.CDMCleanupPromise=Promise.all(i.map((t=>this.removeSession(t))).concat(null==e||null==(t=e.setMediaKeys(null))?void 0:t.catch((t=>{var e;this.log(`Could not clear media keys: ${t}`),null==(e=this.hls)||e.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})})))).catch((t=>{var e;this.log(`Could not close sessions and clear media keys: ${t}`),null==(e=this.hls)||e.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})})).then((()=>{r&&this.log("finished closing key sessions and clearing media keys")}))}onManifestLoading(){this.keyFormatPromise=null}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:i}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);r>-1&&this.mediaKeySessions.splice(r,1);const{drmSystemOptions:s}=this.config,n=function(t){var e;return"persistent-license"===t.sessionType||!(null==(e=t.sessionTypes)||!e.some((t=>"persistent-license"===t)))}(s)?new Promise(((t,i)=>{self.setTimeout((()=>i(new Error("MediaKeySession.remove() timeout"))),8e3),e.remove().then(t)})):Promise.resolve();return n.catch((t=>{var e;this.log(`Could not remove session: ${t}`),null==(e=this.hls)||e.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})})).then((()=>e.close())).catch((t=>{var e;this.log(`Could not close session: ${t}`),null==(e=this.hls)||e.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})}))}}}ha.CDMCleanupPromise=void 0;class da 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}}function ua(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function ca(t,e){const i=t.mode;if("disabled"===i&&(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){O.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){O.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function fa(t,e){const i=t.mode;if("disabled"===i&&(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"===i&&(t.mode=i)}function ga(t,e,i,r){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=function(t,e,i){const r=[],s=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let r,s=0,n=i;for(;s<=n;)if(r=Math.floor((n+s)/2),e<t[r].startTime)n=r-1;else{if(!(e>t[r].startTime&&s<i))return r;s=r+1}return t[s].startTime-e<e-t[n].startTime?s:n}(t,e);if(s>-1)for(let n=s,a=t.length;n<a;n++){const s=t[n];if(s.startTime>=e&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(t.cues,e,i);for(let e=0;e<s.length;e++)r&&!r(s[e])||t.removeCue(s[e])}"disabled"===s&&(t.mode=s)}function ma(t){const e=[];for(let i=0;i<t.length;i++){const r=t[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[i])}return e}function pa(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const va=.025;let ya=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Ea(t,e,i){return`${t.identifier}-${i+1}-${pa(e)}`}class Ta{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 i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}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 Sa(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-Sa(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=l(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 Sa(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)<va))}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"]?ya.Range:ya.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Sa(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<va)?e.start:e.start+e.duration}function Aa(t,e,i){const r=new self.URL(t,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",e),r}function La(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function Ra(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class Ia{constructor(t,e,i,r){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(f.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new t(e);this.interstitial=i,this.assetItem=r;const n=()=>{this.hasDetails=!0};s.once(f.LEVEL_LOADED,n),s.once(f.AUDIO_TRACK_LOADED,n),s.once(f.SUBTITLE_TRACK_LOADED,n),s.on(f.MEDIA_ATTACHING,((t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(f.BUFFER_APPENDED,(()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,s.trigger(f.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 e=this.assetItem.uri;try{e=Aa(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=ti.bufferInfo(t,r,0);return this.getAssetTime(s.end)>=i-.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=ti.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 i=e-this.startOffset;if(i>0&&i<t)return i}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 i=t-e;if(Math.abs(i)>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,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&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,i){var r;null==(r=this.hls)||r.on(t,e)}once(t,e,i){var r;null==(r=this.hls)||r.once(t,e)}off(t,e,i){var r;null==(r=this.hls)||r.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${Ra(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class ba 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(((i,r)=>t<=r.startOffset&&e>r.startOffset?(delete r.error,i+1):i),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 i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const r=this.items;if(r)for(r[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let r=0;r<i.length;r++){let s=i[r];if(e&&"primary"!==e&&(s=s[e]),t===s.start||t>s.start&&t<s.end)return r}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let r=t;r<=e&&i[r];r++){const t=i[r].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return r}return-1}findEventIndex(t){const e=this.items;if(e)for(let r=e.length;r--;){var i;if((null==(i=e[r].event)?void 0:i.identifier)===t)return r}return-1}findAssetIndex(t,e){const i=t.assetList,r=i.length;if(r>1)for(let t=0;t<r;t++){const s=i[t];if(!s.error){const i=s.timelineStart;if(e===i||e>i&&(e<i+(s.duration||0)||t===r-1))return t}}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,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e){const i=t.main.details,{dateRanges:r}=i,s=this.events,n=this.parseDateRanges(r,{url:i.url},e),a=Object.keys(r),o=s?s.filter((t=>!a.includes(t.identifier))):[];n.length&&n.sort(((t,e)=>{const i=t.cue.pre,r=t.cue.post,s=e.cue.pre,n=e.cue.post;if(i&&!s)return-1;if(s&&!i)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(i||s||r||n)){const i=t.startTime,r=e.startTime;if(i!==r)return i-r}return t.dateRange.tagOrder-e.dateRange.tagOrder})),this.events=n,o.forEach((t=>{this.removeEvent(t)})),this.updateSchedule(t,o)}updateSchedule(t,e=[],i=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const s=this.items,n=this.parseSchedule(r,t);(i||e.length||(null==s?void 0:s.length)!==n.length||n.some(((t,e)=>Math.abs(t.playout.start-s[e].playout.start)>.005||Math.abs(t.playout.end-s[e].playout.end)>.005)))&&(this.items=n,this.onScheduleUpdate(e,s))}}parseDateRanges(t,e,i){const r=[],s=Object.keys(t);for(let n=0;n<s.length;n++){const a=s[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Ta(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),r.push(t)}}return r}parseSchedule(t,e){const i=[],r=e.main.details,s=r.live?1/0:r.edge;let n=0;if((t=t.filter((t=>!(t.error||t.cue.once&&t.hasPlayed)))).length){this.resolveOffsets(t,e);let r=0,o=0;if(t.forEach(((e,a)=>{const l=e.cue.pre,h=e.cue.post,d=t[a-1]||null,u=e.appendInPlace,c=h?s:e.startOffset,f=e.duration,g=e.timelineOccupancy===ya.Range?f:0,m=e.resumptionOffset,p=(null==d?void 0:d.startTime)===c,v=c+e.cumulativeDuration;let y=u?v+f:c+m;if(l||!h&&c<=0){const t=o;o+=g,e.timelineStart=v;const r=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:r,end:n},integrated:{start:t,end:o}})}else{if(!(c<=s))return;{if(!p){const s=c-r;if(s>.033){const l=r,h=o;o+=s;const d=n;n+=s;const u={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+s,playout:{start:d,end:n},integrated:{start:h,end:o}};i.push(u)}else s>0&&d&&(d.cumulativeDuration+=s,i[i.length-1].end=c)}h&&(y=v),e.timelineStart=v;const s=o;o+=g;const l=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:s,end:o}})}}const E=e.resumeTime;r=h||E>s?s:E})),r<s){var a;const t=r,e=o,l=s-r;o+=l;const h=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:r,end:t+l,playout:{start:h,end:n},integrated:{start:e,end:o}})}this.setDurations(s,n,o)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:s,playout:{start:t,end:s},integrated:{start:t,end:s}}),this.setDurations(s,s,s)}return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,e){const i=e.main.details,r=i.live?1/0:i.edge;let s=0,n=-1;t.forEach(((a,o)=>{const h=a.cue.pre,d=a.cue.post,u=h?0:d?r:a.startTime;this.updateAssetDurations(a);if(n===u?a.cumulativeDuration=s:(s=0,n=u),!d&&a.snapOptions.in&&(a.resumeAnchor=me(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)}if(!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=l(a.resumeOffset)?a.resumeOffset:a.duration;s+=c}))}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,r=t.startTime+t.resumptionOffset;if(Math.abs(i-r)>va)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1;return!Object.keys(e).some((r=>{const s=e[r].details,n=s.edge;if(i>=n)return this.log(`"${t.identifier}" resumption ${i} past ${r} playlist end ${n}`),!1;const a=me(null,s.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;const o="audio"===r?.175:0;return!(Math.abs(a.start-i)<va+o||Math.abs(a.end-i)<va+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)}))}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,r=!1,s=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,r||(r=null===a.duration),s||(s=!!a.error);i+=a.error?0:a.duration||0}t.duration=r&&!s?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function ka(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Da{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let r;try{r=Aa(i,this.hls.sessionId,t.baseUrl)}catch(e){const r=this.assignAssetListError(t,c.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(f.ERROR,r)}e&&"data:"!==r.protocol&&r.searchParams.set("_HLS_start_offset",""+e);const s=this.hls.config,n=new(0,s.loader)(s),a={responseType:"json",url:r.href},o=s.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,i,r,s)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))t.assetListResponse=n,this.hls.trigger(f.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:s});else{const e=this.assignAssetListError(t,c.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),r.url,i,s);this.hls.trigger(f.ERROR,e)}},onError:(e,i,r,s)=>{const n=this.assignAssetListError(t,c.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,s,r);this.hls.trigger(f.ERROR,n)},onTimeout:(e,i,r)=>{const s=this.assignAssetListError(t,c.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,r);this.hls.trigger(f.ERROR,s)}};return n.load(a,l,h),this.hls.trigger(f.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,i,r,s,n){return t.error=i,{type:u.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:r,error:i,networkDetails:n,stats:s}}}function _a(t){null==t||t.play().catch((()=>{}))}class Pa{constructor(t){this.buffered=void 0;const e=(e,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}const Ca={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},wa=t=>String.fromCharCode(Ca[t]||t),Oa=15,xa=100,Ma={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Fa={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Na={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ua={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ba=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ga{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;O.log(`${this.time} [${t}] ${i}`)}}}const $a=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class Ka{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 i=0;i<e.length;i++){const r=e[i];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Va{constructor(){this.uchar=" ",this.penState=new Ka}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()}}class Ha{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Ka,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<xa;t++)this.chars.push(new Va);this.logger=t}equals(t){for(let e=0;e<xa;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<xa;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<xa;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>xa&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=xa)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].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=wa(t);this.pos>=xa?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<xa;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 i=0;i<xa;i++){const r=this.chars[i].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class Ya{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Oa;e++)this.rows.push(new Ha(t));this.logger=t}reset(){for(let t=0;t<Oa;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<Oa;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<Oa;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Oa;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 = "+ne(t)));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<Oa;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const r=i.rows[t].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(i.rows[t+r])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,r=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[r].penState.foreground}const r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,(()=>"bkgData = "+ne(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 i="",r=-1;for(let i=0;i<Oa;i++){const s=this.rows[i].getTextString();s&&(r=i+1,t?e.push("Row "+r+": '"+s+"'"):e.push(s.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Wa{constructor(t,e,i){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 Ya(i),this.nonDisplayedMemory=new Ya(i),this.lastOutputScreen=new Ya(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}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 e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);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};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[i]}this.logger.log(2,"MIDROW: "+ne(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))}}class ja{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Ga;this.channels=[null,new Wa(t,e,r),new Wa(t+1,i,r)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],r=127&e[t+1];let s=!1,n=null;if(0===i&&0===r)continue;this.logger.log(3,(()=>"["+$a([e[t],e[t+1]])+"] -> ("+$a([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if(Xa(i,r,a)){qa(null,null,a),this.logger.log(3,(()=>"Repeated command ("+$a([i,r])+") is dropped"));continue}qa(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else qa(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+$a([i,r])+" orig: "+$a([e[t],e[t+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 i=20===t||21===t||23===t?1:2,r=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+$a([t,e])+")")),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const r=t<=23?1:2;i=e>=64&&e<=95?1===r?Ma[t]:Na[t]:1===r?Fa[t]:Ua[t];const s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,e)),this.currentChannel=r,!0)}interpretPAC(t,e){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(t,e){let i,r=null,s=null;if(t>=25?(i=2,s=t-8):(i=1,s=t),s>=17&&s<=19){let t;t=17===s?e+80:18===s?e+112:e+144,this.logger.log(2,(()=>"Special char '"+wa(t)+"' in channel "+i)),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);return r&&this.logger.log(3,(()=>"Char codes = "+$a(r).join(","))),r}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const r={};16===t||24===t?(i=Math.floor((e-32)/2),r.background=Ba[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));const s=t<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}qa(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function qa(t,e,i){i.a=t,i.b=e}function Xa(t,e,i){return i.a===t&&i.b===e}var Qa=function(){if(null!=vi&&vi.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function r(t){return i(e,t)}function s(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,u=e,c=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(t){d=!!t}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return m},set:function(e){const r=function(e){return i(t,e)}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},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",s({},l,{get:function(){return y},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},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",s({},l,{get:function(){return T},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},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",s({},l,{get:function(){return A},set:function(t){const e=r(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}();class za{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Za(t){function e(t,e,i,r){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(r||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class Ja{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let r=0;r<i.length;++r)if(e===i[r]){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 i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function to(t,e,i,r){const s=r?t.split(r):[t];for(const t in s){if("string"!=typeof s[t])continue;const r=s[t].split(i);if(2!==r.length)continue;e(r[0],r[1])}}const eo=new Qa(0,0,""),io="middle"===eo.align?"middle":"center";function ro(t,e,i){const r=t;function s(){const e=Za(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=s(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),n(),e.endTime=s(),n(),function(t,e){const r=new Ja;to(t,(function(t,e){let s;switch(t){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===e){r.set(t,i[s].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":s=e.split(","),r.integer(t,s[0]),r.percent(t,s[0])&&r.set("snapToLines",!1),r.alt(t,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",io,"end"]);break;case"position":s=e.split(","),r.percent(t,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",io,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",io,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===eo.line&&(s=-1),e.line=s,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",io);let n=r.get("position","auto");"auto"===n&&50===eo.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function so(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class no{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new za,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=so(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const r=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),r}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=i();const r=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?to(t,(function(t,e){}),/:/):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 Qa(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{ro(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!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(t){"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}}const ao=/\r\n|\n\r|\n|\r/g,oo=function(t,e,i=0){return t.slice(i,i+e.length)===e};function lo(t,e,i){return pa(t.toString())+pa(e.toString())+pa(i)}function ho(t,e,i,r,s,n,a){const o=new no,h=F(new Uint8Array(t)).trim().replace(ao,"\n").split("\n"),d=[],u=e?function(t,e=1){return Is(t,Rs,1/e)}(e.baseTime,e.timescale):0;let c,f="00:00.000",g=0,m=0,p=!0;o.oncue=function(t){const n=i[r];let a=i.ccOffset;const o=(g-u)/9e4;if(null!=n&&n.new&&(void 0!==m?a=i.ccOffset=n.start:function(t,e,i){let r=t[e],s=t[r.prevCC];if(!s||!s.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;t.ccOffset+=r.start-s.start,r.new=!1,r=s,s=t[r.prevCC]}t.presentationOffset=i}(i,r,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=t.endTime-t.startTime,h=ws(9e4*(t.startTime+a-m),9e4*s)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=lo(t.startTime,t.endTime,f)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(d)},h.forEach((t=>{if(p){if(oo(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{oo(t,"LOCAL:")?f=t.slice(6):oo(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))}));try{m=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),s=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(l(e)&&l(i)&&l(r)&&l(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*r,e+=36e5*s,e}(f)/1e3}catch(t){c=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}const uo="stpp.ttml.im1t",co=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,fo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,go={left:"start",center:"center",right:"end",start:"start",end:"end"};function mo(t,e,i,r){const s=ut(new Uint8Array(t),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=s.map((t=>F(t))),a=function(t,e,i=1,r=!1){return Is(t,e,1/i,r)}(e.baseTime,1,e.timescale);try{n.forEach((t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((t,e)=>(t[e]=r.getAttribute(`ttp:${e}`)||s[e],t)),{}),a="preserve"!==r.getAttribute("xml:space"),o=vo(po(r,"styling","style")),l=vo(po(r,"layout","region")),h=po(r,"body","[begin]");return[].map.call(h,(t=>{const i=yo(t,a);if(!i||!t.hasAttribute("begin"))return null;const r=So(t.getAttribute("begin"),n),s=So(t.getAttribute("dur"),n);let h=So(t.getAttribute("end"),n);if(null===r)throw To(t);if(null===h){if(null===s)throw To(t);h=r+s}const d=new Qa(r-e,h-e,i);d.id=lo(d.startTime,d.endTime,d.text);const u=function(t,e,i){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(s=i[a]);return n.reduce(((i,n)=>{const a=Eo(e,r,n)||Eo(t,r,n)||Eo(s,r,n);return a&&(i[n]=a),i}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:c}=u;if(c){const t=go[c];t&&(d.lineAlign=t),d.align=c}return R(d,u),d})).filter((t=>null!==t))}(t,a))))}catch(t){r(t)}}function po(t,e,i){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function vo(t){return t.reduce(((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t}),{})}function yo(t,e){return[].slice.call(t.childNodes).reduce(((t,i,r)=>{var s;return"br"===i.nodeName&&r?t+"\n":null!=(s=i.childNodes)&&s.length?yo(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent}),"")}function Eo(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function To(t){return new Error(`Could not parse ttml timestamp ${t}`)}function So(t,e){if(!t)return null;let i=Za(t);return null===i&&(co.test(t)?i=function(t,e){const i=co.exec(t),r=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/e.frameRate}(t,e):fo.test(t)&&(i=function(t,e){const i=fo.exec(t),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),i}class Ao{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,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Lo{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(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(f.FRAG_LOADING,this.onFragLoading,this),t.on(f.FRAG_LOADED,this.onFragLoaded,this),t.on(f.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(f.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(f.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(f.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(f.FRAG_LOADING,this.onFragLoading,this),t.off(f.FRAG_LOADED,this.onFragLoaded,this),t.off(f.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(f.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(f.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(f.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Ao(this,"textTrack1"),e=new Ao(this,"textTrack2"),i=new Ao(this,"textTrack3"),r=new Ao(this,"textTrack4");this.cea608Parser1=new ja(1,t,e),this.cea608Parser2=new ja(3,i,r)}addCues(t,e,i,r,s){let n=!1;for(let t=s.length;t--;){const r=s[t],d=(a=r[0],o=r[1],l=e,h=i,Math.min(o,h)-Math.max(a,l));if(d>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],i),n=!0,d/(i-e)>.5))return}var a,o,l,h;if(n||s.push([e,i]),this.config.renderTextTracksNatively){const s=this.captionsTracks[t];this.Cues.newCue(s,e,i,r)}else{const s=this.Cues.newCue(null,e,i,r);this.hls.trigger(f.CUES_PARSED,{type:"captions",cues:s,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:s,trackId:n}){const{unparsedVttFrags:a}=this;i===y&&(this.initPTS[e.cc]={baseTime:r,timescale:s,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach((t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(f.FRAG_LOADED,t):this.hls.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){const s=i.textTracks[r];if(Io(s,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:r}=this,{label:s,languageCode:n}=e[t],a=this.getExistingTrack(s,n);if(a)i[t]=a,fa(i[t]),ua(i[t],r);else{const e=this.createTextTrack("captions",s,n);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(f.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const r=this.media;if(r)return r.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,i)return;const{captionsTracks:r}=this;Object.keys(r).forEach((t=>{fa(r[t]),delete r[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 t=0;t<e.length;t++)fa(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],r=i.some((t=>t.textCodec===uo));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Ws(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?ma(t.textTracks):null;if(this.tracks.forEach(((t,i)=>{let r;if(e){let i=null;for(let r=0;r<e.length;r++)if(e[r]&&Io(e[r],t)){i=e[r],e[r]=null;break}i&&(r=i)}if(r)fa(r);else{const e=Ro(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)})),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(f.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 i=`textTrack${e[1]}`,r=this.captionsProperties[i];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.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===y){var i,r;const{cea608Parser1:t,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(r=e.part)?void 0:r.index)?i:-1;t&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:r}=e;if(i.type===T)if(r.byteLength){const t=i.decryptdata,s="stats"in e;if(null==t||!t.encrypted||s){const t=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===uo?this._parseIMSC1(i,r):this._parseVTTs(e)}}else this.hls.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;mo(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),i.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{i.logger.log(`Failed to parse IMSC1: ${e}`),i.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:i,payload:r}=t,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(t);const o=this.hls;ho(null!=(e=i.initSegment)&&e.data?Tt(i.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(t=>{this._appendCues(t,i.level),o.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(e=>{const s="Missing initPTS for VTT MPEGTS"===e.message;s?n.push(t):this._fallbackToIMSC1(i,r),o.logger.log(`Failed to parse VTT cue: ${e}`),s&&a>i.cc||o.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})}))}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||mo(e,this.initPTS[t.cc],(()=>{i.textCodec=uo,this._parseIMSC1(t,e)}),(()=>{i.textCodec="wvtt"}))}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((t=>ca(i,t)))}else{const r=this.tracks[e];if(!r)return;const s=r.default?"default":"subtitles"+e;i.trigger(f.CUES_PARSED,{type:"subtitles",cues:t,track:s})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===T&&this.onFragLoaded(f.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:r}=e;if(i.type!==y||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<r.length;t++){const e=r[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(r[t].pts,i[0]),this.cea608Parser2.addData(r[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:r,type:s}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!s||"video"===s){const{captionsTracks:t}=this;Object.keys(t).forEach((r=>ga(t[r],e,i)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach((i=>ga(t[i],e,r)))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let r=2;for(let s=0;s<i;s++){const i=t[r++],s=127&t[r++],n=127&t[r++];if(0===s&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(s),e[t].push(n))}}return e}}function Ro(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Io(t,e){return!!t&&t.kind===Ro(e)&&qs(e,t)}const bo=/\s/,ko={newCue(t,e,i,r){const s=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let c=0;c<r.rows.length;c++)if(n=r.rows[c],o=!0,l=0,h="",!n.isEmpty()){var u;for(let t=0;t<n.chars.length;t++)bo.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const r=so(h.trim()),f=lo(e,i,r);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(a=new d(e,i,r),a.id=f,a.line=c+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return t&&s.length&&(s.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),s.forEach((e=>ca(t,e)))),s}};const Do=/(\d+)-(\d+)\/(\d+)/;class _o{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||Po,this.controller=new self.AbortController,this.stats=new q}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,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(R({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),n="arraybuffer"===t.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&l(o)?o:h,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))}),e.timeout);(Gs(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((i=>{var s;this.response=this.loader=i;const a=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))}),h-(a-r.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new Co(e||"fetch, bad network response",t,i)}r.loading.first=a,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Do.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(l(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(i.headers)||r.total;const o=null==(s=this.callbacks)?void 0:s.onProgress;return o&&l(e.highWaterMark)?this.loadProgressively(i,r,t,e.highWaterMark,o):n?i.arrayBuffer():"json"===t.responseType?i.json():i.text()})).then((i=>{var s,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const h=i[a];h&&(r.loaded=r.total=h);const d={url:o.url,data:i,code:o.status},u=null==(s=this.callbacks)?void 0:s.onProgress;u&&!l(e.highWaterMark)&&u(r,t,i,o),null==(n=this.callbacks)||n.onSuccess(d,r,t,o)})).catch((e=>{var i;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=e&&e.code||0,n=e?e.message:null;null==(i=this.callbacks)||i.onError({code:s,text:n},t,e?e.details:null,r)}))}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,i,r=0,s){const n=new fr,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(e,i,n.flush().buffer,t)):s(e,i,l.buffer,t),o()})).catch((()=>Promise.reject()));return o()}}function Po(t,e){return new self.Request(t.url,e)}class Co extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const wo=/^age:\s*[\d.]+\s*$/im;class Oo{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 q,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,i){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=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,e.url)})).catch((t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),s(i,e.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)})).catch((t=>{var s;null==(s=this.callbacks)||s.onError({code:i.status,text:t.message},e,i,r)})):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const r=e.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);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),i.timeout=s&&l(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const r=e.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const r=e.status,l="text"===e.responseType?e.responseText:null;if(r>=200&&r<300){const s=null!=l?l:e.response;if(null!=s){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?s.byteLength:s.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,t,s,e);const h={url:e.responseURL,data:s,code:r};return void(null==(a=this.callbacks)||a.onSuccess(h,i,t,e))}}const h=s.loadPolicy.errorRetry;var o;if(Le(h,i.retry,!1,{url:t.url,data:void 0,code:r}))this.retry(h);else O.error(`${r} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:r,text:e.statusText},t,e,i)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Le(t,this.stats.retry,!0))this.retry(t);else{var e;O.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:i}=this;this.retryDelay=Se(t,i.retry),i.retry++,O.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.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&&wo.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}}const xo=b(b({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:Oo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController: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:i,partCurrent:r,hls:s}=this,{autoLevelEnabled:n,media:a}=s;if(!i||!a)return;const o=performance.now(),h=r?r.stats:i.stats,d=r?r.duration:i.duration,u=o-h.loading.start,c=s.minAutoLevel,g=i.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(a.paused||!a.playbackRate||!a.readyState))return;const y=s.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(a.playbackRate);if(u<=Math.max(E,d/(2*T)*1e3))return;const S=y?y.len/T:0,A=h.loading.first?h.loading.first-h.loading.start:-1,L=h.loaded&&A>-1,R=this.getBwEstimate(),I=s.levels,b=I[g],k=Math.max(h.loaded,Math.round(d*(i.bitrate||b.averageBitrate)/8));let D=L?u-A:u;D<1&&L&&(D=Math.min(u,8*h.loaded/R));const _=L?1e3*h.loaded/D:0,P=E/1e3,C=_?(k-h.loaded)/_:8*k/R+P;if(C<=S)return;const w=_?8*_:R,O=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),x=this.hls.config.abrBandWidthUpFactor;let M,F=Number.POSITIVE_INFINITY;for(M=g-1;M>c;M--){const t=I[M].maxBitrate,e=!I[M].details||O;if(F=this.getTimeToLoadFrag(P,w,d*t,e),F<Math.min(S,d+P))break}if(F>=C)return;if(F>10*d)return;L?this.bwEstimator.sample(u-Math.min(E,A),h.loaded):this.bwEstimator.sampleTTFB(u);const N=I[M].maxBitrate;this.getBwEstimate()*x>N&&this.resetEstimator(N);const U=this.findBestLevel(N,c,M,0,S,1,1);U>-1&&(M=U),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|A} ms\n Current BW estimate: ${l(R)?0|R:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|N} bps`),s.nextLoadLevel=s.nextAutoLevel=M,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===M&&M>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),i.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)}}};p||C>2*F?B():this.timer=self.setInterval(B,1e3*F),s.trigger(f.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},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 A(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.FRAG_LOADING,this.onFragLoading,this),t.on(f.FRAG_LOADED,this.onFragLoaded,this),t.on(f.FRAG_BUFFERED,this.onFragBuffered,this),t.on(f.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(f.LEVEL_LOADED,this.onLevelLoaded,this),t.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(f.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.FRAG_LOADING,this.onFragLoading,this),t.off(f.FRAG_LOADED,this.onFragLoaded,this),t.off(f.FRAG_BUFFERED,this.onFragBuffered,this),t.off(f.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(f.LEVEL_LOADED,this.onLevelLoaded,this),t.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(f.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(f.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 i=e.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r: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 c.BUFFER_ADD_CODEC_ERROR:case c.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case c.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:r}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=r?r.stats:t.stats,s=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(t,e,i,r){return t+i/e+(r?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:r}=e.stats,s=r.end-r.first;l(s)&&(this.lastLevelLoadSec=s/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:i}){const r=i?i.stats:e.stats;if(e.type===y&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,s=this.hls.levels[e.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+t;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:r,frag:e,part:i,id:e.type};this.onFragBuffered(f.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:r}=e,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted)return;if(this.ignoreFragment(i))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==y||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,e,t,0,r,1,1);if(s>-1)return s;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(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const r=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,r)&&e[t].loadError<=e[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,r,l,0,h,d);if(t>=0)return this.rebufferNotice=-1,t}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1}}const c=this.findBestLevel(o,n,r,l,u,h,d);if(this.rebufferNotice!==c&&(this.rebufferNotice=c,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`)),c>-1)return c;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,r,s,n,a){var o;const h=r+s,d=this.lastLoadedFragLevel,u=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===g.length)return 0;const y=g[u],E=!(null==(o=this.hls.latestLevelDetails)||!o.live),T=-1===p||-1===d;let S,A="SDR",L=(null==y?void 0:y.frameRate)||0;const{audioPreference:R,videoPreference:I}=v,b=this.audioTracksByGroup||(this.audioTracksByGroup=oe(m));let k=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,i,r){return t.slice(i,r+1).reduce(((t,i,r)=>{if(!i.codecSet)return t;const s=i.audioGroups;let n=t[i.codecSet];n||(t[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,s&&s.forEach((t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach((t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]})))})),t}),{})}(g,b,e,i)),s=function(t,e,i,r,s){const n=Object.keys(t),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,h=null==s?void 0:s.videoCodec,d=a&&2===parseInt(a);let u=!1,c=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=se(e,s);for(let e=n.length;e--;){const i=t[n[e]];u||(u=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter((t=>i.videoRanges[t]>0)).length>0&&(c=!0)}f=l(f)?f:0,g=l(g)?g:0;const S=Math.max(1080,f),A=Math.max(30,g);m=l(m)?m:i,i=Math.max(m,i),c||(e=void 0);const L=n.length>1;return{codecSet:n.reduce(((e,r)=>{const s=t[r];if(r===e)return e;if(y=c?T.filter((t=>s.videoRanges[t]>0)):[],L){if(s.minBitrate>i)return ae(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),e;if(!s.hasDefaultAudio)return ae(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return ae(r,`audio codec preference "${o}" not found`),e;if(a&&!d){if(!s.channels[a])return ae(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),e}else if((!o||d)&&u&&0===s.channels[2])return ae(r,"no renditions with stereo sound found"),e;if(s.minHeight>S)return ae(r,`min resolution of ${s.minHeight} > maximum of ${S}`),e;if(s.minFramerate>A)return ae(r,`min framerate of ${s.minFramerate} > maximum of ${A}`),e;if(!y.some((t=>s.videoRanges[t]>0)))return ae(r,`no variants with VIDEO-RANGE of ${ne(y)} found`),e;if(h&&r.indexOf(h.substring(0,4))%5!=0)return ae(r,`video codec preference "${h}" not found`),e;if(s.maxScore<v)return ae(r,`max score of ${s.maxScore} < selected max of ${v}`),e}return e&&(xt(r)>=xt(e)||s.fragmentError>t[e].fragmentError)?e:(p=s.minIndex,v=s.maxScore,r)}),void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(r,A,t,R,I),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:h,minIndex:d,preferHDR:u}=s;k=d,S=n,A=u?a[a.length-1]:a[0],L=o,t=Math.max(t,h),this.log(`picked start tier ${ne(s)}`)}else S=null==y?void 0:y.codecSet,A=null==y?void 0:y.videoRange;const D=f?f.duration:c?c.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=i;o>=e;o--){var C;const e=g[o],c=o>u;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Yt(e,b,A,L,t,R)?(e.supportedPromise=Wt(e,b,i,this.supportedCache),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const i=this.hls.levels,r=i.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${r} ${ne(t)}`):t.supported?t.decodingInfoResults.some((t=>!1===t.smooth||!1===t.powerEfficient))&&this.log(`MediaCapabilities decodingInfo for level ${r} not smooth or powerEfficient: ${ne(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${ne(t)}`),r>-1&&i.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):e.supportedResult=Vt}if((S&&e.codecSet!==S||A&&e.videoRange!==A||c&&L>e.frameRate||!c&&L>0&&L<e.frameRate||null!=(C=e.supportedResult)&&null!=(C=C.decodingInfoResults)&&C.some((t=>!1===t.smooth)))&&(!T||o!==k)){P.push(o);continue}const m=e.details,y=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||D;let I;I=c?a*t:n*t;const w=D&&r>=2*D&&0===s?e.averageBitrate:e.maxBitrate,O=this.getTimeToLoadFrag(_,I,w*y,void 0===m);if(I>=w&&(o===d||0===e.loadError&&0===e.fragmentError)&&(O<=_||!l(O)||E&&!this.bitrateTestDelay||O<h)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[P[0]].codecs}" ${g[P[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(I)})-bitrate=${Math.round(I-w)} ttfb:${_.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${O.toFixed(1)} firstSelection:${T} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends k{constructor(t,e){var i;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:i}=this;t&&this.log("Media source opened"),e&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(f.MEDIA_ATTACHED,{media:e,mediaSource:i}),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=(i=x(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===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(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.MANIFEST_PARSED,this.onManifestParsed,this),t.on(f.BUFFER_RESET,this.onBufferReset,this),t.on(f.BUFFER_APPENDING,this.onBufferAppending,this),t.on(f.BUFFER_CODECS,this.onBufferCodecs,this),t.on(f.BUFFER_EOS,this.onBufferEos,this),t.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(f.FRAG_PARSED,this.onFragParsed,this),t.on(f.FRAG_CHANGED,this.onFragChanged,this),t.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.MANIFEST_PARSED,this.onManifestParsed,this),t.off(f.BUFFER_RESET,this.onBufferReset,this),t.off(f.BUFFER_APPENDING,this.onBufferAppending,this),t.off(f.BUFFER_CODECS,this.onBufferCodecs,this),t.off(f.BUFFER_EOS,this.onBufferEos,this),t.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(f.FRAG_PARSED,this.onFragParsed,this),t.off(f.FRAG_CHANGED,this.onFragChanged,this),t.off(f.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};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 r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===e?R(i,r.tracks):this.sourceBuffers.forEach((t=>{const[e]=t;e&&(i[e]=R({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null})),{media:t,mediaSource:e,tracks:i}}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 i;let r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const r=x(this.appendSource);if(r){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const s=this.mediaSource=e.mediaSource||new r;if(this.assignMediaSource(s),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&s instanceof e,Js(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.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 i=this.tracks,r=e.tracks,s=r?Object.keys(r):null,n=s?s.length:0,a=()=>{Promise.resolve().then((()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()}))};if(r&&s&&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: ${ne(i,((t,e)=>"initSegment"===t?void 0:e))};\ntransfer tracks: ${ne(r,((t,e)=>"initSegment"===t?void 0:e))}}`),!M(r,i)){e.mediaSource=null,e.tracks=void 0;const s=t.currentTime,n=this.details,a=Math.max(s,(null==n?void 0:n.fragments[0].start)||0);return a-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${s}`),this.onMediaDetaching(f.MEDIA_DETACHING,{}),this.onMediaAttaching(f.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,s.forEach((t=>{const e=t,i=r[e];if(i){const t=i.buffer;if(t){const r=this.fragmentTracker,s=i.id;if(r.hasFragments(s)||r.hasParts(s)){const i=ti.getBuffered(t);r.detectEvictedFragments(e,i,s,null,!0)}const n=tn(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}})),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 i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:r,mediaSource:s,_objectUrl:n}=this;if(s){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((([t])=>{t&&this.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===s.readyState;try{const e=s.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),s.removeSourceBuffer(e[i]);t&&s.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(r.removeAttribute("src"),this.appendSource&&Js(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(f.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach((([t])=>{t&&this.resetBuffer(t)})),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[tn(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Xs(this.tracks)}onBufferCodecs(t,e){const i=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),n=!s&&this.sourceBufferCount&&this.media&&r.some((t=>!i[t]));s||n?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach((t=>{var r,s;const n=e[t],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:u}=n;let c=i[t];const f=null==(r=this.transferData)||null==(r=r.tracks)?void 0:r[t],g=null!=f&&f.buffer?f:c,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;c||(c=i[t]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:h,levelCodec:l,metadata:d,id:a});const v=Ut(m,p),y=null==v?void 0:v.replace(Qs,"$1");let E=Ut(o,l);const T=null==(s=E)?void 0:s.replace(Qs,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=Nt(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(c.pendingCodec||c.codec)&&(c.pendingCodec=E),c.container=h,this.appendChangeType(t,h,E))})),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t}),{})}appendChangeType(t,e,i){const r=`${e};codecs=${i}`,s={label:`change-type=${r}`,execute:()=>{const s=this.tracks[t];if(s){const n=s.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${r}`),n.changeType(r),s.codec=i,s.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(s,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,r=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,y))?void 0:e.gap))return;const s={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>r||null!=e&&e.buffer&&ti.isBuffered(e.buffer,r)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(r,y))?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:s,frag:t},this.append(s,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:i}=this,{data:r,type:s,parent:n,frag:a,part:o,chunkMeta:h,offset:d}=e,g=h.buffering[s],{sn:m,cc:p}=a,v=self.performance.now();g.start=v;const y=a.stats.buffering,E=o?o.stats.buffering:null;0===y.start&&(y.start=v),E&&0===E.start&&(E.start=v);const T=i.audio;let S=!1;"audio"===s&&"audio/mpeg"===(null==T?void 0:T.container)&&(S=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const A=i.video,L=null==A?void 0:A.buffer;if(L&&"initSegment"!==m){const t=o||a,e=this.blockedAudioAppend;if("audio"!==s||"main"===n||this.blockedAudioAppend||A.ending||A.ended){if("video"===s){const i=t.end;if(e){const t=e.frag.start;(i>t||i<this.lastVideoAppendEnd||ti.isBuffered(L,t))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const e=t.start+.05*t.duration,i=L.buffered,r=this.currentOp("video");i.length||r?!r&&!ti.isBuffered(L,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const R=(o||a).start,I={label:`append-${s}`,execute:()=>{var t;g.executeStart=self.performance.now();const e=null==(t=this.tracks[s])?void 0:t.buffer;e&&(S?this.updateTimestampOffset(e,R,.1,s,m,p):void 0!==d&&l(d)&&this.updateTimestampOffset(e,d,1e-6,s,m,p)),this.appendExecutor(r,s)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();g.executeEnd=g.end=t,0===y.first&&(y.first=t),E&&0===E.first&&(E.first=t);const e={};this.sourceBuffers.forEach((([t,i])=>{t&&(e[t]=ti.getBuffered(i))})),this.appendErrors[s]=0,"audio"===s||"video"===s?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(f.BUFFER_APPENDED,{type:s,frag:a,part:o,chunkMeta:h,parent:a.type,timeRanges:e})},onError:t=>{var e;const i={type:u.MEDIA_ERROR,parent:a.type,details:c.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:o,chunkMeta:h,error:t,err:t,fatal:!1},r=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)i.details=c.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!r)i.errorAction=Ce(!0);else if(t.name===zs&&0===this.sourceBufferCount)i.errorAction=Ce(!0);else{const t=++this.appendErrors[s];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${r||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||r)&&(i.fatal=!0)}this.hls.trigger(f.ERROR,i)}};this.append(I,s,this.isPending(this.tracks[s]))}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(f.BUFFER_FLUSHED,{type:t})},onError:r=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,r)}}}onBufferFlushing(t,e){const{type:i,startOffset:r,endOffset:s}=e;i?this.append(this.getFlushOp(i,r,s),i):this.sourceBuffers.forEach((([t])=>{t&&this.append(this.getFlushOp(t,r,s),t)}))}onFragParsed(t,e){const{frag:i,part:r}=e,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[z]?s.push("audiovideo"):(n[X]&&s.push("audio"),n[Q]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const t=self.performance.now();i.stats.buffering.end=t,r&&(r.stats.buffering.end=t);const e=r?r.stats:i.stats;this.hls.trigger(f.FRAG_BUFFERED,{frag:i,part:r,stats:e,id:i.type})}),s).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 i;this.sourceBuffers.forEach((([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}}));const r=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)}))?r?(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(f.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(f.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===c.BUFFER_APPEND_ERROR&&e.frag){var i;const t=null==(i=e.errorAction)?void 0:i.nextAutoLevel;l(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||null===e)return;if(!this.sourceBufferCount)return;const r=t.config,s=i.currentTime,n=e.levelTargetDuration,a=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(l(a)&&a>=0){const t=Math.max(a,n),e=Math.floor(s/n)*n-t;this.flushBackBuffer(s,n,e)}const o=r.frontBufferFlushThreshold;if(l(o)&&o>0){const t=Math.max(r.maxBufferLength,o),e=Math.max(t,n),i=Math.floor(s/n)*n+e;this.flushFrontBuffer(s,n,i)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach((([t,e])=>{if(e){const s=ti.getBuffered(e);if(s.length>0&&i>s.start(0)){var r;this.hls.trigger(f.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(r=this.details)&&r.live)this.hls.trigger(f.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(f.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}}))}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach((([e,r])=>{if(r){const s=ti.getBuffered(r),n=s.length;if(n<2)return;const a=s.start(n-1),o=s.end(n-1);if(i>a||t>=a&&t<=o)return;this.hls.trigger(f.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}}))}getDurationAndRange(){var t;const{details:e,mediaSource:i}=this;if(!e||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const r=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,r)}}return{duration:1/0}}const s=null==(t=this.overrides)?void 0:t.duration;if(s)return l(s)?{duration:s}:null;const n=this.media.duration;return r>(l(i.duration)?i.duration:0)&&r>n||!l(n)?{duration:r}:null}updateMediaSource({duration:t,start:e,end:i}){const r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==t&&(l(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),r.duration=t),void 0!==e&&void 0!==i&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${e}-${i}.`),r.setLiveSeekableRange(e,i)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${ne(i)}`),this.tracksReady){var r;const t=null==(r=this.transferData)?void 0:r.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach((([e,i])=>{if(e){const r=this.tracks[e];t[e]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}})),this.hls.trigger(f.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(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in t){const n=s,a=t[n];if(this.isPending(a)){const t=this.getTrackCodec(a,n),s=`${a.container};codecs=${t}`;a.codec=t,this.log(`creating sourceBuffer(${s})${this.currentOp(n)?" Queued":""} ${ne(a)}`);try{const t=i.addSourceBuffer(s),r=tn(n),o=[n,t];e[r]=o,a.buffer=t}catch(t){var r;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(r=this.operationQueue)||r.removeBlockers(),delete this.tracks[n],void this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:s,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let r=t.codec;i&&("video"===e||"audiovideo"===e)&&Pt(i,"video")&&(r=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)_t(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(r,i));const s=Ut(r,t.levelCodec);return s?"audio"===e.slice(0,5)?Nt(s,this.appendSource):s:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const r=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:r,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 i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(f.BUFFER_FLUSHED,{type:t})}))}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.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 i=this.currentOp(t);i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;const r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,e),this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const s=this.currentOp(t);s&&s.onError(r)}updateTimestampOffset(t,e,i,r,s,n){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${e} (sn: ${s} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,i){const{media:r,mediaSource:s}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!r||!s||!a)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=l(r.duration)?r.duration:1/0,h=l(s.duration)?s.duration:1/0,d=Math.max(0,e),u=Math.min(i,o,h);u>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${u}] from the ${t} SourceBuffer`),a.remove(d,u)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],r=null==i?void 0:i.buffer;if(!r)throw new Zs(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,r.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch((t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some((([t,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:i}=this,r=e.map((t=>this.appendBlocker(t)));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then((e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(t){t.forEach((t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;i&&!i.updating&&this.shiftAndExecuteNext(t)}))}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}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,i){const r=this.tracks[t];if(!r)return;const s=r.buffer;if(!s)return;const n=i.bind(this,t);r.listeners.push({event:e,listener:n}),s.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach((t=>{i.removeEventListener(t.event,t.listener)})),e.listeners.length=0)}},capLevelController:en,errorController:class extends k{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(f.ERROR,this.onError,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(f.ERROR,this.onError,this),t.off(f.ERROR,this.onErrorOut,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===y?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const r=this.hls,s=e.context;switch(e.details){case c.FRAG_LOAD_ERROR:case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_ERROR:case c.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case c.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=Ce());case c.FRAG_GAP:case c.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ie);case c.LEVEL_EMPTY_ERROR:case c.LEVEL_PARSING_ERROR:{var n;const t=e.parent===y?e.level:r.loadLevel;e.details===c.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 c.LEVEL_LOAD_ERROR:case c.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.level)));case c.AUDIO_TRACK_LOAD_ERROR:case c.AUDIO_TRACK_LOAD_TIMEOUT:case c.SUBTITLE_LOAD_ERROR:case c.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const t=r.loadLevelObj;if(t&&(s.type===p&&t.hasAudioGroup(s.groupId)||s.type===v&&t.hasSubtitleGroup(s.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Ie,void(e.errorAction.flags=_e)}return;case c.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.loadLevelObj,i=null==t?void 0:t.attrs["HDCP-LEVEL"];i?e.errorAction={action:Ie,flags:Pe,hdcpLevel:i}:this.keySystemError(e)}return;case c.BUFFER_ADD_CODEC_ERROR:case c.REMUX_ALLOC_ERROR:case c.BUFFER_APPEND_ERROR:var a;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(a=e.level)?a:r.loadLevel);return;case c.INTERNAL_EXCEPTION:case c.BUFFER_APPENDING_ERROR:case c.BUFFER_FULL_ERROR:case c.LEVEL_SWITCH_ERROR:case c.BUFFER_STALLED_ERROR:case c.BUFFER_SEEK_OVER_HOLE:case c.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=Ce())}e.type===u.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const i=Te(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(Le(i,r,Ee(t),t.response))return{action:ke,flags:De,retryConfig:i,retryCount:r};const s=this.getLevelSwitchAction(t,e);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),r=e.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=e.config,a=Te(t.details.startsWith("key")?n:s,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(r){t.details!==c.FRAG_GAP&&r.fragmentError++;if(Le(a,o,Ee(t),t.response))return{action:ke,flags:De,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const r=this.hls.levels[e];if(r){var s,n;const e=t.details;r.loadError++,e===c.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:u,maxAutoLevel:f}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const g=null==(s=t.frag)?void 0:s.type,m=(g===E&&e===c.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===c.BUFFER_ADD_CODEC_ERROR||e===c.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:t})=>r.audioCodec!==t)),S="video"===t.sourceBufferName&&(e===c.BUFFER_ADD_CODEC_ERROR||e===c.BUFFER_APPEND_ERROR)&&h.some((({codecSet:t,audioCodec:e})=>r.codecSet!==t&&r.audioCodec===e)),{type:A,groupId:L}=null!=(n=t.context)?n:{};for(let i=h.length;i--;){const s=(i+d)%h.length;if(s!==d&&s>=u&&s<=f&&0===h[s].loadError){var a,o;const i=h[s];if(e===c.FRAG_GAP&&g===y&&t.frag){const e=h[s].details;if(e){const i=me(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(A===p&&i.hasAudioGroup(L)||A===v&&i.hasSubtitleGroup(L))continue;if(g===E&&null!=(a=r.audioGroups)&&a.some((t=>i.hasAudioGroup(t)))||g===T&&null!=(o=r.subtitleGroups)&&o.some((t=>i.hasSubtitleGroup(t)))||m&&r.audioCodec===i.audioCodec||S&&r.codecSet===i.codecSet||!m&&r.codecSet!==i.codecSet)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ie,flags:De,nextAutoLevel:l}}return{action:Ie,flags:_e}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case Re:break;case Ie:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===c.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}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:r,hdcpLevel:s,nextAutoLevel:n}=i;switch(r){case De:this.switchLevel(t,n);break;case Pe:s&&(e.maxHdcpLevel=Xt[Xt.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(t,n)}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===c.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Kt(t.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${t.sourceBufferName}Codec`]===e&&this.hls.removeLevel(r)}}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(f.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(f.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.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),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const r=performance.now();if(e){if(this.lastTime){const t=r-this.lastTime,s=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*s/t,o=this.hls;if(o.trigger(f.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>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(f.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,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)}},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:bi,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:ko,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends ur{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",T),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(f.LEVEL_LOADED,this.onLevelLoaded,this),t.on(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(f.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(f.LEVEL_LOADED,this.onLevelLoaded,this),t.off(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(f.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=dr.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:i,success:r}=e;if(this.fragContextChanged(i)||(J(i)&&(this.fragPrevious=i),this.state=dr.IDLE),!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=i.start;for(let t=0;t<s.length;t++)if(a>=s[t].start&&a<=s[t].end){n=s[t];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:i,endOffset:r}=e;if(0===i&&r!==Number.POSITIVE_INFINITY){const t=r-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}})),this.fragmentTracker.removeFragmentsInRange(i,t,T)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===T&&(e.details===c.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dr.STOPPED&&(this.state=dr.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Ws(this.levels,e)?this.levels=e.map((t=>new ie(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new ie(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,T),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==dr.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:r,levels:s}=this,{details:n,id:a}=e;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[a];if(a>=s.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!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,Zi(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(lr(n,t),l=n.fragmentStart):e&&(l=e.start,Zi(n,l));t&&!this.startFragRequested&&this.setStartPosition(t,l)}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(f.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===dr.IDLE)){me(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:i}=t,r=e.decryptdata,s=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&ci(r.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,fi(r.method)).catch((t=>{throw s.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((i=>{const r=performance.now();s.trigger(f.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:r}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=dr.IDLE}))}}doTick(){if(this.media){if(this.state===dr.IDLE){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;if(this.waitForLive(i))return;const{config:r}=this,s=this.getLoadPosition(),n=ti.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const h=l.fragments,d=h.length,u=l.edge;let c=null;const f=this.fragPrevious;if(a<u){const t=r.maxFragLookUpTolerance,e=a>u-t?0:t;c=me(f,h,Math.max(h[0].start,a),e),!c&&f&&f.start<h[0].start&&(c=h[0])}else c=h[d-1];if(c=this.filterReplacedPrimary(c,i.details),!c)return;const g=h[c.sn-l.startSN-1];if(g&&g.cc===c.cc&&this.fragmentTracker.getState(g)===we&&(c=g),this.fragmentTracker.getState(c)===we){const t=this.mapToInitFragWhenRequired(c);t&&this.loadFragment(t,i,a)}}}else this.state=dr.IDLE}loadFragment(t,e,i){J(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Pa(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Ys{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=ma(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 i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.MANIFEST_PARSED,this.onManifestParsed,this),t.on(f.LEVEL_LOADING,this.onLevelLoading,this),t.on(f.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.MANIFEST_PARSED,this.onManifestParsed,this),t.off(f.LEVEL_LOADING,this.onLevelLoading,this),t.off(f.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(f.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 i=this.media;if(!i)return;const r=!!e.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;ma(i.textTracks).forEach((t=>{fa(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:i,groupId:r,details:s}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,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 i=e.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.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(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!s&&e){this.selectDefaultTrack=!1;const i=he(e,t);if(i>-1)s=t[i];else{const t=he(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(f.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<e.length;r++){const s=e[r];if((!i||s.default)&&(i||t)&&(!t||de(s,t)))return r}if(t){for(let i=0;i<e.length;i++){const r=e[i];if(js(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(js(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(qs(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==v||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 i=this.currentTrack;if(i&&de(t,i))return i;const r=he(t,this.tracksInGroup);if(r>-1){const t=this.tracksInGroup[r];return this.setSubtitleTrack(r),t}if(i)return null;{const i=he(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,r=t.groupId,s=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${r}${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||0:""):""} ${s}`),this.hls.trigger(f.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=ma(t.textTracks),i=this.currentTrack;let r;if(i&&(r=e.filter((t=>qs(i,t)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==r&&(t.mode="disabled")})),r){const t=this.subtitleDisplay?"showing":"hidden";r.mode!==t&&(r.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!l(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(f.SUBTITLE_TRACK_SWITCH,{id:t});const s=!!r.details&&!r.details.live;if(t===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:h,url:d}=r;this.hls.trigger(f.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:h,url:d});const u=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(u)}},timelineController:Lo,audioStreamController:class extends ur{constructor(t,e,i){super(t,e,i,"audio-stream-controller",E),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(f.LEVEL_LOADED,this.onLevelLoaded,this),t.on(f.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(f.BUFFER_RESET,this.onBufferReset,this),t.on(f.BUFFER_CREATED,this.onBufferCreated,this),t.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(f.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(f.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(f.FRAG_LOADING,this.onFragLoading,this),t.on(f.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(f.LEVEL_LOADED,this.onLevelLoaded,this),t.off(f.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(f.BUFFER_RESET,this.onBufferReset,this),t.off(f.BUFFER_CREATED,this.onBufferCreated,this),t.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(f.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(f.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(f.FRAG_LOADING,this.onFragLoading,this),t.off(f.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:s,trackId:n}){if(i===y){const t=e.cc,i=this.fragCurrent;if(this.initPTS[t]={baseTime:r,timescale:s,trackId:n},this.log(`InitPTS for cc: ${t} found from main: ${r/s} (${r}/${s}) trackId: ${n}`),this.mainAnchor=e,this.state===dr.WAITING_INIT_PTS){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==t)&&this.syncWithAnchor(e,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==t?(i.abortRequests(),this.syncWithAnchor(e,i)):this.state===dr.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==r?void 0:r.cc)===e.cc)return;const s=(r||t).cc,n=ye(this.getLevelDetails(),s,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===dr.IDLE&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=dr.STOPPED);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=dr.IDLE):this.state=dr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case dr.IDLE:this.doTickIdle();break;case dr.WAITING_TRACK:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=dr.WAITING_INIT_PTS}break}case dr.FRAG_LOADING_WAITING_RETRY:{var t;const e=performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=dr.IDLE}break}case dr.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:r,complete:s}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=dr.FRAG_LOADING;const t={frag:e,part:i,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),s&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=dr.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:i,media:r,trackId:s}=this,n=e.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[s])return;const a=i[s],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=dr.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,X,E));const h=this.getFwdBufferInfo(l,E);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return e.trigger(f.BUFFER_EOS,{type:"audio"}),void(this.state=dr.ENDED);const d=h.len,u=e.maxBufferLength,c=o.fragments,g=c[0].start,m=this.getLoadPosition(),p=this.flushing?m:h.end;if(this.switchingTrack&&r){const t=m;o.PTSKnown&&t<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=g+.05)}if(d>=u&&!this.switchingTrack&&p<c[c.length-1].start)return;let v=this.getNextFragment(p,o);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,o,h,y,u)),!v)return void(this.bufferFlushed=!0);let T=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&J(v)&&!v.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===Me&&(this.mainFragLoading=T=null),T&&J(T))){if(v.start>T.end){const t=this.fragmentTracker.getFragAtPos(p,y);t&&t.end>T.end&&(T=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,a,p)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map((t=>new ie(t)))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==dr.STOPPED&&(this.setInterval(100),this.state=dr.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 i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(f.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:r}=this,{details:s,id:n,groupId:a,track:o}=e;if(!r)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||s.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==dr.STOPPED&&(this.state=dr.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const h=r[n];let d=0;if(s.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;var u;if(h.details)d=this.alignPlaylists(s,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);s.alignedSliding||(or(s,l),s.alignedSliding||lr(s,l),d=s.fragmentStart)}h.details=s,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(f.AUDIO_TRACK_UPDATED,{details:s,id:n,groupId:e.groupId}),this.state!==dr.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=dr.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:r,payload:s}=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 ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Hs(this.hls,E,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const c=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==c){const t=!1,e=r?r.index:-1,n=-1!==e,a=new Ze(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,n);u.push(s,f,d,"",i,r,h.totalduration,t,a,c)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new fr,complete:!1};t.push(new Uint8Array(s)),this.state!==dr.STOPPED&&(this.state=dr.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 i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===y&&J(e.frag)&&(this.mainFragLoading=e,this.state===dr.IDLE&&this.tick())}onFragBuffered(t,e){const{frag:i,part:r}=e;if(i.type===E)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(J(i)){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(f.AUDIO_TRACK_SWITCHED,b({},t)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==y||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var i;if(e.fatal)this.state=dr.ERROR;else switch(e.details){case c.FRAG_GAP:case c.FRAG_PARSING_ERROR:case c.FRAG_DECRYPT_ERROR:case c.FRAG_LOAD_ERROR:case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_ERROR:case c.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(E,e);break;case c.AUDIO_TRACK_LOAD_ERROR:case c.AUDIO_TRACK_LOAD_TIMEOUT:case c.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==dr.WAITING_TRACK||(null==(i=e.context)?void 0:i.type)!==p||(this.state=dr.IDLE);break;case c.BUFFER_ADD_CODEC_ERROR:case c.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case c.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case c.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Q&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Q){this.flushing=!1,this.bufferFlushed=!0,this.state===dr.ENDED&&(this.state=dr.IDLE);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,E),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:u,text:c,id3:g,initSegment:m}=s;if(!this.fragContextChanged(o)&&d){if(this.state=dr.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(m,o))return;this._bufferInitSegment(h,m.tracks,t,n),r.trigger(f.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:m.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=u;l&&(l.elementaryStreams[X]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(X,t,e,i,r),this.bufferFragmentData(u,o,l,n)}if(null!=g&&null!=(e=g.samples)&&e.length){const t=R({id:i,frag:o,details:d},g);r.trigger(f.FRAG_PARSING_METADATA,t)}if(c){const t=R({id:i,frag:o,details:d},c);r.trigger(f.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,i,r){if(this.state!==dr.PARSING)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const s=e.audio;s.id=E;const n=t.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(f.BUFFER_CODECS,e);const a=s.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(f.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);var s;if(this.switchingTrack||r===we||r===xe)if(J(t))if(null!=(s=e.details)&&s.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=dr.WAITING_INIT_PTS;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&lr(e.details,i)}else super.loadFragment(t,e,i);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:i,assocLang:r,characteristics:s,audioCodec:n,channels:a}=this.bufferedTrack;de({name:e,lang:i,assocLang:r,characteristics:s,audioCodec:n,channels:a},t,ue)||(fe(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(f.AUDIO_TRACK_SWITCHED,b({},t))}},audioTrackController:class extends Ys{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(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.MANIFEST_PARSED,this.onManifestParsed,this),t.on(f.LEVEL_LOADING,this.onLevelLoading,this),t.on(f.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.MANIFEST_PARSED,this.onManifestParsed,this),t.off(f.LEVEL_LOADING,this.onLevelLoading,this),t.off(f.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(f.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:i,groupId:r,details:s}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,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 i=e.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.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(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!s&&e){const i=he(e,t,ue);if(i>-1)s=t[i];else{const t=he(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(f.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);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(f.ERROR,{type:u.MEDIA_ERROR,details:c.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==p||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 i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&de(t,r,ue))return r;const s=he(t,this.tracksInGroup,ue);if(s>-1){const t=this.tracksInGroup[s];return this.setAudioTrack(s),t}if(r){let r=e.loadLevel;-1===r&&(r=e.firstAutoLevel);const s=function(t,e,i,r,s){const n=e[r],a=e.reduce(((t,e,i)=>{const r=e.uri;return(t[r]||(t[r]=[])).push(i),t}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=ce(e,r,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const r=e.audioGroups,n=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return he(t,n,s)>-1}));return d>-1?d:ce(e,r,(e=>{const r=e.audioGroups,n=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return he(t,n,s)>-1}))}(t,e.levels,i,r,ue);if(-1===s)return null;e.nextLoadLevel=s}if(t.channels||t.audioCodec){const e=he(t,i);if(e>-1)return i[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 i=this.currentTrack,r=e[t],s=r.details&&!r.details.live;if(t===this.trackId&&r===i&&s)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(f.AUDIO_TRACK_SWITCHING,b({},r)),s)return;const n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const r=e[i];if((!this.selectDefaultTrack||r.default)&&(!t||de(t,r,ue)))return i}if(t){const{name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(de({name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o},e[t],ue))return t}for(let i=0;i<e.length;i++){const r=e[i];if(js(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(js(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&fe(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,r=t.groupId,s=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${r}${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||0:""):""} ${s}`),this.hls.trigger(f.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null,track:t})}},emeController:ha,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:rn.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:e,part:i}=t,r=this.hls.levels[e.level],s=this.getObjectType(e),n={d:1e3*(i||e).duration,ot:s};s!==rn.VIDEO&&s!==rn.AUDIO&&s!=rn.MUXED||(n.br=r.bitrate/1e3,n.tb=this.getTopBandwidth(s)/1e3,n.bl=this.getBufferLength(s));const a=i?this.getNextPart(i):this.getNextFrag(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||t.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(f.MEDIA_DETACHED,this.onMediaDetached,this),t.on(f.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(f.MEDIA_DETACHED,this.onMediaDetached,this),t.off(f.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 i,r;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:sn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){R(e,this.createData());const i=e.ot===rn.INIT||e.ot===rn.VIDEO||e.ot===rn.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:r}=this;r&&(e=Object.keys(e).reduce(((t,i)=>(r.includes(i)&&(t[i]=e[i]),t)),{}));const s={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),ta(t.headers,e,s)):t.url=sa(t.url,e,s)}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:r}=t,s=null==(e=this.hls.levels[r.level])||null==(e=e.details)?void 0:e.partList;if(s){const{sn:t}=r;for(let e=s.length-1;e>=0;e--){const r=s[e];if(r.index===i&&r.fragment.sn===t)return s[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?rn.TIMED_TEXT:"initSegment"===t.sn?rn.INIT:"audio"===e?rn.AUDIO:"main"===e?this.hls.audioTracks.length?rn.VIDEO:rn.MUXED:void 0}getTopBandwidth(t){let e,i=0;const r=this.hls;if(t===rn.AUDIO)e=r.audioTracks;else{const t=r.maxAutoLevel,i=t>-1?t+1:r.levels.length;e=r.levels.slice(0,i)}return e.forEach((t=>{t.bitrate>i&&(i=t.bitrate)})),i>0?i:NaN}getBufferLength(t){const e=this.media,i=t===rn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*ti.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}},contentSteeringController: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(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(f.MANIFEST_PARSED,this.onManifestParsed,this),t.on(f.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(f.MANIFEST_PARSED,this.onManifestParsed,this),t.off(f.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:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===Ie&&i.flags===_e){const t=this.levels;let r=this._pathwayPriority,s=this.pathwayId;if(e.context){const{groupId:i,pathwayId:r,type:n}=e.context;i&&t?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&t&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),e.details!==c.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${s} levels: ${t?t.length:t} priorities: ${ne(r)} penalized: ${ne(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}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 i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((t=>{r-i[t]>3e5&&delete i[t]}));for(let r=0;r<t.length;r++){const s=t[r];if(s in i)continue;if(s===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(s),e.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,rr(e),this.hls.trigger(f.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,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(e===p&&r[i].hasAudioGroup(t)||e===v&&r[i].hasSubtitleGroup(t))return r[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},r={};t.forEach((t=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new li(t.attrs);e["PATHWAY-ID"]=s;const n=e.AUDIO&&`${e.AUDIO}_clone_${s}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${s}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(r[e.SUBTITLES]=o,e.SUBTITLES=o);const l=aa(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new ie({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 e=1;e<t.audioGroups.length;e++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${s}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${s}`);return h}));e.push(...o),na(this.audioTracks,i,a,s),na(this.subtitleTracks,r,a,s)}))}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let r;this.loader&&this.loader.destroy(),this.loader=new i(e);try{r=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==r.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+t)}const s={responseType:"json",url:r.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,i,s)=>{this.log(`Loaded steering manifest: "${r}"`);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,r).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(f.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,i,r)=>{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 s=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,s);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(s=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}},interstitialsController: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 i=e<=-.01;this.timelinePos=t,this.bufferedPos=t;const r=this.playingItem;if(!r)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<r.start||t>=r.end){var s;const e=this.findItemIndex(r);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(r)&&null!=(s=this.media)&&s.paused&&(this.shouldPlay=!1),!i&&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(r)){const e=r.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;(i&&t<a||t>=a+o)&&(null!=(l=r.event)&&l.appendInPlace&&(this.clearInterstitial(r.event,r),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 i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const r=this.playingItem,s=i.events||[],n=i.items||[],a=i.durations,o=t.map((t=>t.identifier)),l=!(!s.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s}\nSchedule: ${n.map((t=>ka(t)))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let h=null,d=null;r&&(h=this.updateItem(r,this.timelinePos),this.itemsMatch(r,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u&&(d=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,d)?this.bufferingItem=d:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach((t=>{t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,null)}))})),this.playerQueue.forEach((t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(r){Math.abs(i)>va&&this.warn(`${r} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}})),l||e){if(this.hls.trigger(f.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(r)&&o.includes(r.event.identifier))return this.warn(`Interstitial "${r.event.identifier}" removed while playing`),void this.primaryFallback(r.event);r&&this.trimInPlace(h,r),u&&this.trimInPlace(d,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Da(t),this.schedule=new ba(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(f.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(f.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(f.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(f.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(f.BUFFER_APPENDED,this.onBufferAppended,this),t.on(f.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(f.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(f.MEDIA_ENDED,this.onMediaEnded,this),t.on(f.ERROR,this.onError,this),t.on(f.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(f.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(f.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(f.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(f.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(f.BUFFER_CODECS,this.onBufferCodecs,this),t.off(f.BUFFER_APPENDED,this.onBufferAppended,this),t.off(f.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(f.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(f.MEDIA_ENDED,this.onMediaEnded,this),t.off(f.ERROR,this.onError,this),t.off(f.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){la(t,"play",this.onPlay),la(t,"pause",this.onPause),la(t,"seeking",this.onSeeking),la(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;oa(i,"seeking",this.onSeeking),oa(i,"timeupdate",this.onTimeupdate),oa(i,"play",this.onPlay),oa(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,r=(e,r,n,a,o)=>{if(e){let l=e[r].start;const h=e.event;if(h){if("playout"===r||h.timelineOccupancy!==ya.Point){const t=i(n);(null==t?void 0:t.interstitial)===h&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?s():t[a])-e.start}return l}return 0},s=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,r;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(r=t.schedule)?void 0:r.durations[e])||0},a=(e,s)=>{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} "${s}"`);const l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,s),d=null==(a=t.schedule.items)?void 0:a[h],u=t.getBufferingPlayer(),c=null==u?void 0:u.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&t.itemsMatch(l,d);if(l&&(f||g)){const n=i(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const i="primary"===s?a.currentTime:r(l,s,t.playingAsset,"timelinePos","currentTime"),o=e-i,h=(f?i:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let i=e;if("primary"!==s){const t=e-d[s].start;i=d.start+t}const r=!t.isInterstitial(d);if(t.isInterstitial(l)&&!l.event.appendInPlace||!r&&!d.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(h>n){const e=t.schedule.findJumpRestrictedIndex(n+1,h);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(r)t.timelinePos=i,t.checkBuffer();else{const t=d.event.assetList,i=e-(d[s]||d).start;for(let e=t.length;e--;){const r=t[e];if(r.duration&&i>=r.startOffset&&i<r.startOffset+r.duration){a=e;break}}}t.setSchedulePosition(h,a)}}else{const e=t.media||(f?null==u?void 0:u.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const r=e();return t.isInterstitial(r)?r:null},l={get bufferedEnd(){const i=e(),s=t.bufferingItem;var n;return s&&s===i&&(r(s,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-s.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?r(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),r=t.effectivePlayingItem;r&&r===i&&a(e+r.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map((e=>t.getAssetPlayer(e.identifier))):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.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 i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return s()},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 r(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){var e;return((e,i)=>{var r;if(0!==e&&"primary"!==i&&null!=(r=t.schedule)&&r.length){var s;const r=t.schedule.findItemIndexAtTime(e),n=null==(s=t.schedule.items)?void 0:s[r];if(n)return e+(n[i].start-n.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const r=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,r,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,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(r=this.primaryMedia);const s=null==(e=r)?void 0:e.currentTime;return void 0!==s&&l(s)?s: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 i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,r=t.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&r)return void(this.detachedData={media:r});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${ne(i)}`),this.detachedData=i}else e&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(t,e){var i,r;if(t.media===e)return;let s=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let h;if(n.media)o&&(s=n.transferMedia(),this.detachedData=s),h="Primary";else if(l){const t=this.getBufferingPlayer();t?(s=t.transferMedia(),h=`${t}`):h="detached MediaSource"}else h="detached media";if(!s)if(l)s=this.detachedData,this.log(`using detachedData: MediaSource ${ne(s)}`);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 d=s&&"mediaSource"in s&&"closed"!==(null==(r=s.mediaSource)?void 0:r.readyState),u=d&&s?s:e;this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${h} (media.currentTime: ${e.currentTime})`);const c=this.schedule;if(u===s&&c){const e=a&&t.assetId===c.assetIdAtEnd;u.overrides={duration:c.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(u)}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 i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.timelinePos=i,e.length&&e[0].cue.pre){const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const e=this.timelinePos=i>0?i:0,r=t.findItemIndexAtTime(e);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){const e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,r=i.findAssetIndex(e),s=La(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var n;const e=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,s)}advanceAfterAssetEnded(t,e,i){const r=La(t,i);if(t.isAssetPastPlayoutLimit(r)){if(this.schedule){const i=this.schedule.items;if(i){const r=e+1;if(r>=i.length)return void this.setSchedulePosition(-1);const s=t.resumeTime;this.timelinePos<s&&(this.timelinePos=s,t.appendInPlace&&this.advanceInPlace(s),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){const e=t.assetList[r];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,r)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const r=e.parentIdentifier,s=i.getEvent(r);if(s){const e=i.findEventIndex(r),n=i.findAssetIndex(s,t);this.advanceAfterAssetEnded(s,e,n-1)}}setSchedulePosition(t,e){var i;const r=null==(i=this.schedule)?void 0:i.items;if(!r||this.playbackDisabled)return;const s=t>=0?r[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${s?ka(s):s})`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,h=this.playingAsset,d=null==h?void 0:h.identifier,u=d?this.getAssetPlayer(d):null;if(u&&d&&(!this.eventItemsMatch(n,s)||void 0!==e&&d!==i.assetList[e].identifier)){var o;const e=i.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${Ra(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(f.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:e,event:i,schedule:r.slice(0),scheduleIndex:t,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(d,s),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${ka(n)}`),i.hasPlayed=!0,this.hls.trigger(f.INTERSTITIAL_ENDED,{event:i,schedule:r.slice(0),scheduleIndex:t}),i.cue.once)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(s&&t){const i=this.findItemIndex(s);this.advanceSchedule(i,t,e,n,a)}return}}this.advanceSchedule(t,r,e,n,a)}advanceSchedule(t,e,i,r,s){const n=this.schedule;if(!n)return;const a=t>=0?e[t]:null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach((e=>{const i=e.interstitial,r=n.findEventIndex(i.identifier);(r<t||r>t+1)&&this.clearInterstitial(i,a)})),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const s=a.event;if(void 0===i){const e=La(s,(i=n.findAssetIndex(s,this.timelinePos))-1);if(s.isAssetPastPlayoutLimit(e)||s.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(s,t,i);i=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(s,i);if(this.eventItemsMatch(a,l||r)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${ka(a)} ${s.appendInPlace?"append in place":""}`),this.hls.trigger(f.INTERSTITIAL_STARTED,{event:s,schedule:e.slice(0),scheduleIndex:t})),!s.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${s}`);if(s.assetListLoader&&(s.assetListLoader.destroy(),s.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${s}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const d=s.assetList[i];if(!d)return void this.advanceAfterAssetEnded(s,t,i||0);if(h||(h=this.getAssetPlayer(d.identifier)),null===h||h.destroyed){const t=s.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${s}`),h=this.createAssetPlayer(s,d,i),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&s.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,i,e,t,o),this.shouldPlay&&_a(h.media)}else null!==a?(this.resumePrimary(a,t,r),this.shouldPlay&&_a(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.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,i){var r,s;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${ka(t)}`),null==(r=this.detachedData)||!r.mediaSource){let i=this.timelinePos;(i<t.start||i>=t.end)&&(i=this.getPrimaryResumption(t,e),this.timelinePos=i),this.attachPrimary(i,t)}if(!i)return;const n=null==(s=this.schedule)?void 0:s.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ka(t)}`),this.hls.trigger(f.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const i=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(i<t.fragmentStart||i>t.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return ti.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const r=this.primaryMedia;if(!r)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(t,i)),i||(this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;const r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-t)>.5?r.startLoad(t,e):r.bufferingEnabled||r.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(f.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(f.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level],r=b(b({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],r=this.mediaSelection;if(!r)return void(this.altSelection=b(b({},this.altSelection),{},{audio:i}));const s=b(b({},r),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],r=this.mediaSelection;if(!r)return void(this.altSelection=b(b({},this.altSelection),{},{subtitles:i}));const s=b(b({},r),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(t,e){const i=le(e);this.playerQueue.forEach((({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i))))}onSubtitleTrackSwitch(t,e){const i=le(e);this.playerQueue.forEach((({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i))))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,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 r=e[t];if(r.cue.post){var i;const t=this.schedule.findEventIndex(r.identifier),e=null==(i=this.schedule.items)?void 0:i[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 i;const r=null==(i=this.schedule)?void 0:i.items;if(t&&r){return r[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach(((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)}));const e=t.end+.25,i=ti.bufferInfo(this.primaryMedia,e,0);(i.end>e||(i.nextStart||0)>e)&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}}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 i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const r=ti.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=r.len<1),this.updateBufferedPos(r.end,i,t)}updateBufferedPos(t,e,i){const r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>t||!r)return;if(1===e.length&&this.itemsMatch(e[0],s))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=r.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(s),r=Math.min(i+1,e.length-1),n=e[r];if((-1===o&&s&&t>=s.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=r),this.isInterstitial(s)){const t=s.event;if(r-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&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 i&&n&&!this.itemsMatch(n,s)&&(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 i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))}))}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:r,events:s}=i;if(!r||!s)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 ${ka(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach(((t,i)=>{const r=this.getAssetPlayer(t.identifier);r&&(i===e&&r.loadSource(),r.resumeBuffering())}))}else this.hls.resumeBuffering(),this.playerQueue.forEach((t=>t.pauseBuffering()));this.hls.trigger(f.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.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 i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.detachedData;if(e)if(e.mediaSource){const e=!0;this.attachPrimary(t.start,t,e)}else this.preloadPrimary(t);else this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){const i=t.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,r=t.assetList.length,s=0===r&&!t.assetListLoader,n=t.cue.once;if(s){const s=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(s+.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-s;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:r} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(t,0,0,s,t.duration,i);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&r){for(let i=e;i<r;i++){const e=t.assetList[i],r=this.getAssetPlayerQueueIndex(e.identifier);-1!==r&&!this.playerQueue[r].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach((e=>{this.hls.trigger(f.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})}))}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;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 i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,r,s,n){const a={parentIdentifier:t.identifier,identifier:Ea(t,n,e),duration:s,startOffset:i,timelineStart:r,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const r=this.hls,s=r.userConfig;let n=s.videoPreference;const a=r.loadLevelObj||r.levels[r.currentLevel];(n||a)&&(n=R({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=r.audioTracks[r.audioTrack],l=r.subtitleTracks[r.subtitleTrack];let h=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const i=e.duration;i&&t<i&&(h=t)}}const d=e.identifier,g=b(b({},s),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||s.audioPreference,subtitlePreference:l||s.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(g.timelineOffset=e.timelineStart));const m=g.cmcd;null!=m&&m.sessionId&&m.contentId&&(g.cmcd=R({},m,{contentId:pa(e.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${t} and asset ${d}`);const p=new Ia(this.HlsPlayerClass,g,t,e);this.playerQueue.push(p),t.assetList[i]=e;let v=!0;const y=r=>{if(r.live){var s;const e=new Error(`Interstitials MUST be VOD assets ${t}`),r={fatal:!0,type:u.OTHER_ERROR,details:c.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=(null==(s=this.schedule)?void 0:s.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(r,t,n,i,e.message)}const n=r.edge-r.fragmentStart,a=e.duration;(v||null===a||n>a)&&(v=!1,this.log(`Interstitial asset "${d}" duration change ${a} > ${n}`),e.duration=n,this.updateSchedule())};p.on(f.LEVEL_UPDATED,((t,{details:e})=>y(e))),p.on(f.LEVEL_PTS_UPDATED,((t,{details:e})=>y(e))),p.on(f.EVENT_CUE_ENTER,(()=>this.onInterstitialCueEnter()));const E=(t,e)=>{const i=this.getAssetPlayer(d);if(i&&e.tracks){i.off(f.BUFFER_CODECS,E),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};p.on(f.BUFFER_CODECS,E);p.on(f.BUFFERED_TO_END,(()=>{var i;const r=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${r}`),!r||!this.schedule)return;const s=this.schedule.findEventIndex(t.identifier),n=null==(i=this.schedule.items)?void 0:i[s];this.isInterstitial(n)&&this.advanceAssetBuffering(n,e)}));const T=e=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return p.once(f.MEDIA_ENDED,T(i)),p.once(f.PLAYOUT_LIMIT_REACHED,T(1/0)),p.on(f.ERROR,((e,r)=>{if(!this.schedule)return;const s=this.getAssetPlayer(d);if(r.details===c.BUFFER_STALLED_ERROR)return null!=s&&s.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(r,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${r.error} ${t}`)})),p.on(f.DESTROYING,(()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${d}`),r={fatal:!0,type:u.OTHER_ERROR,details:c.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(r,t,this.schedule.findEventIndex(t.identifier),i,e.message)})),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ra(e)}`),this.hls.trigger(f.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:p}),p}clearInterstitial(t,e){t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,e)})),t.reset()}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){this.log(`clear asset player "${t}" toSegment: ${e?ka(e):e}`);const r=this.playerQueue[i];this.transferMediaFromPlayer(r,e),this.playerQueue.splice(i,1),r.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,r,s){const{interstitial:n,assetItem:a,assetId:o}=t,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${Ra(a)}`),this.hls.trigger(f.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:r,player:t})),this.bufferAssetPlayer(t,s)}bufferAssetPlayer(t,e){var i,r;if(!this.schedule)return;const{interstitial:s,assetItem:n}=t,a=this.schedule.findEventIndex(s.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(!o)return;t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===t)return;const h=s.appendInPlace;if(h&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const d=(null==l?void 0:l.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(d&&!M(d,t.tracks)){const e=new Error(`Asset ${Ra(n)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),i={fatal:!0,type:u.OTHER_ERROR,details:c.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},r=s.findAssetIndex(n);return void this.handleAssetItemError(i,s,a,r,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const r=i.currentTime,s=e.findAssetIndex(t,r),n=t.assetList[s];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||r-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${r})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,s)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,i,r,s){if(t.details===c.BUFFER_STALLED_ERROR)return;const n=e.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Ra(n):n} ${t.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,d=R({},t,{fatal:!1,errorAction:Ce(!0),asset:n,assetListIndex:r,event:e,schedule:h,scheduleIndex:i,player:l});if(this.hls.trigger(f.INTERSTITIAL_ASSET_ERROR,d),!t.fatal)return;const u=this.playingAsset,g=this.bufferingAsset,m=new Error(s);if(n&&(this.clearAssetPlayer(a,null),n.error=m),e.assetList.some((t=>!t.error)))for(let t=r;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=m;this.updateSchedule(!0),e.error?this.primaryFallback(e):u&&u.identifier===a?this.advanceAfterAssetEnded(e,i,r):g&&g.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem;if(i){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${this.timelinePos} playing: ${ka(i)} error: ${t.error}`);let r=this.timelinePos;-1===r&&(r=this.hls.startPosition);const s=this.updateItem(i,r);if(this.itemsMatch(i,s)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e)),!this.schedule)return;const n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}else this.checkStart()}onAssetListLoaded(t,e){var i,r;const s=e.event,n=s.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=s.timelineStart,l=s.duration;let h=0;a.forEach(((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(s,e,h,o+h,i,t.URI),h+=i})),s.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${s}`);const d=this.waitingItem,u=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const c=null==(r=this.bufferingItem)?void 0:r.event;if(u){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){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return s.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${s}`),this.updateSchedule(!0),void this.primaryFallback(s)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==c?void 0:c.identifier)===n){const t=s.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(c.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 c.ASSET_LIST_PARSING_ERROR:case c.ASSET_LIST_LOAD_ERROR:case c.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case c.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}}}}});function Mo(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Mo):Object.keys(t).reduce(((e,i)=>(e[i]=Mo(t[i]),e)),{}):t}function Fo(t,e){const i=t.loader;if(i!==_o&&i!==Oo)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=_o,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class No extends ze{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(f.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.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 i=this.media=e.media;oa(i,"playing",this.onMediaPlaying),oa(i,"waiting",this.onMediaWaiting),oa(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(la(i,"playing",this.onMediaPlaying),la(i,"waiting",this.onMediaWaiting),la(i,"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 i,r;const s=null==(i=this.hls)?void 0:i.config;if(!s)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=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,s.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(h)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(f.MEDIA_ENDED,{stalled:!1})));if(!ti.getBuffered(n).length)return void(this.nudgeRetry=0);const d=ti.bufferInfo(n,t,0),u=d.nextStart||0,c=this.fragmentTracker;if(a&&c&&this.hls){const e=Uo(this.hls.inFlightFragments,t),i=d.len>2,r=!u||e||u-t>2&&!c.getPartialFragment(t);if(i||r)return;this.moved=!1}const g=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(d.len>0)&&!u)return;const e=Math.max(u,d.start||0)-t,i=!(null==g||!g.live)?2*g.targetduration:2,r=Go(t,c);if(e>0&&(e<=i||r))return void(n.paused||this._trySkipBufferHole(r))}const m=s.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&p-v<m))return void(this.stalled=p);y=this.stalled=v}const E=p-y;if(!a&&(E>=m||v)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(f.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}const S=ti.bufferInfo(n,t,s.maxBufferHole);this._tryFixBufferStall(S,E,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(f.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&t>r.end(0)){const i=ti.bufferedInfo(ti.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=ti.timeRangesToArray(r),s=ti.bufferedInfo(i,e,0).bufferedIndex;if(s>-1&&s<i.length-1){const e=ti.bufferedInfo(i,t,0).bufferedIndex,r=i[s].end,n=i[s+1].start;if((-1===e||e>s)&&n-r<1&&t-r<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${r} -> ${n} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let s=Go(t,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);const a=ti.bufferInfo(this.media,t,0);this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:s,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,i){var r,s;const{fragmentTracker:n,media:a}=this,o=null==(r=this.hls)?void 0:r.config;if(!a||!n||!o)return;const l=null==(s=this.hls)?void 0:s.latestLevelDetails,h=Go(i,n);if(h||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=t.buffered,u=this.adjacentTraversal(t,i);(d&&d.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,r=t.nextStart;if(i&&r){const t=i.getFragAtPos(e,y),s=i.getFragAtPos(r,y);if(t&&s)return s.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:r,stalled:s}=this;if(!r&&null!==s&&i&&e){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ne(t)})`);this.warn(r.message),e.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len,bufferInfo:t,stalled:{start:s}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:r}=this,s=null==(e=this.hls)?void 0:e.config;if(!r||!i||!s)return 0;const n=r.currentTime,a=ti.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const e=a.len<=s.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,d=o-n;if(d>0&&(e||h)){if(d>s.maxBufferHole){let e=!1;if(0===n){const t=i.getAppendedFrag(0,y);t&&o<t.end&&(e=!0)}if(!e&&t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Uo(this.hls.inFlightFragments,o))return 0;let e=!1,r=t.end;for(;r<o;){const t=Go(r,i);if(!t){e=!0;break}r+=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,r.currentTime=e,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`),r={type:u.MEDIA_ERROR,details:c.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?r.part=t:r.frag=t),this.hls.trigger(f.ERROR,r)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:r}=this,s=null==e?void 0:e.config;if(!i||!s)return 0;const n=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){const a=n+(r+1)*s.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,e.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${s.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Uo(t,e){const i=Bo(t.main);if(i&&i.start<=e)return i;const r=Bo(t.audio);return r&&r.start<=e?r:null}function Bo(t){if(!t)return null;switch(t.state){case dr.IDLE:case dr.STOPPED:case dr.ENDED:case dr.ERROR:return null}return t.frag}function Go(t,e){return e.getAppendedFrag(t,y)||e.getPartialFragment(t)}function $o(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Ko(t,e,i,r,s){let n=new t(e,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new t(e,i,ne(s?b({type:s},r):r))}return n}const Vo=(()=>{const t=$o();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Ho{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(f.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(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(f.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(f.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,!1===(null==(i=e.overrides)?void 0:i.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&&fa(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 i=t[e];if("metadata"===i.kind&&"id3"===i.label)return ua(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;const{samples:s}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=$o();if(n)for(let t=0;t<s.length;t++){const e=s[t].type;if(e===Vr.emsg&&!i||!r)continue;const a=Br(s[t].data),o=s[t].pts;let l=o+s[t].duration;l>Vo&&(l=Vo);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!Gr(i)){this.updateId3CueEnds(o,e);const t=Ko(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){var i;const r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){const s=r[i];s.type===e&&s.startTime<t&&s.endTime===Vo&&(s.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:r}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let t;t="audio"===r?t=>t.type===Vr.audioId3&&o:"video"===r?t=>t.type===Vr.emsg&&a:t=>t.type===Vr.audioId3&&o||t.type===Vr.emsg&&a,ga(s,e,i,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:i,timelineOffset:r,enableDateRangeMetadataCues:s,interstitialsController:n}=this.hls.config;if(!s)return;const a=$o();if(i&&r&&!n){const{fragmentStart:e,fragmentEnd:r}=t;let s=this.assetCue;s?(s.startTime=e,s.endTime=r):a&&(s=this.assetCue=Ko(a,e,r,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),s&&(s.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(s),s.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:h}=t,d=Object.keys(h);let u=this.dateRangeCuesAppended;var c;if(o&&e)if(null!=(c=o.cues)&&c.length){const t=Object.keys(u).filter((t=>!d.includes(t)));for(let e=t.length;e--;){var f;const i=t[e],r=null==(f=u[i])?void 0:f.cues;delete u[i],r&&Object.keys(r).forEach((t=>{const e=r[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(e)}catch(t){}}}))}}else u=this.dateRangeCuesAppended={};const g=t.fragments[t.fragments.length-1];if(0!==d.length&&l(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],i=h[e],r=i.startTime,s=u[e],o=(null==s?void 0:s.cues)||{};let l=(null==s?void 0:s.durationKnown)||!1,c=Vo;const{duration:f,endDate:g}=i;if(g&&null!==f)c=r+f,l=!0;else if(i.endOnNext&&!l){const t=d.reduce(((t,e)=>{if(e!==i.id){const r=h[e];if(r.class===i.class&&r.startDate>i.startDate&&(!t||i.startDate<t.startDate))return r}return t}),null);t&&(c=t.startTime,l=!0)}const p=Object.keys(i.attr);for(let t=0;t<p.length;t++){const h=p[t];if("ID"===(m=h)||"CLASS"===m||"CUE"===m||"START-DATE"===m||"DURATION"===m||"END-DATE"===m||"END-ON-NEXT"===m)continue;const d=o[h];if(d)!l||null!=s&&s.durationKnown?Math.abs(d.startTime-r)>.01&&(d.startTime=r,d.endTime=c):d.endTime=c;else if(a){let t=i.attr[h];hi(h)&&(t=U(t));const s=Ko(a,r,c,{key:h,data:t},Vr.dateRange);s&&(s.id=e,this.id3Track.addCue(s),o[h]=s,n&&("X-ASSET-LIST"!==h&&"X-ASSET-URL"!==h||s.addEventListener("enter",this.onEventCueEnter)))}}u[e]={cues:o,dateRange:i,durationKnown:l}}var m}}}class Yo{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 i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,r=Math.min(e,Math.max(1,i));this.changeMediaPlaybackRate(t,r)}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:i,targetduration:r}=t,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);const h=r;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 i=this.levelDetails;if(null===i)return null;const r=i.edge,s=t-e-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),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 i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(f.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(f.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 i;e.details===c.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,r;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(r=this.targetLatency)?void 0:r.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}}class Wo extends Ys{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(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(f.LEVEL_LOADED,this.onLevelLoaded,this),t.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(f.FRAG_BUFFERED,this.onFragBuffered,this),t.on(f.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(f.LEVEL_LOADED,this.onLevelLoaded,this),t.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(f.FRAG_BUFFERED,this.onFragBuffered,this),t.off(f.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 i=this.hls.config.preferManagedMediaSource,r=[],s={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{const e=t.attrs;let{audioCodec:h,videoCodec:d}=t;h&&(t.audioCodec=h=Nt(h,i)||void 0),d&&(d=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(d));const{width:u,height:c,unknownCodecs:f}=t;let g=f?f.length:0;if(f)for(let e=g;e--;){const i=f[e];this.isAudioSupported(i)?(t.audioCodec=h=h?`${h},${i}`:i,g--,Dt.audio[h.substring(0,4)]=2):this.isVideoSupported(i)&&(t.videoCodec=d=d?`${d},${i}`:i,g--,Dt.video[d.substring(0,4)]=2)}if(a||(a=!(!u||!c)),o||(o=!!d),l||(l=!!h),g||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d))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(s[S])if(s[S].uri===t.url||t.attrs["PATHWAY-ID"])s[S].addGroupId("audio",e.AUDIO),s[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);s[S]=i,r.push(i)}else{const e=this.createLevel(t);s[S]=e,n[S]=1,r.push(e)}})),this.filterAndSortMediaOptions(r,e,a,o,l)}createLevel(t){const e=new ie(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=Ht(t,[])}return e}isAudioSupported(t){return Pt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Pt(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,r,s){let n=[],a=[],o=t;if((i||r)&&s&&(o=o.filter((({videoCodec:t,videoRange:e,width:i,height:r})=>{return(!!t||!(!i||!r))&&(!!(s=e)&&Qt.indexOf(s)>-1);var s}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${ne(e.levels.map((t=>t.attrs.CODECS)).filter(((t,e,i)=>i.indexOf(t)===e)))}`,this.warn(i),t+=` (${i})`);const r=new Error(t);this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:r,reason:i})}}));e.audioTracks&&(n=e.audioTracks.filter((t=>!t.audioCodec||this.isAudioSupported(t.audioCodec))),jo(n)),e.subtitles&&(a=e.subtitles,jo(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&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 Qt.indexOf(t.videoRange)-Qt.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=Ot(t.videoCodec),r=Ot(e.videoCodec);if(i!==r)return r-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=xt(t.codecSet),r=xt(e.codecSet);if(i!==r)return r-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;t<l.length;t++)if(l[t].pathwayId===o[0].pathwayId){h=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===h){var d;this._firstLevel=t;const e=h.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const g=s&&!r,m=this.hls.config,p=!(!m.audioStreamController||!m.audioTrackController),v={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:r,altAudio:p&&!g&&n.some((t=>!!t.url))};this.hls.trigger(f.MANIFEST_PARSED,v)}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 i=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:i,reason:i.message}),r)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,i===t&&r&&s===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 ${i}${s?" with Pathway "+s:""}`);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(f.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==r?void 0:r.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(),i=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=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===m&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===y){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:r,details:s}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(s.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(r,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),r=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${r}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${s?" Pathway "+s:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${i}`),this.hls.trigger(f.LEVEL_LOADING,{url:i,level:r,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 i=this._levels.filter(((e,i)=>i!==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)));rr(i),this._levels=i,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 r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(f.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(f.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function jo(t){const e={};t.forEach((t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++}))}function qo(){return self.SourceBuffer||self.WebKitSourceBuffer}function Xo(){if(!x())return!1;const t=qo();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class Qo extends ur{constructor(t,e,i){super(t,e,i,"stream-controller",y),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||!l(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const i=this.getFwdBufferInfoAtPos(t,e,y,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(f.MANIFEST_PARSED,this.onManifestParsed,this),t.on(f.LEVEL_LOADING,this.onLevelLoading,this),t.on(f.LEVEL_LOADED,this.onLevelLoaded,this),t.on(f.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(f.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(f.BUFFER_CREATED,this.onBufferCreated,this),t.on(f.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(f.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(f.MANIFEST_PARSED,this.onManifestParsed,this),t.off(f.LEVEL_LOADED,this.onLevelLoaded,this),t.off(f.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(f.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(f.BUFFER_CREATED,this.onBufferCreated,this),t.off(f.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(f.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=r.startLevel;-1===t&&(r.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=r.firstAutoLevel),r.nextLoadLevel=t,this.level=r.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=dr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=dr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case dr.WAITING_LEVEL:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=dr.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=dr.IDLE;break}break}case dr.FRAG_LOADING_WAITING_RETRY:{var t;const e=self.performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,i=null==t?void 0:t[e];this.resetStartWhenNotLoaded(i||null),this.state=dr.IDLE}}}this.state===dr.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:i,media:r}=this;if(null===e||!r&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[s])return;const n=i[s],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(f.BUFFER_EOS,t),void(this.state=dr.ENDED)}if(!this.buffering)return;t.loadLevel!==s&&-1===t.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=t.nextLoadLevel=s;const l=n.details;if(!l||this.state===dr.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=dr.WAITING_LEVEL,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let c=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&c&&J(c)&&this.fragmentTracker.getState(c)!==Me){var g;const t=(null!=(g=this.backtrackFragment)?g:c).sn-l.startSN,e=l.fragments[t-1];e&&c.cc===e.cc&&(c=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){const t=this.audioOnly&&!this.altAudio?X:Q,e=(t===Q?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,y)}c=this.getNextFragmentLoopLoading(c,l,a,y,d)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,n,u))}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);r===we||r===xe?J(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,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,y)}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 i;const r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*s.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else i=0;const n=this.getBufferedFrag(e.currentTime+i);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,r=Math.max(n.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,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 dr.KEY_LOADING:case dr.FRAG_LOADING:case dr.FRAG_LOADING_WAITING_RETRY:case dr.PARSING:case dr.PARSED:this.state=dr.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 i=e.media;oa(i,"playing",this.onMediaPlaying),oa(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(la(i,"playing",this.onMediaPlaying),la(i,"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(f.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 i=!1,r=!1;for(let t=0;t<e.levels.length;t++){const s=e.levels[t].audioCodec;s&&(i=i||-1!==s.indexOf("mp4a.40.2"),r=r||-1!==s.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&r&&!function(){var t;const e=qo();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:i}=this;if(!i||this.state!==dr.IDLE)return;const r=e.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=dr.WAITING_LEVEL)}onLevelLoaded(t,e){var i;const{levels:r,startFragRequested:s}=this,n=e.level,a=e.details,o=a.totalduration;if(!r)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,h=this.fragCurrent;!h||this.state!==dr.FRAG_LOADING&&this.state!==dr.FRAG_LOADING_WAITING_RETRY||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,d),this.hls.trigger(f.LEVEL_UPDATED,{details:a,level:n}),this.state===dr.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=dr.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const r=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||s<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const t=ti.bufferInfo(i,r,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=r);if(t.start<=s)return void(i.currentTime=r);const{nextStart:e}=ti.bufferedInfo(t.buffered,s,0);e&&(i.currentTime=e)}else i.currentTime=r}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:r,payload:s}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Hs(this.hls,y,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Ze(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];c.push(s,d,u,l,i,r,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const i=this.hls,r=2===this.altAudio;if(fe(e.url,i))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(r)return this.fragmentTracker.removeAllFragments(),i.once(f.BUFFER_FLUSHED,(()=>{this.hls&&this.hls.trigger(f.AUDIO_TRACK_SWITCHED,e)})),void i.trigger(f.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(f.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=fe(e.url,this.hls);if(i){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=i?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let r,s,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(s=t,r=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:r}=e,s=i.type===y;if(s){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===dr.PARSED&&(this.state=dr.IDLE));const t=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),J(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}const n=this.media;n&&(!this._hasEnoughToStart&&ti.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=dr.ERROR;else switch(e.details){case c.FRAG_GAP:case c.FRAG_PARSING_ERROR:case c.FRAG_DECRYPT_ERROR:case c.FRAG_LOAD_ERROR:case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_ERROR:case c.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(y,e);break;case c.LEVEL_LOAD_ERROR:case c.LEVEL_LOAD_TIMEOUT:case c.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==dr.WAITING_LEVEL||(null==(i=e.context)?void 0:i.type)!==m||(this.state=dr.IDLE);break;case c.BUFFER_ADD_CODEC_ERROR:case c.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case c.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case c.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=dr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==X||!this.altAudio){const t=(e===Q?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,y),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 i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const r=this.timelineOffset;r&&i&&(i+=r);const s=this.getLevelDetails(),n=ti.getBuffered(t),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i)}}_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:i}=this,r=null==t?void 0:t.frag;if(!r||this.fragContextChanged(r))return;e.fragmentError=0,this.state=dr.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const s=r.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(f.FRAG_LOADED,t),r.bitrateTest=!1}))}_handleTransmuxComplete(t){const e=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:s}=t,n=this.getCurrentContext(s);if(!n)return void this.resetWhenMissingContext(s);const{frag:a,part:o,level:h}=n,{video:d,text:u,id3:c,initSegment:g}=r,{details:m}=h,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=dr.PARSING,g){const t=g.tracks;if(t){const r=a.initSegment||a;if(this.unhandledEncryptionError(g,a))return;this._bufferInitSegment(h,t,r,s),i.trigger(f.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:e,tracks:t})}const r=g.initPTS,n=g.timescale,o=this.initPTS[a.cc];if(l(r)&&(!o||o.baseTime!==r||o.timescale!==n)){const t=g.trackId;this.initPTS[a.cc]={baseTime:r,timescale:n,trackId:t},i.trigger(f.INIT_PTS_FOUND,{frag:a,id:e,initPTS:r,timescale:n,trackId:t})}}if(d&&m){p&&"audiovideo"===d.type&&this.logMuxedErr(a);const t=m.fragments[a.sn-1-m.startSN],e=a.sn===m.startSN,i=!t||a.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:r,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:t,endPTS:r,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===s.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(a);i&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,r,a.start,l,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,t,r,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,s,e||i)}else{if(!e&&!i)return void this.backtrack(a);a.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=p;o&&(o.elementaryStreams[X]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),a.setElementaryStreamInfo(X,t,e,i,r),this.bufferFragmentData(p,a,o,s)}if(m&&null!=c&&c.samples.length){const t={id:e,frag:a,details:m,samples:c.samples};i.trigger(f.FRAG_PARSING_METADATA,t)}if(m&&u){const t={id:e,frag:a,details:m,samples:u.samples};i.trigger(f.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${J(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,r){if(this.state!==dr.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:s,video:n,audiovideo:a}=e;if(s){const i=t.audioCodec;let r=Ut(s.codec,i);"mp4a"===r&&(r="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){r&&(r=-1!==r.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=s.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===n.indexOf("firefox")&&(r="mp4a.40.5")}r&&-1!==r.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==s.container&&(r="mp4a.40.2",this.log(`Android: force audio codec to ${r}`)),i&&i!==r&&this.log(`Swapping manifest audio codec "${i}" for "${r}"`),s.levelCodec=r,s.id=y,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${r||""}/${i||""}/${s.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=y;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){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||""}/${i}]${n.codec!==i?" 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(f.BUFFER_CODECS,e),!this.hls)return;o.forEach((t=>{const s=e[t].initSegment;null!=s&&s.byteLength&&this.hls.trigger(f.BUFFER_APPENDING,{type:t,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,y)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.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=dr.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(ti.isBuffered(t,i)?e=this.getAppendedFrag(i):ti.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(f.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(f.LEVEL_SWITCHED,{level:i}))}}}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 l(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(l(e)){const t=this.getLevelDetails(),i=this.currentFrag||(t?me(null,t.fragments,e):null);if(i){const t=i.programDateTime;if(null!==t){const r=t+1e3*(e-i.start);return new Date(r)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class zo{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var e;if(t&&t!==(null==(e=r.context)?void 0:e.frag.type))return;r.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=c.KEY_LOAD_ERROR,i,r,s){return new Qe({type:u.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:i,networkDetails:r})}loadClear(t,e,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let r=0,s=e.length;r<s;r++){const n=e[r];if(t.cc<=n.cc&&(!J(t)||!J(n)||t.sn<n.sn)||!i&&r==s-1)return this.emeController.selectKeySystemFormat(n).then((t=>{if(!this.emeController)return;n.setKeyFormat(t);const e=Li(t);return e?this.emeController.getKeySystemAccess([e]):void 0}))}if(this.config.requireKeySystemAccessOnStart){const t=Ii(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 i,r;e&&t.setKeyFormat(e);const s=t.decryptdata;if(!s){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,c.KEY_LOAD_ERROR,i))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,c.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(s.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,c.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(i);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,i)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,r=new(0,i.loader)(i);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,r)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,c.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(t,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(e,c.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),r,b({url:a.url,data:void 0},t)))},onTimeout:(t,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,c.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,c.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,h)}))}resetLoader(t){const{frag:e,keyInfo:i,url:r}=t,s=i.loader;e.keyLoader===s&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}function Zo(t){const{type:e}=t;switch(e){case p:return E;case v:return T;default:return y}}function Jo(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class tl{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(f.MANIFEST_LOADING,this.onManifestLoading,this),t.on(f.LEVEL_LOADING,this.onLevelLoading,this),t.on(f.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(f.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(f.MANIFEST_LOADING,this.onManifestLoading,this),t.off(f.LEVEL_LOADING,this.onLevelLoading,this),t.off(f.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(f.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,r=e.loader,s=new(i||r)(e);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:g,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:m,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:r,url:s,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:p,url:s,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:r,url:s,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:v,url:s,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[m];if(i){const t=i.context;t&&!e.levels.some((e=>e===t.levelOrTrack))&&(i.abort(),delete this.loaders[m])}}load(t){var e;const i=this.hls.config;let r,s=this.getInternalLoader(t);if(s){const e=this.hls.logger,i=s.context;if(i&&i.levelOrTrack===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}if(r=t.type===g?i.manifestLoadPolicy.default:R({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),l(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===m&&null!==t.level?e=this.hls.levels[t.level].details:t.type===p&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===v&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);r=R({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,i,r)=>{const s=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),Mi.isMediaPlaylist(n)||i.type!==g?this.handleTrackOrLevelPlaylist(t,e,i,r||null,s):this.handleMasterPlaylist(t,e,i,r)):this.handleManifestParsingError(t,i,new Error("no EXTM3U delimiter"),r||null,e)},onError:(t,e,i,r)=>{this.handleNetworkError(e,i,!1,t,r)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};s.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,r){const s=this.hls,n=t.data,a=Jo(t,i),o=Mi.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,i,o.playlistParsingError,r,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:g}=o;this.variableList=g;const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Mi.parseMasterPlaylistMedia(n,a,o);if(m.length){m.some((t=>!t.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new li({}),bitrate:0,url:""}))}s.trigger(f.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:v,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:g})}handleTrackOrLevelPlaylist(t,e,i,r,s){const n=this.hls,{id:a,level:o,type:h}=i,d=Jo(t,i),u=l(o)?o:l(a)?a:0,c=Zo(i),m=Mi.parseLevelPlaylist(t.data,d,u,c,0,this.variableList);if(h===g){const t={attrs:new li({}),bitrate:0,details:m,name:"",url:d};m.requestScheduled=e.loading.start+Ji(m,0),n.trigger(f.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,t,e,i,r,s)}handleManifestParsingError(t,e,i,r,s){this.hls.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.MANIFEST_PARSING_ERROR,fatal:e.type===g,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:r,stats:s})}handleNetworkError(t,e,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${t.type}`;t.type===m?n+=`: ${t.level} id: ${t.id}`:t.type!==p&&t.type!==v||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=c.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case g:o=i?c.MANIFEST_LOAD_TIMEOUT:c.MANIFEST_LOAD_ERROR,l=!0;break;case m:o=i?c.LEVEL_LOAD_TIMEOUT:c.LEVEL_LOAD_ERROR,l=!1;break;case p:o=i?c.AUDIO_TRACK_LOAD_TIMEOUT:c.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case v:o=i?c.SUBTITLE_TRACK_LOAD_TIMEOUT:c.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const d={type:u.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:s};if(r){const i=(null==e?void 0:e.url)||t.url;d.response=b({url:i,data:void 0},r)}this.hls.trigger(f.ERROR,d)}handlePlaylistLoaded(t,e,i,r,s,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:E}=r,T=Jo(e,r),S=Zo(r),A="number"==typeof r.level&&S===y?l:void 0;if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.LEVEL_EMPTY_ERROR,fatal:!1,url:T,error:n,reason:n.message,response:e,context:r,level:A,parent:S,networkDetails:s,stats:i})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const L=t.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.LEVEL_PARSING_ERROR,fatal:!1,url:T,error:L,reason:L.message,response:e,context:r,level:A,parent:S,networkDetails:s,stats:i});t.playlistParsingError=null}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case g:case m:a.trigger(f.LEVEL_LOADED,{details:t,levelInfo:r.levelOrTrack||a.levels[0],level:A||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:E,withoutMultiVariant:o===g});break;case p:a.trigger(f.AUDIO_TRACK_LOADED,{details:t,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:E});break;case v:a.trigger(f.SUBTITLE_TRACK_LOADED,{details:t,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:E})}}}class el{static get version(){return yr}static isMSESupported(){return Xo()}static isSupported(){return function(){if(!Xo())return!1;const t=x();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(wt(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(wt(e,"audio")))))}()}static getMediaSource(){return x()}static get Events(){return f}static get MetadataSchema(){return Vr}static get ErrorTypes(){return u}static get ErrorDetails(){return c}static get DefaultConfig(){return el.defaultConfig?el.defaultConfig:xo}static set DefaultConfig(t){el.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new vr,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 e=this.logger=function(t,e,i){const r=P();if("object"==typeof console&&!0===t||"object"==typeof t){const s=["debug","log","info","warn","error"];s.forEach((e=>{r[e]=C(e,t,i)}));try{r.log(`Debug logs enabled for "${e}" in hls.js version 1.6.9`)}catch(t){return P()}s.forEach((e=>{w[e]=C(e,t)}))}else R(w,r);return r}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(t,e,i){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 r=Mo(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];s.forEach((i=>{const s=`${t}Loading${i}`,l=e[s];if(void 0!==l&&a){o.push(s);const t=r[n].default;switch(e[n]={default:t},i){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&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${ne(e[n])}`)})),b(b({},r),e)}(el.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Fo(i,e);const{abrController:r,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),h=this.abrController=new r(this),d=new Fe(this),u=i.interstitialsController,c=u?this.interstitialsController=new u(this,el):null,g=this.bufferController=new s(this,d),m=this.capLevelController=new n(this),p=new o(this),v=new tl(this),y=i.contentSteeringController,E=y?new y(this):null,T=this.levelController=new Wo(this,E),S=new Ho(this),A=new zo(this.config),L=this.streamController=new Qo(this,d,A),I=this.gapController=new No(this,d);m.setStreamController(L),p.setStreamController(L);const k=[v,T,L];c&&k.splice(1,0,c),E&&k.splice(1,0,E),this.networkControllers=k;const D=[h,g,I,m,p,S,d];this.audioTrackController=this.createController(i.audioTrackController,k);const _=i.audioStreamController;_&&k.push(this.audioStreamController=new _(this,d,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,k);const O=i.subtitleStreamController;O&&k.push(this.subtititleStreamController=new O(this,d,A)),this.createController(i.timelineController,D),A.emeController=this.emeController=this.createController(i.emeController,D),this.cmcdController=this.createController(i.cmcdController,D),this.latencyController=this.createController(Yo,D),this.coreComponents=D,k.push(l);const x=l.onErrorOut;"function"==typeof x&&this.on(f.ERROR,x,l),this.on(f.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,r){this._emitter.off(t,e,i,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===f.ERROR;this.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(f.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(f.ERROR,{type:u.OTHER_ERROR,details:c.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,i=e?t.media:t,r=e?t:{media:i};this._media=i,this.trigger(f.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(f.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(f.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,r=this._url=j.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),e&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(f.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 i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}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={[y]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[E]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[T]=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 i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|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 Xt.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 i=t.length;for(let r=0;r<i;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let r;if(r=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=r;e--;){const r=t[e].attrs["HDCP-LEVEL"];if(r&&r<=i)return e}return r}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 Wt(t,oe(e),navigator.mediaCapabilities)}}el.defaultConfig=void 0;var il=i(24091),rl=i.n(il),sl=function(t,e,i,r,s,n){function a(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!e&&t?r.static?t:t.prototype:null,u=e||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(t){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(t||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},nl=function(t,e,i){for(var r=arguments.length>2,s=0;s<e.length;s++)i=r?e[s].call(t,i):e[s].call(t);return r?i:void 0},al=function(t,e,i){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:i?"".concat(i," ",e):e})},ol=function(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)},ll=function(t,e,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,i):s?s.value=i:e.set(t,i),i};let hl=(()=>{var t,e,i;let l,h,d=[a.JW],u=[],g=n.F;h=class extends g{get hlsInstance(){return this.hls}constructor(s,n){super(s,n),t.set(this,null),e.set(this,!1),this.dvrSegmentDuration=0,this.dvrWindowRight=0,this.dvrWindowLeft=0,this.dvrTime=-1,this.dvrRightToLiveOffset=0,this.dvrToDateSync=null,this.recoverDecodingErrorDate=-1,this.recoverSwapAudioCodecDate=-1,this.networkRecoveryHandler=null,this.hls=null,i.set(this,!1),this.lastTickerUpdate=-1,this.onLevelsChanged=(t,e)=>{e.levels.length>0&&this.player.loop.dispatchEvent(r.a.EVENT_QUALITY_CHANGE,{fromQuality:this.player.currentQuality,toQuality:this.player.currentQuality})},this._dvrModeEnabled=!1,this._dvrWindow=0,this._dvrIsLive=!1,this.dvrTime=-1,this.dvrRightToLiveOffset=0,this.dvrToDateSync=null,this.emap.map(this.mediaElement,"playing",this.onPlaying,this)}get isPlayingSpatialAudio(){var t,e,i;return(null!==(e=null===(t=this.audioTrack)||void 0===t?void 0:t.channelCount)&&void 0!==e?e:0)>5||!0===(null===(i=this.audioTrack)||void 0===i?void 0:i.isAtmos)}applyVideoScale(t){this.mediaElement.style.objectFit="COVER"===t?"cover":"contain"}onError(t){var e;"error"===t.type&&t.currentTarget instanceof HTMLMediaElement&&(null===(e=t.currentTarget.error)||void 0===e?void 0:e.code)===MediaError.MEDIA_ERR_DECODE?this.handleHLSMediaError():this.handleError(t)}onSeekEnd(t){super.onSeekEnd(t),this.updateDVRValues()}onDurationChange(t){super.onDurationChange(t),this.dvrWindowRight=this.mediaElement.duration-this.dvrRightToLiveOffset,this.dvrWindowLeft=this.dvrWindowRight-this._dvrWindow}onPlaying(){ol(this,i,"f")&&(ll(this,i,!1,"f"),this.mediaElement.pause())}addSource(s){this.resetNetworkErrorHandler(),ll(this,e,!1,"f");const n=rl().isSupported()&&s.url.indexOf("m3u8")>0;if(this.hls&&(this.hls.destroy(),this.hls=null),n){ll(this,t,s,"f");const n={debug:!1,enableWorker:!0,liveSyncDurationCount:2,capLevelToPlayerSize:!0,startFragPrefetch:!0,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,manifestLoadingMaxRetry:2,manifestLoadingRetryDelay:500,manifestLoadingMaxRetryTimeout:64e3,levelLoadingMaxRetry:3,levelLoadingRetryDelay:500,levelLoadingMaxRetryTimeout:2e3,maxBufferSize:1e3*(this.player.isAudio?10:60)*1e3},a=(0,o.$N)(this.pc.getPluginData("plugin-hls"),this.mc.getPluginData("plugin-hls")),l=(0,o.$N)(n,a);this._pendingSeek>0&&(l.startPosition=this._pendingSeek),l.timelineController=class extends Lo{constructor(t){super(t),this.lastTracksLength=0,t.on(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdatedModifier,this)}get superTextTracks(){return this.textTracks}onSubtitleTracksUpdatedModifier(t,e){if(this.lastTracksLength!==this.superTextTracks.length){this.lastTracksLength=this.superTextTracks.length;const t=e.subtitleTracks;this.superTextTracks.length>1&&t.length&&t.forEach(((t,e)=>{t.forced&&(this.superTextTracks[e].isForced=!0)}))}}},this.log("HLS.js config:",l),this.hls=new(rl())(l),this.hls.subtitleDisplay=!1,this.recoverDecodingErrorDate=-1,this.recoverSwapAudioCodecDate=-1,this.hls.attachMedia(this.mediaElement),this.hls.on(rl().Events.MEDIA_ATTACHED,(()=>{var t;this.player.pixelController&&this.player.pixelController.loadStream(s.url),null===(t=this.hls)||void 0===t||t.loadSource(s.url),this.isPlaying()&&this.mediaElement.play()}));let h=!1;this.hls.on(rl().Events.ERROR,((t,e)=>{var r,n,a,o,l,d,u,f,g,m,p,v,y;if(e.fatal)switch(e.type){case rl().ErrorTypes.NETWORK_ERROR:if(this.warn("fatal network error encountered",e.details,e.reason,e.networkDetails,null===(r=navigator.connection)||void 0===r?void 0:r.downlink),"object"==typeof navigator.connection&&(null!==(n=navigator.connection.downlink)&&void 0!==n?n:1)<=0)return this.warn("navigator says offline - add change handler"),this.networkRecoveryHandler=()=>{var t;this.log("network change, try to recover"),h=!0,null===(t=this.hls)||void 0===t||t.startLoad()},void navigator.connection.addEventListener("change",this.networkRecoveryHandler);if(null==this.hls||h){this.error("irrecoverable"),null===(a=this.hls)||void 0===a||a.destroy();const t=e.networkDetails;this.handleError(`${e.details} ${null!==(o=e.reason)&&void 0!==o?o:""} - Status: ${null!==(l=t.status)&&void 0!==l?l:-1} ${null!==(d=t.statusText)&&void 0!==d?d:""} - Response: ${null!==(u=t.response)&&void 0!==u?u:"null"}`)}else h=!0,[c.MANIFEST_LOAD_ERROR,c.MANIFEST_LOAD_TIMEOUT,c.MANIFEST_PARSING_ERROR,c.MANIFEST_INCOMPATIBLE_CODECS_ERROR].includes(e.details)||(null!==(m=null===(g=null===(f=this.hls)||void 0===f?void 0:f.levels)||void 0===g?void 0:g.length)&&void 0!==m?m:0)<1?(this.warn("manifest not loaded, try complete re-set"),null===(p=this.hls)||void 0===p||p.loadSource(s.url),this.mediaElement.play()):(this.log("try to recover"),null===(v=this.hls)||void 0===v||v.startLoad());break;case rl().ErrorTypes.MEDIA_ERROR:case rl().ErrorTypes.MUX_ERROR:this.warn("fatal media error encountered, try to recover",e),ll(this,i,!this.isPlaying(),"f"),this.handleHLSMediaError();break;default:this.error("fatal error",t,e),null===(y=this.hls)||void 0===y||y.destroy(),this.handleError()}})),this.hls.on(rl().Events.MANIFEST_PARSED,this.onLevelsChanged),this.hls.on(rl().Events.LEVELS_UPDATED,this.onLevelsChanged),this.hls.on(rl().Events.LEVEL_LOADED,((t,i)=>{var s,n;this._dvrModeEnabled=i.details.live,this.mc.isLive&&!i.details.live&&this.log("config mismatch: MC is live, stream is not!"),this.dvrSegmentDuration=i.details.targetduration,this.dvrRightToLiveOffset=(null!==(n=null===(s=this.hls)||void 0===s?void 0:s.config.liveSyncDurationCount)&&void 0!==n?n:0)*this.dvrSegmentDuration+1,this._dvrWindow=i.details.totalduration-this.dvrRightToLiveOffset,(this.dvrTime<0||isNaN(this.dvrTime))&&(this.dvrTime=this.getDuration()),this.updateDVRValues(),ol(this,e,"f")||(this.player.loop.dispatchEvent(r.a.EVENT_STREAM_LOADED,{}),ll(this,e,!0,"f"))})),this.hls.on(rl().Events.FRAG_LOADED,((t,e)=>{const i=e.frag;if("main"===i.type)if(!i.programDateTime||isNaN(this.dvrWindowLeft)){if(i.sn&&"initSegment"!==i.sn&&i.duration&&!isNaN(this.dvrWindowLeft)){let t=i.duration;const e=i.tagList||[];for(const i of e)if("INF"===i[0]){t=Number(i[1]);break}const r=i.sn*t*1e3,s=new Date(r),n=new Date;if(s.getFullYear()!==n.getFullYear())return;const a=i.start-this.dvrWindowLeft;this.dvrToDateSync={rel:a,real:r,at:Date.now()}}}else{const t=i.start-this.dvrWindowLeft;this.dvrToDateSync={rel:t,real:i.programDateTime,at:Date.now()}}})),this.hls.on(rl().Events.AUDIO_TRACKS_UPDATED,((t,e)=>{var i,r,s,n,a,l;this.audioTracks=[];const h=null!==(r=null===(i=this.hls)||void 0===i?void 0:i.audioTrack)&&void 0!==r?r:-1;for(const t of e.audioTracks){const e=h<0?t.default:h===this.audioTracks.length,i=(0,o.i5)(t.attrs,"CHANNELS")?parseInt(String(t.attrs.CHANNELS),10):void 0,r=(0,o.i5)(t.attrs,"CHARACTERISTICS")?String(t.attrs.CHARACTERISTICS).includes("public.accessibility.describes-video"):/audio\s*des[ck]ription/i.test(t.name),d={id:String(t.id),default:t.default,label:t.name,language:null!==(s=t.lang)&&void 0!==s?s:"und",isSpeechOptimized:/klare\s*sprache/i.test(t.name),isSimpleLanguage:/einfache\s*sprache/i.test(t.name),isAtmos:/dolby\s*atmos/i.test(t.name)||/ea?c3-joc/i.test(null!==(n=t.audioCodec)&&void 0!==n?n:"")||/immersive/i.test(null!==(a=t.channels)&&void 0!==a?a:"")||/joc/i.test(null!==(l=t.channels)&&void 0!==l?l:""),enabled:e,channelCount:i,isAudioDescription:r};this.audioTracks.push(d),t.default&&(this.audioTrack=d)}this.onAudioTracksChanged()})),this.hls.on(rl().Events.AUDIO_TRACK_SWITCHED,((t,e)=>{const i=String(e.id);for(const t of this.audioTracks)i===t.id&&(this.audioTrack=t);this.player.loop.dispatchEvent(r.a.CURRENT_AUDIO_TRACK_CHANGED,{audioTrack:this.audioTrack})}))}else ll(this,t,null,"f"),this.handleError()}handleHLSMediaError(){var t,e,i,r;const s=Date.now();-1===this.recoverDecodingErrorDate||s-this.recoverDecodingErrorDate>3e3?(this.recoverDecodingErrorDate=s,this.log(`try to recover media Error @ ${this.getCurrentTime()}`),null===(t=this.hls)||void 0===t||t.recoverMediaError()):-1===this.recoverSwapAudioCodecDate||s-this.recoverSwapAudioCodecDate>3e3?(this.recoverSwapAudioCodecDate=Date.now(),this.log(`try to swap Audio Codec and recover media Error @ ${this.getCurrentTime()}`),null===(e=this.hls)||void 0===e||e.swapAudioCodec(),null===(i=this.hls)||void 0===i||i.recoverMediaError()):(this.log("cannot recover, last media error recovery failed ..."),null===(r=this.hls)||void 0===r||r.destroy(),this.handleError())}resetNetworkErrorHandler(){var t;this.networkRecoveryHandler&&(null===(t=navigator.connection)||void 0===t||t.removeEventListener("change",this.networkRecoveryHandler))}canSeek(){return!0}getDvrToDateSync(){return this.dvrToDateSync}setCurrentTime(t,e=!1,i=!1,r=!1){let s=-1;this.dvrToDateSync&&t>=this.dvrRelToUnix(0)&&(s=t,t=this.dvrUnixToRel(t));let n=Math.min(t,this.getDuration()-.1);if(this.setSeekEventTimestamps(this.getCurrentTime(),t),this._dvrModeEnabled){const e=t/this.getDuration();n=this.dvrWindowLeft+(this.dvrWindowRight-this.dvrWindowLeft)*e,this.dvrTime=t}this.setCurrentTimeRaw(n,s,e,i,r),this.player.model.time=t}getCurrentTime(){return this._dvrModeEnabled?this.dvrTime:super.getCurrentTime()}getDuration(){return this._dvrModeEnabled?this._dvrWindow:super.getDuration()}seekToLive(){var t,e;this.setCurrentTime(null!==(e=null===(t=this.hls)||void 0===t?void 0:t.liveSyncPosition)&&void 0!==e?e:this.getDuration())}updateTicker(){if(this._dvrModeEnabled){const t=performance.now();-1!==this.lastTickerUpdate&&(this.model.playstate===s.R.PLAYSTATE_PAUSED||this.model.playstate===s.R.PLAYSTATE_PLAYING&&this.playbackStalled?this.dvrTime=Math.max(0,this.dvrTime-(t-this.lastTickerUpdate)/1e3):this.model.playstate===s.R.PLAYSTATE_PLAYING&&(this.dvrTime+=(this.model.playbackRate-1)*((t-this.lastTickerUpdate)/1e3),this.dvrTime>=this.getDuration()&&(this.dvrTime=this.getDuration()))),this.lastTickerUpdate=t}super.updateTicker()}stopTicker(){this.lastTickerUpdate=-1,super.stopTicker()}updateDVRValues(){this.onDVRCallback(this._dvrModeEnabled,this._dvrWindow,this.dvrTime>=this.getDuration())}play(){this.model.playstate===s.R.PLAYSTATE_PAUSED&&this.mc.isLive&&!this.mc.isDvrEnabled&&this.seekToLive(),super.play()}getAudioTracks(){return null===this.hls?[]:this.audioTracks}setAudioTrack(t){if(this.audioTrack=t,null===this.hls)return;const e=parseInt(t.id,10);this.hls.audioTrack!==e&&(this.hls.audioTrack=e)}setAudioTrackById(t){if(null===this.hls)return;const e=parseInt(t,10);this.hls.audioTrack!==e&&(this.hls.audioTrack=e)}getAudioTrack(){return this.audioTrack}setWebVTTSubtitlesEnabled(t){this.hls&&this.hls.subtitleDisplay!==t&&(this.hls.subtitleDisplay=t)}dispose(){this.resetNetworkErrorHandler(),this.hls&&(this.hls.destroy(),this.hls=null),super.dispose()}debugString(){var e,i,r,s;return this.hls?`AutoLevel: ${String(this.hls.autoLevelEnabled)} | Quality ${(null!==(e=this.hls.currentLevel)&&void 0!==e?e:-2)+1} of ${null!==(r=null===(i=this.hls.levels)||void 0===i?void 0:i.length)&&void 0!==r?r:-1}${!0===(null===(s=ol(this,t,"f"))||void 0===s?void 0:s.isAdaptiveQualitySelectable)?" (sub-selectable)":""}`:"no instance"}debugQualityLevel(){var t,e,i,r,s;return[null!==(e=null===(t=this.hls)||void 0===t?void 0:t.currentLevel)&&void 0!==e?e:-1,null!==(s=null===(r=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===r?void 0:r.length)&&void 0!==s?s:1]}get subQualities(){var t,e,i,r,s;const n=[{level:-1,label:"Auto",width:-1,height:-1}],a=null!==(r=null===(i=null===(t=this.hls)||void 0===t?void 0:t.levels[null===(e=this.hls)||void 0===e?void 0:e.currentLevel])||void 0===i?void 0:i.codecSet)&&void 0!==r?r:null;return null===(s=this.hls)||void 0===s||s.levels.forEach(((t,e)=>{var i,r,s;if(a&&t.codecSet!==a)return;const l=null!==(r=null===(i=t.videoCodec)||void 0===i?void 0:i.startsWith("hvc1.2"))&&void 0!==r&&r;n.push({level:e,label:null!==(s=t.name)&&void 0!==s?s:(0,o.a7)(t.width,t.height,l),width:t.width,height:t.height,debug:`${t.codecSet}@${Number.isFinite(t.bitrate)?t.bitrate/1e3+"k":t.bitrate}`}),n[0].width=Math.max(n[0].width,t.width),n[0].height=Math.max(n[0].height,t.height)})),n}selectSubQuality(t){null!==this.hls&&(this.hls.currentLevel=t<0||t>this.hls.levels.length?-1:t)}get currentSubQuality(){return null==this.hls||this.hls.autoLevelEnabled?-1:this.hls.currentLevel}getClassTypeString(){return"HLSCtrl"}};return t=new WeakMap,e=new WeakMap,i=new WeakMap,al(h,"HLSCtrl"),(()=>{var t;const e="function"==typeof Symbol&&Symbol.metadata?Object.create(null!==(t=g[Symbol.metadata])&&void 0!==t?t:null):void 0;sl(null,l={value:h},d,{kind:"class",name:h.name,metadata:e},null,u),h=l.value,e&&Object.defineProperty(h,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:e}),nl(h,u)})(),h})();const dl={Generator:i(73913).X,Controller:hl}},73913:(t,e,i)=>{"use strict";i.d(e,{X:()=>l,q:()=>h});var r=i(10032),s=i(94406),n=function(t,e,i,r,s,n){function a(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!e&&t?r.static?t:t.prototype:null,u=e||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(t){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(t||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},a=function(t,e,i){for(var r=arguments.length>2,s=0;s<e.length;s++)i=r?e[s].call(t,i):e[s].call(t);return r?i:void 0},o=function(t,e,i){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:i?"".concat(i," ",e):e})};let l=(()=>{let t,e,i=[s.JW],l=[];e=class{execute(t,e){var i,s;const n=t.model.mediaCollection.streams.some((t=>!t.isAudioOnly))?r.J.createVideo(t,!0):r.J.createAudio(t,!0);try{null===(i=t.viewCtrl)||void 0===i||i.removeMediaCanvas()}catch(t){}null!==n?e(n):null===(s=t.errorCtrl)||void 0===s||s.throwError("MEDIACANVAS_NOT_GENERATED",!0)}};return o(e,"DefaultMediaElementGenerator"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;n(null,t={value:e},i,{kind:"class",name:e.name,metadata:r},null,l),e=t.value,r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r}),a(e,l)})(),e})(),h=(()=>{let t,e,i=[s.JW],l=[];e=class{execute(t,e){var i,s;const n=r.J.createVideo(t,!0);try{null===(i=t.viewCtrl)||void 0===i||i.removeMediaCanvas()}catch(t){}null!==n?e(n):null===(s=t.errorCtrl)||void 0===s||s.throwError("MEDIACANVAS_NOT_GENERATED",!0)}};return o(e,"DefaultVideoElementGenerator"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;n(null,t={value:e},i,{kind:"class",name:e.name,metadata:r},null,l),e=t.value,r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r}),a(e,l)})(),e})()}}]);