@scaleflex/asset-picker 0.1.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 (180) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/LICENSE +50 -0
  3. package/README.md +702 -0
  4. package/dist/asset-picker-BA876lMW.js +11444 -0
  5. package/dist/asset-picker-BbEOZw7O.cjs +5865 -0
  6. package/dist/asset-picker.d.ts +77 -0
  7. package/dist/asset-picker.d.ts.map +1 -0
  8. package/dist/components/filters/ap-filter-approval.d.ts +43 -0
  9. package/dist/components/filters/ap-filter-approval.d.ts.map +1 -0
  10. package/dist/components/filters/ap-filter-color.d.ts +31 -0
  11. package/dist/components/filters/ap-filter-color.d.ts.map +1 -0
  12. package/dist/components/filters/ap-filter-date.d.ts +32 -0
  13. package/dist/components/filters/ap-filter-date.d.ts.map +1 -0
  14. package/dist/components/filters/ap-filter-image.d.ts +21 -0
  15. package/dist/components/filters/ap-filter-image.d.ts.map +1 -0
  16. package/dist/components/filters/ap-filter-labels.d.ts +26 -0
  17. package/dist/components/filters/ap-filter-labels.d.ts.map +1 -0
  18. package/dist/components/filters/ap-filter-metadata.d.ts +93 -0
  19. package/dist/components/filters/ap-filter-metadata.d.ts.map +1 -0
  20. package/dist/components/filters/ap-filter-popover.d.ts +13 -0
  21. package/dist/components/filters/ap-filter-popover.d.ts.map +1 -0
  22. package/dist/components/filters/ap-filter-product-ref.d.ts +38 -0
  23. package/dist/components/filters/ap-filter-product-ref.d.ts.map +1 -0
  24. package/dist/components/filters/ap-filter-size.d.ts +24 -0
  25. package/dist/components/filters/ap-filter-size.d.ts.map +1 -0
  26. package/dist/components/filters/ap-filter-tags.d.ts +31 -0
  27. package/dist/components/filters/ap-filter-tags.d.ts.map +1 -0
  28. package/dist/components/filters/ap-filter-type.d.ts +13 -0
  29. package/dist/components/filters/ap-filter-type.d.ts.map +1 -0
  30. package/dist/components/filters/ap-filters-bar.d.ts +40 -0
  31. package/dist/components/filters/ap-filters-bar.d.ts.map +1 -0
  32. package/dist/components/filters/filters.constants.d.ts +189 -0
  33. package/dist/components/filters/filters.constants.d.ts.map +1 -0
  34. package/dist/components/filters/shared/filter-styles.d.ts +10 -0
  35. package/dist/components/filters/shared/filter-styles.d.ts.map +1 -0
  36. package/dist/components/header/ap-header.d.ts +30 -0
  37. package/dist/components/header/ap-header.d.ts.map +1 -0
  38. package/dist/components/header/ap-regional-settings.d.ts +19 -0
  39. package/dist/components/header/ap-regional-settings.d.ts.map +1 -0
  40. package/dist/components/modal/ap-modal.d.ts +17 -0
  41. package/dist/components/modal/ap-modal.d.ts.map +1 -0
  42. package/dist/components/navigation/ap-breadcrumb.d.ts +14 -0
  43. package/dist/components/navigation/ap-breadcrumb.d.ts.map +1 -0
  44. package/dist/components/preview/ap-preview-panel.d.ts +80 -0
  45. package/dist/components/preview/ap-preview-panel.d.ts.map +1 -0
  46. package/dist/components/selection/ap-marquee-overlay.d.ts +14 -0
  47. package/dist/components/selection/ap-marquee-overlay.d.ts.map +1 -0
  48. package/dist/components/selection/ap-selection-bar.d.ts +21 -0
  49. package/dist/components/selection/ap-selection-bar.d.ts.map +1 -0
  50. package/dist/components/shared/ap-badge.d.ts +12 -0
  51. package/dist/components/shared/ap-badge.d.ts.map +1 -0
  52. package/dist/components/shared/ap-checkbox.d.ts +17 -0
  53. package/dist/components/shared/ap-checkbox.d.ts.map +1 -0
  54. package/dist/components/shared/ap-dropdown.d.ts +37 -0
  55. package/dist/components/shared/ap-dropdown.d.ts.map +1 -0
  56. package/dist/components/shared/ap-icon.d.ts +13 -0
  57. package/dist/components/shared/ap-icon.d.ts.map +1 -0
  58. package/dist/components/shared/ap-popover.d.ts +15 -0
  59. package/dist/components/shared/ap-popover.d.ts.map +1 -0
  60. package/dist/components/shared/ap-radio-group.d.ts +30 -0
  61. package/dist/components/shared/ap-radio-group.d.ts.map +1 -0
  62. package/dist/components/shared/ap-spinner.d.ts +12 -0
  63. package/dist/components/shared/ap-spinner.d.ts.map +1 -0
  64. package/dist/components/shared/ap-tooltip.d.ts +12 -0
  65. package/dist/components/shared/ap-tooltip.d.ts.map +1 -0
  66. package/dist/components/toolbar/ap-content-toolbar.d.ts +64 -0
  67. package/dist/components/toolbar/ap-content-toolbar.d.ts.map +1 -0
  68. package/dist/components/toolbar/sort.constants.d.ts +9 -0
  69. package/dist/components/toolbar/sort.constants.d.ts.map +1 -0
  70. package/dist/components/views/ap-asset-card.d.ts +20 -0
  71. package/dist/components/views/ap-asset-card.d.ts.map +1 -0
  72. package/dist/components/views/ap-asset-row.d.ts +18 -0
  73. package/dist/components/views/ap-asset-row.d.ts.map +1 -0
  74. package/dist/components/views/ap-folder-card.d.ts +27 -0
  75. package/dist/components/views/ap-folder-card.d.ts.map +1 -0
  76. package/dist/components/views/ap-folder-row.d.ts +14 -0
  77. package/dist/components/views/ap-folder-row.d.ts.map +1 -0
  78. package/dist/components/views/ap-grid-view.d.ts +25 -0
  79. package/dist/components/views/ap-grid-view.d.ts.map +1 -0
  80. package/dist/components/views/ap-list-view.d.ts +22 -0
  81. package/dist/components/views/ap-list-view.d.ts.map +1 -0
  82. package/dist/components/views/ap-skeleton.d.ts +12 -0
  83. package/dist/components/views/ap-skeleton.d.ts.map +1 -0
  84. package/dist/controllers/infinite-scroll.controller.d.ts +13 -0
  85. package/dist/controllers/infinite-scroll.controller.d.ts.map +1 -0
  86. package/dist/controllers/keyboard.controller.d.ts +10 -0
  87. package/dist/controllers/keyboard.controller.d.ts.map +1 -0
  88. package/dist/controllers/marquee.controller.d.ts +43 -0
  89. package/dist/controllers/marquee.controller.d.ts.map +1 -0
  90. package/dist/controllers/selection.controller.d.ts +19 -0
  91. package/dist/controllers/selection.controller.d.ts.map +1 -0
  92. package/dist/controllers/store.controller.d.ts +14 -0
  93. package/dist/controllers/store.controller.d.ts.map +1 -0
  94. package/dist/define.cjs +1 -0
  95. package/dist/define.d.ts +2 -0
  96. package/dist/define.d.ts.map +1 -0
  97. package/dist/define.js +2 -0
  98. package/dist/hls.light-C3NKRmfw.cjs +27 -0
  99. package/dist/hls.light-DxDlt6yF.js +14441 -0
  100. package/dist/index.cjs +1 -0
  101. package/dist/index.d.ts +8 -0
  102. package/dist/index.d.ts.map +1 -0
  103. package/dist/index.js +4 -0
  104. package/dist/react.cjs +1 -0
  105. package/dist/react.d.ts +17 -0
  106. package/dist/react.d.ts.map +1 -0
  107. package/dist/react.js +46 -0
  108. package/dist/services/api-client.d.ts +12 -0
  109. package/dist/services/api-client.d.ts.map +1 -0
  110. package/dist/services/auth.service.d.ts +3 -0
  111. package/dist/services/auth.service.d.ts.map +1 -0
  112. package/dist/services/files.service.d.ts +21 -0
  113. package/dist/services/files.service.d.ts.map +1 -0
  114. package/dist/services/filters.service.d.ts +13 -0
  115. package/dist/services/filters.service.d.ts.map +1 -0
  116. package/dist/services/folders.service.d.ts +26 -0
  117. package/dist/services/folders.service.d.ts.map +1 -0
  118. package/dist/services/labels.service.d.ts +4 -0
  119. package/dist/services/labels.service.d.ts.map +1 -0
  120. package/dist/services/settings.service.d.ts +4 -0
  121. package/dist/services/settings.service.d.ts.map +1 -0
  122. package/dist/services/tags.service.d.ts +4 -0
  123. package/dist/services/tags.service.d.ts.map +1 -0
  124. package/dist/store/index.d.ts +6 -0
  125. package/dist/store/index.d.ts.map +1 -0
  126. package/dist/store/store.d.ts +14 -0
  127. package/dist/store/store.d.ts.map +1 -0
  128. package/dist/store/store.types.d.ts +49 -0
  129. package/dist/store/store.types.d.ts.map +1 -0
  130. package/dist/styles/shared-styles.d.ts +4 -0
  131. package/dist/styles/shared-styles.d.ts.map +1 -0
  132. package/dist/types/api.types.d.ts +82 -0
  133. package/dist/types/api.types.d.ts.map +1 -0
  134. package/dist/types/asset.types.d.ts +77 -0
  135. package/dist/types/asset.types.d.ts.map +1 -0
  136. package/dist/types/config.types.d.ts +51 -0
  137. package/dist/types/config.types.d.ts.map +1 -0
  138. package/dist/types/events.types.d.ts +23 -0
  139. package/dist/types/events.types.d.ts.map +1 -0
  140. package/dist/types/filter.types.d.ts +190 -0
  141. package/dist/types/filter.types.d.ts.map +1 -0
  142. package/dist/types/folder.types.d.ts +27 -0
  143. package/dist/types/folder.types.d.ts.map +1 -0
  144. package/dist/types/index.d.ts +8 -0
  145. package/dist/types/index.d.ts.map +1 -0
  146. package/dist/types/label.types.d.ts +9 -0
  147. package/dist/types/label.types.d.ts.map +1 -0
  148. package/dist/types/tag.types.d.ts +13 -0
  149. package/dist/types/tag.types.d.ts.map +1 -0
  150. package/dist/utils/brand-color.d.ts +12 -0
  151. package/dist/utils/brand-color.d.ts.map +1 -0
  152. package/dist/utils/css-helpers.d.ts +2 -0
  153. package/dist/utils/css-helpers.d.ts.map +1 -0
  154. package/dist/utils/debounce.d.ts +4 -0
  155. package/dist/utils/debounce.d.ts.map +1 -0
  156. package/dist/utils/file-type.d.ts +25 -0
  157. package/dist/utils/file-type.d.ts.map +1 -0
  158. package/dist/utils/filter-date.d.ts +9 -0
  159. package/dist/utils/filter-date.d.ts.map +1 -0
  160. package/dist/utils/filter-normalize.d.ts +7 -0
  161. package/dist/utils/filter-normalize.d.ts.map +1 -0
  162. package/dist/utils/filter-pin-storage.d.ts +8 -0
  163. package/dist/utils/filter-pin-storage.d.ts.map +1 -0
  164. package/dist/utils/filter-serialize.d.ts +3 -0
  165. package/dist/utils/filter-serialize.d.ts.map +1 -0
  166. package/dist/utils/filter-url.d.ts +8 -0
  167. package/dist/utils/filter-url.d.ts.map +1 -0
  168. package/dist/utils/filter-validate.d.ts +3 -0
  169. package/dist/utils/filter-validate.d.ts.map +1 -0
  170. package/dist/utils/format.d.ts +5 -0
  171. package/dist/utils/format.d.ts.map +1 -0
  172. package/dist/utils/preference-storage.d.ts +6 -0
  173. package/dist/utils/preference-storage.d.ts.map +1 -0
  174. package/dist/utils/sort-storage.d.ts +7 -0
  175. package/dist/utils/sort-storage.d.ts.map +1 -0
  176. package/dist/utils/thumbnail.d.ts +27 -0
  177. package/dist/utils/thumbnail.d.ts.map +1 -0
  178. package/dist/utils/video.d.ts +7 -0
  179. package/dist/utils/video.d.ts.map +1 -0
  180. package/package.json +67 -0
@@ -0,0 +1,27 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},yr=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=Tr},Tr=Number.MAX_SAFE_INTEGER||9007199254740991;let Y=(function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n})({}),D=(function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.UNKNOWN="unknown",n})({}),E=(function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n})({});var X={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},W={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Bt{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 Sr{constructor(t,e,i,s=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 Bt(t),this.fast_=new Bt(e),this.defaultTTFB_=s,this.ttfb_=new Bt(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new Bt(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Bt(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new Bt(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){t=Math.max(t,this.minDelayMs_);const i=8*e,s=t/1e3,r=i/s;this.fast_.sample(s,r),this.slow_.sample(s,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 xr(n,t,e){return(t=Ar(t))in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}function at(){return at=Object.assign?Object.assign.bind():function(n){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)({}).hasOwnProperty.call(e,i)&&(n[i]=e[i])}return n},at.apply(null,arguments)}function mi(n,t){var e=Object.keys(n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(n);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),e.push.apply(e,i)}return e}function ft(n){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?mi(Object(e),!0).forEach(function(i){xr(n,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)):mi(Object(e)).forEach(function(i){Object.defineProperty(n,i,Object.getOwnPropertyDescriptor(e,i))})}return n}function Lr(n,t){if(typeof n!="object"||!n)return n;var e=n[Symbol.toPrimitive];if(e!==void 0){var i=e.call(n,t);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(n)}function Ar(n){var t=Lr(n,"string");return typeof t=="symbol"?t:t+""}class It{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=Ct,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 Ct=function(){},Rr={trace:Ct,debug:Ct,log:Ct,warn:Ct,info:Ct,error:Ct};function Ve(){return at({},Rr)}function br(n,t){const e=self.console[n];return e?e.bind(self.console,`${t?"["+t+"] ":""}[${n}] >`):Ct}function pi(n,t,e){return t[n]?t[n].bind(t):br(n,e)}const Ke=Ve();function Ir(n,t,e){const i=Ve();if(typeof console=="object"&&n===!0||typeof n=="object"){const s=["debug","log","info","warn","error"];s.forEach(r=>{i[r]=pi(r,n,e)});try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch{return Ve()}s.forEach(r=>{Ke[r]=pi(r,n)})}else at(Ke,i);return i}const J=Ke;function ms(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var be,Ei;function Dr(){return Ei||(Ei=1,be={}),be}var wt=Dr(),Mt=ms(wt);function bt(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Cr(n){return typeof self<"u"&&n===self.ManagedMediaSource}function _r(n,t){const e=Object.keys(n),i=Object.keys(t),s=e.length,r=i.length;return!s||!r||s===r&&!e.some(a=>i.indexOf(a)===-1)}function mt(n,t=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(n);if(t){const d=l.indexOf("\0");return d!==-1?l.substring(0,d):l}return l.replace(/\0/g,"")}const e=n.length;let i,s,r,a="",o=0;for(;o<e;){if(i=n[o++],i===0&&t)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:s=n[o++],a+=String.fromCharCode((i&31)<<6|s&63);break;case 14:s=n[o++],r=n[o++],a+=String.fromCharCode((i&15)<<12|(s&63)<<6|(r&63)<<0);break}}return a}function Vt(n){let t="";for(let e=0;e<n.length;e++){let i=n[e].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function ps(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var Ie={exports:{}},vi;function Pr(){return vi||(vi=1,(function(n,t){(function(e){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(u,l,d){if(d=d||{},u=u.trim(),l=l.trim(),!l){if(!d.alwaysNormalize)return u;var h=o.parseURL(u);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse relative URL.");if(c.scheme)return d.alwaysNormalize?(c.path=o.normalizePath(c.path),o.buildURLFromParts(c)):l;var f=o.parseURL(u);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:c.netLoc,path:null,params:c.params,query:c.query,fragment:c.fragment};if(!c.netLoc&&(p.netLoc=f.netLoc,c.path[0]!=="/"))if(!c.path)p.path=f.path,c.params||(p.params=f.params,c.query||(p.query=f.query));else{var m=f.path,y=m.substring(0,m.lastIndexOf("/")+1)+c.path;p.path=o.normalizePath(y)}return p.path===null&&(p.path=d.alwaysNormalize?o.normalizePath(c.path):c.path),o.buildURLFromParts(p)},parseURL:function(u){var l=i.exec(u);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(u){for(u=u.split("").reverse().join("").replace(r,"");u.length!==(u=u.replace(a,"")).length;);return u.split("").reverse().join("")},buildURLFromParts:function(u){return u.scheme+u.netLoc+u.path+u.params+u.query+u.fragment}};n.exports=o})()})(Ie)),Ie.exports}var Je=Pr();class Le{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 et={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class ti{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof t=="string"&&(t={url:t}),this.base=t,kr(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let s;i.length===1?s=(e==null?void 0:e.byteRangeEndOffset)||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[et.AUDIO]:null,[et.VIDEO]:null,[et.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Le),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Je.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[et.AUDIO]=null,t[et.VIDEO]=null,t[et.AUDIOVIDEO]=null}}function ct(n){return n.sn!=="initSegment"}class ce extends ti{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(B(t)&&B(e))return e-t}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(!((t=this._decryptdata)!=null&&t.keyId)){const i=Object.keys(e);if(i.length===1){const s=this._decryptdata=e[i[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const t=B(this.duration)?this.duration:0;return this.programDateTime+t*1e3}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){var e;const i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(e=this.levelkeys[i[0]])!=null&&e.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!B(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return ct(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const s=e[t];s&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,e))}}abortRequests(){var t,e;(t=this.loader)==null||t.abort(),(e=this.keyLoader)==null||e.abort()}setElementaryStreamInfo(t,e,i,s,r,a=!1){const{elementaryStreams:o}=this,u=o[t];if(!u){o[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:a};return}u.startPTS=Math.min(u.startPTS,e),u.endPTS=Math.max(u.endPTS,i),u.startDTS=Math.min(u.startDTS,s),u.endDTS=Math.max(u.endDTS,r)}}class Es extends ti{constructor(t,e,i,s,r){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=s;const a=t.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function vs(n,t){const e=Object.getPrototypeOf(n);if(e){const i=Object.getOwnPropertyDescriptor(e,t);return i||vs(e,t)}}function kr(n,t){const e=vs(n,t);e&&(e.enumerable=!0,Object.defineProperty(n,t,e))}const yi=Math.pow(2,32)-1,Or=[].push,ys={video:1,audio:2,id3:3,text:4};function nt(n){return String.fromCharCode.apply(null,n)}function Ts(n,t){const e=n[t]<<8|n[t+1];return e<0?65536+e:e}function H(n,t){const e=Ss(n,t);return e<0?4294967296+e:e}function Ti(n,t){let e=H(n,t);return e*=Math.pow(2,32),e+=H(n,t+4),e}function Ss(n,t){return n[t]<<24|n[t+1]<<16|n[t+2]<<8|n[t+3]}function Fr(n){const t=n.byteLength;for(let e=0;e<t;){const i=H(n,e);if(i>8&&n[e+4]===109&&n[e+5]===111&&n[e+6]===111&&n[e+7]===102)return!0;e=i>1?e+i:t}return!1}function j(n,t){const e=[];if(!t.length)return e;const i=n.byteLength;for(let s=0;s<i;){const r=H(n,s),a=nt(n.subarray(s+4,s+8)),o=r>1?s+r:i;if(a===t[0])if(t.length===1)e.push(n.subarray(s+8,o));else{const u=j(n.subarray(s+8,o),t.slice(1));u.length&&Or.apply(e,u)}s=o}return e}function wr(n){const t=[],e=n[0];let i=8;const s=H(n,i);i+=4;let r=0,a=0;e===0?(r=H(n,i),a=H(n,i+4),i+=8):(r=Ti(n,i),a=Ti(n,i+8),i+=16),i+=2;let o=n.length+a;const u=Ts(n,i);i+=2;for(let l=0;l<u;l++){let d=i;const h=H(n,d);d+=4;const c=h&2147483647;if((h&2147483648)>>>31===1)return J.warn("SIDX has hierarchical references (not supported)"),null;const g=H(n,d);d+=4,t.push({referenceSize:c,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+c-1}}),o+=c,d+=4,i=d}return{earliestPresentationTime:r,timescale:s,version:e,referencesCount:u,references:t}}function xs(n){const t=[],e=j(n,["moov","trak"]);for(let s=0;s<e.length;s++){const r=e[s],a=j(r,["tkhd"])[0];if(a){let o=a[0];const u=H(a,o===0?12:20),l=j(r,["mdia","mdhd"])[0];if(l){o=l[0];const d=H(l,o===0?12:20),h=j(r,["mdia","hdlr"])[0];if(h){const c=nt(h.subarray(8,12)),f={soun:et.AUDIO,vide:et.VIDEO}[c],g=j(r,["mdia","minf","stbl","stsd"])[0],p=Mr(g);f?(t[u]={timescale:d,type:f,stsd:p},t[f]=ft({timescale:d,id:u},p)):t[u]={timescale:d,type:c,stsd:p}}}}}return j(n,["moov","mvex","trex"]).forEach(s=>{const r=H(s,4),a=t[r];a&&(a.default={duration:H(s,12),flags:H(s,20)})}),t}function Mr(n){const t=n.subarray(8),e=t.subarray(86),i=nt(t.subarray(4,8));let s=i,r;const a=i==="enca"||i==="encv";if(a){const l=j(t,[i])[0].subarray(i==="enca"?28:78);j(l,["sinf"]).forEach(h=>{const c=j(h,["schm"])[0];if(c){const f=nt(c.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=j(h,["frma"])[0];g&&(s=nt(g))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const u=j(e,["avcC"])[0];u&&u.length>3&&(s+="."+se(u[1])+se(u[2])+se(u[3]),r=ie(o==="avc1"?"dva1":"dvav",e));break}case"mp4a":{const u=j(t,[i])[0],l=j(u.subarray(28),["esds"])[0];if(l&&l.length>7){let d=4;if(l[d++]!==3)break;d=De(l,d),d+=2;const h=l[d++];if(h&128&&(d+=2),h&64&&(d+=l[d++]),l[d++]!==4)break;d=De(l,d);const c=l[d++];if(c===64)s+="."+se(c);else break;if(d+=12,l[d++]!==5)break;d=De(l,d);const f=l[d++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[d]&224)>>5)),s+="."+g}break}case"hvc1":case"hev1":{const u=j(e,["hvcC"])[0];if(u&&u.length>12){const l=u[1],d=["","A","B","C"][l>>6],h=l&31,c=H(u,2),f=(l&32)>>5?"H":"L",g=u[12],p=u.subarray(6,12);s+="."+d+h,s+="."+Nr(c).toString(16).toUpperCase(),s+="."+f+g;let m="";for(let y=p.length;y--;){const T=p[y];(T||m)&&(m="."+T.toString(16).toUpperCase()+m)}s+=m}r=ie(o=="hev1"?"dvhe":"dvh1",e);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=ie(s,e)||s;break}case"vp09":{const u=j(e,["vpcC"])[0];if(u&&u.length>6){const l=u[4],d=u[5],h=u[6]>>4&15;s+="."+yt(l)+"."+yt(d)+"."+yt(h)}break}case"av01":{const u=j(e,["av1C"])[0];if(u&&u.length>2){const l=u[1]>>>5,d=u[1]&31,h=u[2]>>>7?"H":"M",c=(u[2]&64)>>6,f=(u[2]&32)>>5,g=l===2&&c?f?12:10:c?10:8,p=(u[2]&16)>>4,m=(u[2]&8)>>3,y=(u[2]&4)>>2,T=u[2]&3;s+="."+l+"."+yt(d)+h+"."+yt(g)+"."+p+"."+m+y+T+"."+yt(1)+"."+yt(1)+"."+yt(1)+"."+0,r=ie("dav1",e)}break}}return{codec:s,encrypted:a,supplemental:r}}function ie(n,t){const e=j(t,["dvvC"]),i=e.length?e[0]:j(t,["dvcC"])[0];if(i){const s=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return n+"."+yt(s)+"."+yt(r)}}function Nr(n){let t=0;for(let e=0;e<32;e++)t|=(n>>e&1)<<31-e;return t>>>0}function De(n,t){const e=t+5;for(;n[t++]&128&&t<e;);return t}function se(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function yt(n){return(n<10?"0":"")+n}function Br(n,t){if(!n||!t)return;const e=t.keyId;e&&t.isCommonEncryption&&Ls(n,(i,s)=>{const r=i.subarray(8,24);r.some(a=>a!==0)||(J.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Vt(r)} -> ${Vt(e)}`),i.set(e,8))})}function $r(n){const t=[];return Ls(n,e=>t.push(e.subarray(8,24))),t}function Ls(n,t){j(n,["moov","trak"]).forEach(i=>{const s=j(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;const r=s.subarray(8);let a=j(r,["enca"]);const o=a.length>0;o||(a=j(r,["encv"])),a.forEach(u=>{const l=o?u.subarray(28):u.subarray(78);j(l,["sinf"]).forEach(h=>{const c=Ur(h);c&&t(c,o)})})})}function Ur(n){const t=j(n,["schm"])[0];if(t){const e=nt(t.subarray(4,8));if(e==="cbcs"||e==="cenc"){const i=j(n,["schi","tenc"])[0];if(i)return i}}}function Gr(n,t,e){const i={},s=j(n,["moof","traf"]);for(let r=0;r<s.length;r++){const a=s[r],o=j(a,["tfhd"])[0],u=H(o,4),l=t[u];if(!l)continue;i[u]||(i[u]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=i[u],h=j(a,["tfdt"])[0];if(h){const v=h[0];let S=H(h,4);v===1&&(S===yi?e.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=yi+1,S+=H(h,8))),B(S)&&(!B(d.start)||S<d.start)&&(d.start=S)}const c=l.default,f=H(o,0)|(c==null?void 0:c.flags);let g=(c==null?void 0:c.duration)||0;f&8&&(f&2?g=H(o,12):g=H(o,8));const p=j(a,["trun"]);let m=d.start||0,y=0,T=g;for(let v=0;v<p.length;v++){const S=p[v],A=H(S,4),C=d.sampleCount;d.sampleCount+=A;const x=S[3]&1,R=S[3]&4,b=S[2]&1,I=S[2]&2,_=S[2]&4,w=S[2]&8;let $=8,V=A;for(x&&($+=4),R&&A&&(!(S[$+1]&1)&&d.keyFrameIndex===void 0&&(d.keyFrameIndex=C),$+=4,b?(T=H(S,$),$+=4):T=g,I&&($+=4),w&&($+=4),m+=T,y+=T,V--);V--;)b?(T=H(S,$),$+=4):T=g,I&&($+=4),_&&(S[$+1]&1||d.keyFrameIndex===void 0&&(d.keyFrameIndex=d.sampleCount-(V+1),d.keyFrameStart=m),$+=4),w&&($+=4),m+=T,y+=T;!y&&g&&(y+=g*A)}d.duration+=y}if(!Object.keys(i).some(r=>i[r].duration)){let r=1/0,a=0;const o=j(n,["sidx"]);for(let u=0;u<o.length;u++){const l=wr(o[u]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const d=l.references.reduce((h,c)=>h+c.info.duration||0,0);a=Math.max(a,d+l.earliestPresentationTime/l.timescale)}}a&&B(a)&&Object.keys(i).forEach(u=>{i[u].duration||(i[u].duration=a*i[u].timescale-i[u].start)})}return i}function Vr(n){const t={valid:null,remainder:null},e=j(n,["moof"]);if(e.length<2)return t.remainder=n,t;const i=e[e.length-1];return t.valid=n.slice(0,i.byteOffset-8),t.remainder=n.slice(i.byteOffset-8),t}function pt(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function Si(n,t){const e=[],i=t.samples,s=t.timescale,r=t.id;let a=!1;return j(i,["moof"]).map(u=>{const l=u.byteOffset-8;j(u,["traf"]).map(h=>{const c=j(h,["tfdt"]).map(f=>{const g=f[0];let p=H(f,4);return g===1&&(p*=Math.pow(2,32),p+=H(f,8)),p/s})[0];return c!==void 0&&(n=c),j(h,["tfhd"]).map(f=>{const g=H(f,4),p=H(f,0)&16777215,m=(p&1)!==0,y=(p&2)!==0,T=(p&8)!==0;let v=0;const S=(p&16)!==0;let A=0;const C=(p&32)!==0;let x=8;g===r&&(m&&(x+=8),y&&(x+=4),T&&(v=H(f,x),x+=4),S&&(A=H(f,x),x+=4),C&&(x+=4),t.type==="video"&&(a=ei(t.codec)),j(h,["trun"]).map(R=>{const b=R[0],I=H(R,0)&16777215,_=(I&1)!==0;let w=0;const $=(I&4)!==0,V=(I&256)!==0;let N=0;const P=(I&512)!==0;let G=0;const M=(I&1024)!==0,U=(I&2048)!==0;let K=0;const O=H(R,4);let F=8;_&&(w=H(R,F),F+=4),$&&(F+=4);let z=w+l;for(let Z=0;Z<O;Z++){if(V?(N=H(R,F),F+=4):N=v,P?(G=H(R,F),F+=4):G=A,M&&(F+=4),U&&(b===0?K=H(R,F):K=Ss(R,F),F+=4),t.type===et.VIDEO){let Q=0;for(;Q<G;){const it=H(i,z);if(z+=4,Kr(a,i[z])){const Et=i.subarray(z,z+it);As(Et,a?2:1,n+K/s,e)}z+=it,Q+=it+4}}n+=N/s}}))})})}),e}function ei(n){if(!n)return!1;const t=n.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function Kr(n,t){if(n){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function As(n,t,e,i){const s=Rs(n);let r=0;r+=t;let a=0,o=0,u=0;for(;r<s.length;){a=0;do{if(r>=s.length)break;u=s[r++],a+=u}while(u===255);o=0;do{if(r>=s.length)break;u=s[r++],o+=u}while(u===255);const l=s.length-r;let d=r;if(o<l)r+=o;else if(o>l){J.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(s[d++]===181){const c=Ts(s,d);if(d+=2,c===49){const f=H(s,d);if(d+=4,f===1195456820){const g=s[d++];if(g===3){const p=s[d++],m=31&p,y=64&p,T=y?2+m*3:0,v=new Uint8Array(T);if(y){v[0]=p;for(let S=1;S<T;S++)v[S]=s[d++]}i.push({type:g,payloadType:a,pts:e,bytes:v})}}}}}else if(a===5&&o>16){const h=[];for(let g=0;g<16;g++){const p=s[d++].toString(16);h.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&h.push("-")}const c=o-16,f=new Uint8Array(c);for(let g=0;g<c;g++)f[g]=s[d++];i.push({payloadType:a,pts:e,uuid:h.join(""),userData:mt(f),userDataBytes:f})}}}function Rs(n){const t=n.byteLength,e=[];let i=1;for(;i<t-2;)n[i]===0&&n[i+1]===0&&n[i+2]===3?(e.push(i+2),i+=2):i++;if(e.length===0)return n;const s=t-e.length,r=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===e[0]&&(a++,e.shift()),r[i]=n[a];return r}function Hr(n){const t=n[0];let e="",i="",s=0,r=0,a=0,o=0,u=0,l=0;if(t===0){for(;nt(n.subarray(l,l+1))!=="\0";)e+=nt(n.subarray(l,l+1)),l+=1;for(e+=nt(n.subarray(l,l+1)),l+=1;nt(n.subarray(l,l+1))!=="\0";)i+=nt(n.subarray(l,l+1)),l+=1;i+=nt(n.subarray(l,l+1)),l+=1,s=H(n,12),r=H(n,16),o=H(n,20),u=H(n,24),l=28}else if(t===1){l+=4,s=H(n,l),l+=4;const h=H(n,l);l+=4;const c=H(n,l);for(l+=4,a=2**32*h+c,yr(a)||(a=Number.MAX_SAFE_INTEGER,J.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=H(n,l),l+=4,u=H(n,l),l+=4;nt(n.subarray(l,l+1))!=="\0";)e+=nt(n.subarray(l,l+1)),l+=1;for(e+=nt(n.subarray(l,l+1)),l+=1;nt(n.subarray(l,l+1))!=="\0";)i+=nt(n.subarray(l,l+1)),l+=1;i+=nt(n.subarray(l,l+1)),l+=1}const d=n.subarray(l,n.byteLength);return{schemeIdUri:e,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:u,payload:d}}const bs=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Kt={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 ii(n,t){const e=Kt[t];return!!e&&!!e[n.slice(0,4)]}function Zt(n,t,e=!0){return!n.split(",").some(i=>!si(i,t,e))}function si(n,t,e=!0){var i;const s=bt(e);return(i=s==null?void 0:s.isTypeSupported(Jt(n,t)))!=null?i:!1}function Jt(n,t){return`${t}/mp4;codecs=${n}`}function xi(n){if(n){const t=n.substring(0,4);return Kt.video[t]}return 2}function me(n){const t=bs();return n.split(",").reduce((e,i)=>{const r=t&&ei(i)?9:Kt.video[i];return r?(r*2+e)/(e?3:2):(Kt.audio[i]+e)/(e?2:1)},0)}const Ce={};function Wr(n,t=!0){if(Ce[n])return Ce[n];const e={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let s=0;s<e.length;s++){var i;if(si(e[s],"audio",t))return Ce[n]=e[s],e[s];if(e[s]==="mp3"&&(i=bt(t))!=null&&i.isTypeSupported("audio/mpeg"))return""}return n}const Yr=/flac|opus|mp4a\.40\.34/i;function pe(n,t=!0){return n.replace(Yr,e=>Wr(e.toLowerCase(),t))}function jr(n,t){const e=[];if(n){const i=n.split(",");for(let s=0;s<i.length;s++)ii(i[s],"video")||e.push(i[s])}return t&&e.push(t),e.join(",")}function fe(n,t){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(Li(n,"audio")||Li(n,"video")))return n;if(t){const e=t.split(",");if(e.length>1){if(n){for(let i=e.length;i--;)if(e[i].substring(0,4)===n.substring(0,4))return e[i]}return e[0]}}return t||n}function Li(n,t){return ii(n,t)&&si(n,t)}function qr(n){const t=n.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");i.length>2&&i[0]==="avc1"&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}function zr(n){if(n.startsWith("av01.")){const t=n.split("."),e=["0","111","01","01","01","0"];for(let i=t.length;i>4&&i<10;i++)t[i]=e[i-4];return t.join(".")}return n}function Ai(n){const t=bt(n)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function He(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const We=["NONE","TYPE-0","TYPE-1",null];function Xr(n){return We.indexOf(n)>-1}const Ee=["SDR","PQ","HLG"];function Qr(n){return!!n&&Ee.indexOf(n)>-1}var qt={No:"",Yes:"YES",v2:"v2"};function Ri(n){const{canSkipUntil:t,canSkipDateRanges:e,age:i}=n,s=i<t/2;return t&&s?e?qt.v2:qt.Yes:qt.No}class Ye{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 this.msn!==void 0&&e.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class ri{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(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=(e=t.supplemental)==null?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 bi(this._audioGroups,t)}hasSubtitleGroup(t){return bi(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e){if(t==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(e)===-1&&i.push(e)}else if(t==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(e)===-1&&i.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(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function bi(n,t){return!t||!n?!1:n.indexOf(t)!==-1}function Zr(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(n.media!==t.media)return n.matches===!0}return!1}function Jr(n,t){let e=!1,i=[];if(n&&(e=n!=="SDR",i=[n]),t){i=t.allowedVideoRanges||Ee.slice(0);const s=i.join("")!=="SDR"&&!t.videoCodec;e=t.preferHDR!==void 0?t.preferHDR:s&&Zr(),e||(i=["SDR"])}return{preferHDR:e,allowedVideoRanges:i}}const tn=n=>{const t=new WeakSet;return(e,i)=>{if(n&&(i=n(e,i)),typeof i=="object"&&i!==null){if(t.has(i))return;t.add(i)}return i}},ot=(n,t)=>JSON.stringify(n,tn(t));function en(n,t,e,i,s){const r=Object.keys(n),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,u=s==null?void 0:s.videoCodec,l=a&&parseInt(a)===2;let d=!1,h=!1,c=1/0,f=1/0,g=1/0,p=1/0,m=0,y=[];const{preferHDR:T,allowedVideoRanges:v}=Jr(t,s);for(let R=r.length;R--;){const b=n[r[R]];d||(d=b.channels[2]>0),c=Math.min(c,b.minHeight),f=Math.min(f,b.minFramerate),g=Math.min(g,b.minBitrate),v.filter(_=>b.videoRanges[_]>0).length>0&&(h=!0)}c=B(c)?c:0,f=B(f)?f:0;const S=Math.max(1080,c),A=Math.max(30,f);g=B(g)?g:e,e=Math.max(g,e),h||(t=void 0);const C=r.length>1;return{codecSet:r.reduce((R,b)=>{const I=n[b];if(b===R)return R;if(y=h?v.filter(_=>I.videoRanges[_]>0):[],C){if(I.minBitrate>e)return vt(b,`min bitrate of ${I.minBitrate} > current estimate of ${e}`),R;if(!I.hasDefaultAudio)return vt(b,"no renditions with default or auto-select sound found"),R;if(o&&b.indexOf(o.substring(0,4))%5!==0)return vt(b,`audio codec preference "${o}" not found`),R;if(a&&!l){if(!I.channels[a])return vt(b,`no renditions with ${a} channel sound found (channels options: ${Object.keys(I.channels)})`),R}else if((!o||l)&&d&&I.channels[2]===0)return vt(b,"no renditions with stereo sound found"),R;if(I.minHeight>S)return vt(b,`min resolution of ${I.minHeight} > maximum of ${S}`),R;if(I.minFramerate>A)return vt(b,`min framerate of ${I.minFramerate} > maximum of ${A}`),R;if(!y.some(_=>I.videoRanges[_]>0))return vt(b,`no variants with VIDEO-RANGE of ${ot(y)} found`),R;if(u&&b.indexOf(u.substring(0,4))%5!==0)return vt(b,`video codec preference "${u}" not found`),R;if(I.maxScore<m)return vt(b,`max score of ${I.maxScore} < selected max of ${m}`),R}return R&&(me(b)>=me(R)||I.fragmentError>n[R].fragmentError)?R:(p=I.minIndex,m=I.maxScore,b)},void 0),videoRanges:y,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:p}}function vt(n,t){J.log(`[abr] start candidates with "${n}" ignored because ${t}`)}function Is(n){return n.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 s=e.channels||"2";return i.channels[s]=(i.channels[s]||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 sn(n,t,e,i){return n.slice(e,i+1).reduce((s,r,a)=>{if(!r.codecSet)return s;const o=r.audioGroups;let u=s[r.codecSet];u||(s[r.codecSet]=u={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),u.minBitrate=Math.min(u.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return u.minHeight=Math.min(u.minHeight,l),u.minFramerate=Math.min(u.minFramerate,r.frameRate),u.minIndex=Math.min(u.minIndex,a),u.maxScore=Math.max(u.maxScore,r.score),u.fragmentError+=r.fragmentError,u.videoRanges[r.videoRange]=(u.videoRanges[r.videoRange]||0)+1,s},{})}function Ii(n,t){var e;return!!n&&n!==((e=t.loadLevelObj)==null?void 0:e.uri)}class Ds extends It{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=e=>{var i;const{fragCurrent:s,partCurrent:r,hls:a}=this,{autoLevelEnabled:o,media:u}=a;if(!s||!u)return;const l=performance.now(),d=r?r.stats:s.stats,h=r?r.duration:s.duration,c=l-d.loading.start,f=a.minAutoLevel,g=s.level,p=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const m=p>-1&&p!==g,y=!!e||m;if(!y&&(u.paused||!u.playbackRate||!u.readyState))return;const T=a.mainForwardBufferInfo;if(!y&&T===null)return;const v=this.bwEstimator.getEstimateTTFB(),S=Math.abs(u.playbackRate);if(c<=Math.max(v,1e3*(h/(S*2))))return;const A=T?T.len/S:0,C=d.loading.first?d.loading.first-d.loading.start:-1,x=d.loaded&&C>-1,R=this.getBwEstimate(),b=a.levels,I=b[g],_=Math.max(d.loaded,Math.round(h*(s.bitrate||I.averageBitrate)/8));let w=x?c-C:c;w<1&&x&&(w=Math.min(c,d.loaded*8/R));const $=x?d.loaded*1e3/w:0,V=v/1e3,N=$?(_-d.loaded)/$:_*8/R+V;if(N<=A)return;const P=$?$*8:R,G=((i=(e==null?void 0:e.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,M=this.hls.config.abrBandWidthUpFactor;let U=Number.POSITIVE_INFINITY,K;for(K=g-1;K>f;K--){const Z=b[K].maxBitrate,Q=!b[K].details||G;if(U=this.getTimeToLoadFrag(V,P,h*Z,Q),U<Math.min(A,h+V))break}if(U>=N||U>h*10)return;x?this.bwEstimator.sample(c-Math.min(v,C),d.loaded):this.bwEstimator.sampleTTFB(c);const O=b[K].maxBitrate;this.getBwEstimate()*M>O&&this.resetEstimator(O);const F=this.findBestLevel(O,f,K,0,A,1,1);F>-1&&(K=F),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
2
+ Fragment duration: ${s.duration.toFixed(3)}
3
+ Time to underbuffer: ${A.toFixed(3)} s
4
+ Estimated load time for current fragment: ${N.toFixed(3)} s
5
+ Estimated load time for down switch fragment: ${U.toFixed(3)} s
6
+ TTFB estimate: ${C|0} ms
7
+ Current BW estimate: ${B(R)?R|0:"Unknown"} bps
8
+ New BW estimate: ${this.getBwEstimate()|0} bps
9
+ Switching to level ${K} @ ${O|0} bps`),a.nextLoadLevel=a.nextAutoLevel=K,this.clearTimer();const z=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===K&&K>0){const Z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${K>0?"and switching down":""}
10
+ Fragment duration: ${s.duration.toFixed(3)} s
11
+ Time to underbuffer: ${Z.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,K>f){let Q=this.findBestLevel(this.hls.levels[f].bitrate,f,K,0,Z,1,1);Q===-1&&(Q=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Q,this.resetEstimator(this.hls.levels[Q].bitrate)}}};m||N>U*2?z():this.timer=self.setInterval(z,U*1e3),a.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:d})},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 Sr(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.FRAG_LOADING,this.onFragLoading,this),t.on(E.FRAG_LOADED,this.onFragLoaded,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.FRAG_LOADING,this.onFragLoading,this),t.off(E.FRAG_LOADED,this.onFragLoaded,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(E.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)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=e.part)!=null?s: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 D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case D.FRAG_LOAD_TIMEOUT:{const i=e.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const a=performance.now(),o=r?r.stats:i.stats,u=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(u-Math.min(h,l),o.loaded)}else this.bwEstimator.sampleTTFB(u)}break}}}getTimeToLoadFrag(t,e,i,s){const r=t+i/e,a=s?t+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(t,e){const i=this.hls.config,{loading:s}=e.stats,r=s.end-s.first;B(r)&&(this.lastLevelLoadSec=r/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 s=i?i.stats:e.stats;if(e.type===W.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:e.duration,a=this.hls.levels[e.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,u=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:u},a.realBitrate=Math.round(8*o/u)}if(e.bitrateTest){const r={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(E.FRAG_BUFFERED,r),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==W.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,e,t,0,s,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,e),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(t!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const r=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const a=this.hls.levels;if(a.length>Math.max(t,r)&&a[t].loadError<=a[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:s,config:r,minAutoLevel:a}=i,o=e?e.duration:t?t.duration:0,u=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const m=this.findBestLevel(u,a,s,l,0,d,h);if(m>=0)return this.rebufferNotice=-1,m}let c=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const m=this.bitrateTestDelay;m&&(c=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1)}const f=this.findBestLevel(u,a,s,l,c,d,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=i.levels[a],p=i.loadLevelObj;return p&&(g==null?void 0:g.bitrate)<p.bitrate?a:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&e.playbackRate!==0?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,s,r,a,o){var u;const l=s+r,d=this.lastLoadedFragLevel,h=d===-1?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:f}=this,{levels:g,allAudioTracks:p,loadLevel:m,config:y}=this.hls;if(g.length===1)return 0;const T=g[h],v=!!((u=this.hls.latestLevelDetails)!=null&&u.live),S=m===-1||d===-1;let A,C="SDR",x=(T==null?void 0:T.frameRate)||0;const{audioPreference:R,videoPreference:b}=y,I=this.audioTracksByGroup||(this.audioTracksByGroup=Is(p));let _=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const P=this.codecTiers||(this.codecTiers=sn(g,I,e,i)),G=en(P,C,t,R,b),{codecSet:M,videoRanges:U,minFramerate:K,minBitrate:O,minIndex:F,preferHDR:z}=G;_=F,A=M,C=z?U[U.length-1]:U[0],x=K,t=Math.max(t,O),this.log(`picked start tier ${ot(G)}`)}else A=T==null?void 0:T.codecSet,C=T==null?void 0:T.videoRange;const w=f?f.duration:c?c.duration:0,$=this.bwEstimator.getEstimateTTFB()/1e3,V=[];for(let P=i;P>=e;P--){var N;const G=g[P],M=P>h;if(!G)continue;if((A&&G.codecSet!==A||C&&G.videoRange!==C||M&&x>G.frameRate||!M&&x>0&&x<G.frameRate||(N=G.supportedResult)!=null&&(N=N.decodingInfoResults)!=null&&N.some(Q=>Q.smooth===!1))&&(!S||P!==_)){V.push(P);continue}const U=G.details,K=(f?U==null?void 0:U.partTarget:U==null?void 0:U.averagetargetduration)||w;let O;M?O=o*t:O=a*t;const F=w&&s>=w*2&&r===0?G.averageBitrate:G.maxBitrate,z=this.getTimeToLoadFrag($,O,F*K,U===void 0);if(O>=F&&(P===d||G.loadError===0&&G.fragmentError===0)&&(z<=$||!B(z)||v&&!this.bitrateTestDelay||z<l)){const Q=this.forcedAutoLevel;return P!==m&&(Q===-1||Q!==m)&&(V.length&&this.trace(`Skipped level(s) ${V.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[V[0]].codecs}" ${g[V[0]].videoRange}; not compatible with "${A}" ${C}`),this.info(`switch candidate:${h}->${P} adjustedbw(${Math.round(O)})-bitrate=${Math.round(O-F)} ttfb:${$.toFixed(1)} avgDuration:${K.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${z.toFixed(1)} firstSelection:${S} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${m}`)),S&&(this.firstSelection=P),P}}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)}}const Cs={search:function(n,t){let e=0,i=n.length-1,s=null,r=null;for(;e<=i;){s=(e+i)/2|0,r=n[s];const a=t(r);if(a>0)e=s+1;else if(a<0)i=s-1;else return r}return null}};function rn(n,t,e){if(t===null||!Array.isArray(n)||!n.length||!B(t))return null;const i=n[0].programDateTime;if(t<(i||0))return null;const s=n[n.length-1].endProgramDateTime;if(t>=(s||0))return null;for(let r=0;r<n.length;++r){const a=n[r];if(an(t,e,a))return a}return null}function ni(n,t,e=0,i=0,s=.005){let r=null;if(n){r=t[1+n.sn-t[0].sn]||null;const o=n.endDTS-e;o>0&&o<15e-7&&(e+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=t[2+n.sn-t[0].sn]||null)}else e===0&&t[0].start===0&&(r=t[0]);if(r&&((!n||n.level===r.level)&&Di(e,i,r)===0||nn(r,n,Math.min(s,i))))return r;const a=Cs.search(t,Di.bind(null,e,i));return a&&(a!==n||!r)?a:r}function nn(n,t,e){if(t&&t.start===0&&t.level<n.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((s,r)=>(r[0]==="INF"&&(s+=parseFloat(r[1])),s),e);return n.start<=i}return!1}function Di(n=0,t=0,e){if(e.start<=n&&e.start+e.duration>n)return 0;const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-i<=n?1:e.start-i>n&&e.start?-1:0}function an(n,t,e){const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-i>n}function on(n,t,e){if(n&&n.startCC<=t&&n.endCC>=t){let i=n.fragments;const{fragmentHint:s}=n;s&&(i=i.concat(s));let r;return Cs.search(i,a=>a.cc<t?1:a.cc>t?-1:(r=a,a.end<=e?1:a.start>e?-1:0)),r||null}return null}function ve(n){switch(n.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function _s(n){return n.details.startsWith("key")}function Ps(n){return _s(n)&&!!n.frag&&!n.frag.decryptdata}function Ci(n,t){const e=ve(t);return n.default[`${e?"timeout":"error"}Retry`]}function ai(n,t){const e=n.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*n.retryDelayMs,n.maxRetryDelayMs)}function _i(n){return ft(ft({},n),{errorRetry:null,timeoutRetry:null})}function ye(n,t,e,i){if(!n)return!1;const s=i==null?void 0:i.code,r=t<n.maxNumRetry&&(ln(s)||!!e);return n.shouldRetry?n.shouldRetry(n,t,e,i,r):r}function ln(n){return je(n)||!!n&&(n<400||n>499)}function je(n){return n===0&&navigator.onLine===!1}var st={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},lt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class ks extends It{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(E.ERROR,this.onError,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(E.ERROR,this.onError,this),t.off(E.ERROR,this.onErrorOut,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(t==null?void 0:t.type)===W.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return(t=e.loadLevelObj)!=null&&t.details||i===-1?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if((i=t.details)!=null&&i.hasKey(e))return!0;const s=t.audioGroups;if(s)return this.hls.allAudioTracks.filter(a=>s.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const s=this.hls,r=e.context;switch(e.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case D.FRAG_PARSING_ERROR:if((i=e.frag)!=null&&i.gap){e.errorAction=zt();return}case D.FRAG_GAP:case D.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=st.SendAlternateToPenaltyBox;return}case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var a;const u=e.parent===W.MAIN?e.level:s.loadLevel;e.details===D.LEVEL_EMPTY_ERROR&&((a=e.context)!=null&&(a=a.levelDetails)!=null&&a.live)?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,u):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,u))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const u=s.loadLevelObj;if(u&&(r.type===X.AUDIO_TRACK&&u.hasAudioGroup(r.groupId)||r.type===X.SUBTITLE_TRACK&&u.hasSubtitleGroup(r.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=st.SendAlternateToPenaltyBox,e.errorAction.flags=lt.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:e.errorAction={action:st.SendAlternateToPenaltyBox,flags:lt.MoveAllAlternatesMatchingHDCP};return;case D.KEY_SYSTEM_SESSION_UPDATE_FAILED:case D.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case D.KEY_SYSTEM_NO_SESSION:e.errorAction={action:st.SendAlternateToPenaltyBox,flags:lt.MoveAllAlternatesMatchingKey};return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:case D.BUFFER_APPEND_ERROR:if(!e.errorAction){var o;e.errorAction=this.getLevelSwitchAction(e,(o=e.level)!=null?o:s.loadLevel)}return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:e.errorAction=zt();return}e.type===Y.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=zt())}getPlaylistRetryOrSwitchAction(t,e){const i=this.hls,s=Ci(i.config.playlistLoadPolicy,t),r=this.playlistError++;if(ye(s,r,ve(t),t.response))return{action:st.RetryRequest,flags:lt.None,retryConfig:s,retryCount:r};const o=this.getLevelSwitchAction(t,e);return s&&(o.retryConfig=s,o.retryCount=r),o}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=e.config,o=Ci(_s(t)?a:r,t),u=e.levels.reduce((d,h)=>d+h.fragmentError,0);if(s&&(t.details!==D.FRAG_GAP&&s.fragmentError++,!Ps(t)&&ye(o,u,ve(t),t.response)))return{action:st.RetryRequest,flags:lt.None,retryConfig:o,retryCount:u};const l=this.getLevelSwitchAction(t,i);return o&&(l.retryConfig=o,l.retryCount=u),l}getLevelSwitchAction(t,e){const i=this.hls;e==null&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,a;const l=t.details;s.loadError++,l===D.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1;const{levels:h,loadLevel:c,minAutoLevel:f,maxAutoLevel:g}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const p=(r=t.frag)==null?void 0:r.type,y=(p===W.AUDIO&&l===D.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(l===D.BUFFER_ADD_CODEC_ERROR||l===D.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:C})=>s.audioCodec!==C),v=t.sourceBufferName==="video"&&(l===D.BUFFER_ADD_CODEC_ERROR||l===D.BUFFER_APPEND_ERROR)&&h.some(({codecSet:C,audioCodec:x})=>s.codecSet!==C&&s.audioCodec===x),{type:S,groupId:A}=(a=t.context)!=null?a:{};for(let C=h.length;C--;){const x=(C+c)%h.length;if(x!==c&&x>=f&&x<=g&&h[x].loadError===0){var o,u;const R=h[x];if(l===D.FRAG_GAP&&p===W.MAIN&&t.frag){const b=h[x].details;if(b){const I=ni(t.frag,b.fragments,t.frag.start);if(I!=null&&I.gap)continue}}else{if(S===X.AUDIO_TRACK&&R.hasAudioGroup(A)||S===X.SUBTITLE_TRACK&&R.hasSubtitleGroup(A))continue;if(p===W.AUDIO&&(o=s.audioGroups)!=null&&o.some(b=>R.hasAudioGroup(b))||p===W.SUBTITLE&&(u=s.subtitleGroups)!=null&&u.some(b=>R.hasSubtitleGroup(b))||y&&s.audioCodec===R.audioCodec||v&&s.codecSet===R.codecSet||!y&&s.codecSet!==R.codecSet)continue}d=x;break}}if(d>-1&&i.loadLevel!==d)return t.levelRetry=!0,this.playlistError=0,{action:st.SendAlternateToPenaltyBox,flags:lt.None,nextAutoLevel:d}}return{action:st.SendAlternateToPenaltyBox,flags:lt.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i;switch((i=e.errorAction)==null?void 0:i.action){case st.DoNothing:break;case st.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==D.FRAG_GAP?e.fatal=!0:/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());break;case st.RetryRequest:break}if(e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case lt.None:this.switchLevel(t,r);break;case lt.MoveAllAlternatesMatchingHDCP:{const u=this.getVariantLevelIndex(t.frag),l=e.levels[u],d=l==null?void 0:l.attrs["HDCP-LEVEL"];if(i.hdcpLevel=d,d==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(d){e.maxHdcpLevel=We[We.indexOf(d)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case lt.MoveAllAlternatesMatchingKey:{const u=t.decryptdata;if(u){const l=this.hls.levels,d=l.length;for(let c=d;c--;)if(this.variantHasKey(l[c],u)){var a,o;this.log(`Banned key found in level ${c} (${l[c].bitrate}bps) or audio group "${(a=l[c].audioGroups)==null?void 0:a.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${Vt(u.keyId||[])}`),l[c].fragmentError++,l[c].loadError++,this.log(`Removing level ${c} with key error (${t.error})`),this.hls.removeLevel(c)}const h=t.frag;if(this.hls.levels.length<d)i.resolved=!0;else if(h&&h.type!==W.MAIN){const c=h.decryptdata;c&&!u.matches(c)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(e!==void 0&&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===D.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&t.sourceBufferName!=="audiovideo")){const i=He(t.mimeType),s=this.hls.levels;for(let r=s.length;r--;)s[r][`${t.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${r} for ${t.details} ("${i}" not supported)`),this.hls.removeLevel(r))}}}function zt(n){const t={action:st.DoNothing,flags:lt.None};return n&&(t.resolved=!0),t}const un=/^(\d+)x(\d+)$/,Pi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class tt{constructor(t,e){typeof t=="string"&&(t=tt.parseAttrList(t,e)),at(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}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=(e.length&1?"0":"")+e;const i=new Uint8Array(e.length/2);for(let s=0;s<e.length/2;s++)i[s]=parseInt(e.slice(s*2,s*2+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((s,r)=>(s[r.toLowerCase()]=!0,s),e)}bool(t){return this[t]==="YES"}decimalResolution(t){const e=un.exec(this[t]);if(e!==null)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const s={};for(Pi.lastIndex=0;(i=Pi.exec(t))!==null;){const a=i[1].trim();let o=i[2];const u=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let l=!1;if(u)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(!(e&&(u||l))){if(!l&&!u)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":J.warn(`${t}: attribute ${a} is missing quotes`)}}s[a]=o}return s}}const dn="com.apple.hls.interstitial";function hn(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function cn(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class oi{constructor(t,e,i=0){var s;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=(e==null?void 0:e.tagAnchor)||null,this.tagOrder=(s=e==null?void 0:e.tagOrder)!=null?s:i,e){const r=e.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(t,a)&&t[a]!==r[a]){J.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=a;break}t=at(new tt({}),r,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 r=(e==null?void 0:e.endDate)||new Date(this.attr["END-DATE"]);B(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return t===void 0?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 t===null||t.programDateTime===null?(J.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 e!==null?this._dateAtEnd=new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(B(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 this.class===dn}get isValid(){return!!this.id&&!this._badValueForSameId&&B(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const fn=10;class Os{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){this.advanced=!0,this.updated=!0;return}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||e===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return this.fragments.length?B(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||fn}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&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(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(e!==-1){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&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 Fs(n,t){return n.length===t.length?!n.some((e,i)=>e!==t[i]):!1}function ki(n,t){return!n&&!t?!0:!n||!t?!1:Fs(n,t)}var kt={cbc:0,ctr:1};function Xt(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function ws(n){switch(n){case"AES-128":case"AES-256":return kt.cbc;case"AES-256-CTR":return kt.ctr;default:throw new Error(`invalid full segment method ${n}`)}}let re={};class Ht{static clearKeyUriToKeyIdMap(){re={}}static setKeyIdForUri(t,e){re[t]=e}static addKeyIdForUri(t){const e=Object.keys(re).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),re[t]=i,i}constructor(t,e,i,s=[1],r=null,a){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=s,this.iv=r,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Xt(t),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(ps(a)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Fs(t.keyFormatVersions,this.keyFormatVersions)&&ki(t.iv,this.iv)&&ki(t.keyId,this.keyId)}isSupported(){if(this.method){if(Xt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES"}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(Xt(this.method)){let i=this.iv;return i||(typeof t!="number"&&(J.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=gn(t)),new Ht(this.method,this.uri,"identity",this.keyFormatVersions,i)}return this}}function gn(n){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=n>>8*(15-e)&255;return t}const Oi=/#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,Fi=/#EXT-X-MEDIA:(.*)/g,mn=/^#EXT(?:INF|-X-TARGETDURATION):/m,_e=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),pn=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 gt{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static resolve(t,e){return Je.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return mn.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},r=[];if(Oi.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=Oi.exec(t))!=null;)if(a[1]){var o;const l=new tt(a[1],s),d=a[2],h={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:gt.resolve(d,e)},c=l.decimalResolution("RESOLUTION");c&&(h.width=c.width,h.height=c.height),Ni(l.CODECS,h);const f=l["SUPPLEMENTAL-CODECS"];f&&(h.supplemental={},Ni(f,h.supplemental)),(o=h.unknownCodecs)!=null&&o.length||r.push(h),s.levels.push(h)}else if(a[3]){const l=a[3],d=a[4];switch(l){case"SESSION-DATA":{const h=new tt(d,s),c=h["DATA-ID"];c&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[c]=h);break}case"SESSION-KEY":{const h=wi(d,e,s);h.encrypted&&h.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(h)):J.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const h=new tt(d,s);s.contentSteering={uri:gt.resolve(h["SERVER-URI"],e),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=Mi(d);break}}}const u=r.length>0&&r.length<s.levels.length;return s.levels=u?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,i){let s;const r={},a=i.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let u=0;for(Fi.lastIndex=0;(s=Fi.exec(t))!==null;){const l=new tt(s[1],i),d=l.TYPE;if(d){const h=o[d],c=r[d]||[];r[d]=c;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],p=l.CHANNELS,m=l.CHARACTERISTICS,y=l["INSTREAM-ID"],T={attrs:l,bitrate:0,id:u++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:d,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?gt.resolve(l.URI,e):""};if(g&&(T.assocLang=g),p&&(T.channels=p),m&&(T.characteristics=m),y&&(T.instreamId=y),h!=null&&h.length){const v=gt.findGroup(h,T.groupId)||h[0];Bi(T,v,"audioCodec"),Bi(T,v,"textCodec")}c.push(T)}}return r}static parseLevelPlaylist(t,e,i,s,r,a){var o;const u={url:e},l=new Os(e),d=l.fragments,h=[];let c=null,f=0,g=0,p=0,m=0,y=0,T=null,v=new ce(s,u),S,A,C,x=-1,R=!1,b=null,I;if(_e.lastIndex=0,l.m3u8=t,l.hasVariableRefs=!1,((o=_e.exec(t))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=_e.exec(t))!==null;){R&&(R=!1,v=new ce(s,u),v.playlistOffset=p,v.setStart(p),v.sn=f,v.cc=m,y&&(v.bitrate=y),v.level=i,c&&(v.initSegment=c,c.rawProgramDateTime&&(v.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null),b&&(v.setByteRange(b),b=null)));const V=S[1];if(V){v.duration=parseFloat(V);const N=(" "+S[2]).slice(1);v.title=N||null,v.tagList.push(N?["INF",V,N]:["INF",V])}else if(S[3]){if(B(v.duration)){v.playlistOffset=p,v.setStart(p),C&&Ui(v,C,l),v.sn=f,v.level=i,v.cc=m,d.push(v);const N=(" "+S[3]).slice(1);v.relurl=N,qe(v,T,h),T=v,p+=v.duration,f++,g=0,R=!0}}else{if(S=S[0].match(pn),!S){J.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<S.length&&S[A]===void 0;A++);const N=(" "+S[A]).slice(1),P=(" "+S[A+1]).slice(1),G=S[A+2]?(" "+S[A+2]).slice(1):null;switch(N){case"BYTERANGE":T?v.setByteRange(P,T):v.setByteRange(P);break;case"PROGRAM-DATE-TIME":v.rawProgramDateTime=P,v.tagList.push(["PROGRAM-DATE-TIME",P]),x===-1&&(x=d.length);break;case"PLAYLIST-TYPE":l.type&&xt(l,N,S),l.type=P.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?xt(l,N,S):d.length>0&&Gi(l,N,S),f=l.startSN=parseInt(P);break;case"SKIP":{l.skippedSegments&&xt(l,N,S);const M=new tt(P,l),U=M.decimalInteger("SKIPPED-SEGMENTS");if(B(U)){l.skippedSegments+=U;for(let O=U;O--;)d.push(null);f+=U}const K=M.enumeratedString("RECENTLY-REMOVED-DATERANGES");K&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(K.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&xt(l,N,S),l.targetduration=Math.max(parseInt(P),1);break;case"VERSION":l.version!==null&&xt(l,N,S),l.version=parseInt(P);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||xt(l,N,S),l.live=!1;break;case"#":(P||G)&&v.tagList.push(G?[P,G]:[P]);break;case"DISCONTINUITY":m++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([N]);break;case"BITRATE":v.tagList.push([N,P]),y=parseInt(P)*1e3,B(y)?v.bitrate=y:y=0;break;case"DATERANGE":{const M=new tt(P,l),U=new oi(M,l.dateRanges[M.ID],l.dateRangeTagCount);l.dateRangeTagCount++,U.isValid||l.skippedSegments?l.dateRanges[U.id]=U:J.warn(`Ignoring invalid DATERANGE tag: "${P}"`),v.tagList.push(["EXT-X-DATERANGE",P]);break}case"DEFINE":break;case"DISCONTINUITY-SEQUENCE":l.startCC!==0?xt(l,N,S):d.length>0&&Gi(l,N,S),l.startCC=m=parseInt(P);break;case"KEY":{const M=wi(P,e,l);if(M.isSupported()){if(M.method==="NONE"){C=void 0;break}C||(C={});const U=C[M.keyFormat];U!=null&&U.matches(M)||(U&&(C=at({},C)),C[M.keyFormat]=M)}else J.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${P}" (light build)`);break}case"START":l.startTimeOffset=Mi(P);break;case"MAP":{const M=new tt(P,l);if(v.duration){const U=new ce(s,u);$i(U,M,i,C),c=U,v.initSegment=c,c.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=c.rawProgramDateTime)}else{const U=v.byteRangeEndOffset;if(U){const K=v.byteRangeStartOffset;b=`${U-K}@${K}`}else b=null;$i(v,M,i,C),c=v,R=!0}c.cc=m;break}case"SERVER-CONTROL":{I&&xt(l,N,S),I=new tt(P),l.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),l.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&xt(l,N,S);const M=new tt(P);l.partTarget=M.decimalFloatingPoint("PART-TARGET");break}case"PART":{let M=l.partList;M||(M=l.partList=[]);const U=g>0?M[M.length-1]:void 0,K=g++,O=new tt(P,l),F=new Es(O,v,u,K,U);M.push(F),v.duration+=F.duration;break}case"PRELOAD-HINT":{const M=new tt(P,l);l.preloadHint=M;break}case"RENDITION-REPORT":{const M=new tt(P,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(M);break}default:J.warn(`line parsed but not handled: ${S}`);break}}}T&&!T.relurl?(d.pop(),p-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(qe(v,T,h),v.cc=m,l.fragmentHint=v,C&&Ui(v,C,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const _=d.length,w=d[0],$=d[_-1];if(p+=l.skippedSegments*l.targetduration,p>0&&_&&$){l.averagetargetduration=p/_;const V=$.sn;l.endSN=V!=="initSegment"?V:0,l.live||($.endList=!0),x>0&&(vn(d,x),w&&h.unshift(w))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,h.length&&l.dateRangeTagCount&&w&&Ms(h,l),l.endCC=m,l}}function Ms(n,t){let e=n.length;if(!e)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];n.push(o),e++}else return;const i=n[e-1],s=t.live?1/0:t.totalduration,r=Object.keys(t.dateRanges);for(let o=r.length;o--;){const u=t.dateRanges[r[o]],l=u.startDate.getTime();u.tagAnchor=i.ref;for(let d=e;d--;){var a;if(((a=n[d])==null?void 0:a.sn)<t.startSN)break;const h=En(t,l,n,d,s);if(h!==-1){u.tagAnchor=t.fragments[h].ref;break}}}}function En(n,t,e,i,s){const r=e[i];if(r){const o=r.programDateTime;if(t>=o||i===0){var a;const u=(((a=e[i+1])==null?void 0:a.start)||s)-r.start;if(t<=o+u*1e3){const l=e[i].sn-n.startSN;if(l<0)return-1;const d=n.fragments;if(d.length>e.length){const c=(e[i+1]||d[d.length-1]).sn-n.startSN;for(let f=c;f>l;f--){const g=d[f].programDateTime;if(t>=g&&t<g+d[f].duration*1e3)return f}}return l}}}return-1}function wi(n,t,e){var i,s;const r=new tt(n,e),a=(i=r.METHOD)!=null?i:"",o=r.URI,u=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,d=(s=r.KEYFORMAT)!=null?s:"identity";o&&r.IV&&!u&&J.error(`Invalid IV: ${r.IV}`);const h=o?gt.resolve(o,t):"",c=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Ht(a,h,d,c,u,r.KEYID)}function Mi(n){const e=new tt(n).decimalFloatingPoint("TIME-OFFSET");return B(e)?e:null}function Ni(n,t){let e=(n||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=e.filter(r=>ii(r,i));s.length&&(t[`${i}Codec`]=s.map(r=>r.split("/")[0]).join(","),e=e.filter(r=>s.indexOf(r)===-1))}),t.unknownCodecs=e}function Bi(n,t,e){const i=t[e];i&&(n[e]=i)}function vn(n,t){let e=n[t];for(let i=t;i--;){const s=n[i];if(!s)return;s.programDateTime=e.programDateTime-s.duration*1e3,e=s}}function qe(n,t,e){n.rawProgramDateTime?e.push(n):t!=null&&t.programDateTime&&(n.programDateTime=t.endProgramDateTime)}function $i(n,t,e,i){n.relurl=t.URI,t.BYTERANGE&&n.setByteRange(t.BYTERANGE),n.level=e,n.sn="initSegment",i&&(n.levelkeys=i),n.initSegment=null}function Ui(n,t,e){n.levelkeys=t;const{encryptedFragments:i}=e;(!i.length||i[i.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&i.push(n)}function xt(n,t,e){n.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${e[0]})`)}function Gi(n,t,e){n.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${e[0]})`)}function Pe(n,t){const e=t.startPTS;if(B(e)){let i=0,s;t.sn>n.sn?(i=e-n.start,s=n):(i=n.start-e,s=t),s.duration!==i&&s.setDuration(i)}else t.sn>n.sn?n.cc===t.cc&&n.minEndPTS?t.setStart(n.start+(n.minEndPTS-n.start)):t.setStart(n.start+n.duration):t.setStart(Math.max(n.start-t.duration,0))}function Ns(n,t,e,i,s,r,a){i-e<=0&&(a.warn("Fragment should have a positive duration",t),i=e+t.duration,r=s+t.duration);let u=e,l=i;const d=t.startPTS,h=t.endPTS;if(B(d)){const y=Math.abs(d-e);n&&y>n.totalduration?a.warn(`media timestamps and playlist times differ by ${y}s for level ${t.level} ${n.url}`):B(t.deltaPTS)?t.deltaPTS=Math.max(y,t.deltaPTS):t.deltaPTS=y,u=Math.max(e,d),e=Math.min(e,d),s=t.startDTS!==void 0?Math.min(s,t.startDTS):s,l=Math.min(i,h),i=Math.max(i,h),r=t.endDTS!==void 0?Math.max(r,t.endDTS):r}const c=e-t.start;t.start!==0&&t.setStart(e),t.setDuration(i-t.start),t.startPTS=e,t.maxStartPTS=u,t.startDTS=s,t.endPTS=i,t.minEndPTS=l,t.endDTS=r;const f=t.sn;if(!n||f<n.startSN||f>n.endSN)return 0;let g;const p=f-n.startSN,m=n.fragments;for(m[p]=t,g=p;g>0;g--)Pe(m[g],m[g-1]);for(g=p;g<m.length-1;g++)Pe(m[g],m[g+1]);return n.fragmentHint&&Pe(m[m.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,c}function yn(n,t,e){if(n===t)return;let i=null;const s=n.fragments;for(let d=s.length-1;d>=0;d--){const h=s[d].initSegment;if(h){i=h;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;xn(n,t,(d,h,c,f)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==d.cc){const g=d.cc-h.cc;for(let p=c;p<f.length;p++)f[p].cc+=g;t.endCC=f[f.length-1].cc}B(d.startPTS)&&B(d.endPTS)&&(h.setStart(h.startPTS=d.startPTS),h.startDTS=d.startDTS,h.maxStartPTS=d.maxStartPTS,h.endPTS=d.endPTS,h.endDTS=d.endDTS,h.minEndPTS=d.minEndPTS,h.setDuration(d.endPTS-d.startPTS),h.duration&&(r=h),t.PTSKnown=t.alignedSliding=!0),d.hasStreams&&(h.elementaryStreams=d.elementaryStreams),h.loader=d.loader,d.hasStats&&(h.stats=d.stats),d.initSegment&&(h.initSegment=d.initSegment,i=d.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach(d=>{var h;d&&(!d.initSegment||d.initSegment.relurl===((h=i)==null?void 0:h.relurl))&&(d.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(d=>!d),t.deltaUpdateFailed){e.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=t.skippedSegments;d--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=Tn(n.dateRanges,t,e));const d=n.fragments.filter(h=>h.rawProgramDateTime);if(n.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&qe(o[h],o[h-1],d);Ms(d,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var u;const d=Us(n,t.startSN-1);t.startCC=(u=d==null?void 0:d.cc)!=null?u:a[0].cc}Sn(n.partList,t.partList,(d,h)=>{h.elementaryStreams=d.elementaryStreams,h.stats=d.stats}),r?Ns(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,e):Bs(n,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=n.driftStartTime,t.driftStart=n.driftStart;const l=t.advancedDateTime;if(t.advanced&&l){const d=t.edge;t.driftStart||(t.driftStartTime=l,t.driftStart=d),t.driftEndTime=l,t.driftEnd=d}else t.driftEndTime=n.driftEndTime,t.driftEnd=n.driftEnd,t.advancedDateTime=n.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=n.requestScheduled)}function Tn(n,t,e){const{dateRanges:i,recentlyRemovedDateranges:s}=t,r=at({},n);s&&s.forEach(u=>{delete r[u]});const o=Object.keys(r).length;return o?(Object.keys(i).forEach(u=>{const l=r[u],d=new oi(i[u].attr,l);d.isValid?(r[u]=d,l||(d.tagOrder+=o)):e.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ot(i[u].attr)}"`)}),r):i}function Sn(n,t,e){if(n&&t){let i=0;for(let s=0,r=n.length;s<=r;s++){const a=n[s],o=t[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?e(a,o):i--}}}function xn(n,t,e){const i=t.skippedSegments,s=Math.max(n.startSN,t.startSN)-t.startSN,r=(n.fragmentHint?1:0)+(i?t.endSN:Math.min(n.endSN,t.endSN))-t.startSN,a=t.startSN-n.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let l=s;l<=r;l++){const d=u[a+l];let h=o[l];if(i&&!h&&d&&(h=t.fragments[l]=d),d&&h){e(d,h,l,o);const c=d.relurl,f=h.relurl;if(c&&An(c,f)){t.playlistParsingError=Vi(`media sequence mismatch ${h.sn}:`,n,t,d,h);return}else if(d.cc!==h.cc){t.playlistParsingError=Vi(`discontinuity sequence mismatch (${d.cc}!=${h.cc})`,n,t,d,h);return}}}}function Vi(n,t,e,i,s){return new Error(`${n} ${s.url}
12
+ Playlist starting @${t.startSN}
13
+ ${t.m3u8}
14
+
15
+ Playlist starting @${e.startSN}
16
+ ${e.m3u8}`)}function Bs(n,t,e=!0){const i=t.startSN+t.skippedSegments-n.startSN,s=n.fragments,r=i>=0;let a=0;if(r&&i<s.length)a=s[i].start;else if(r&&t.startSN===n.endSN+1)a=n.fragmentEnd;else if(r&&e)a=n.fragmentStart+i*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)a=n.fragmentStart;else return;Ln(t,a)}function Ln(n,t){if(t){const e=n.fragments;for(let i=n.skippedSegments;i<e.length;i++)e[i].addStart(t);n.fragmentHint&&n.fragmentHint.addStart(t)}}function $s(n,t=1/0){let e=1e3*n.targetduration;if(n.updated){const i=n.fragments;if(i.length&&e*4>t){const r=i[i.length-1].duration*1e3;r<e&&(e=r)}}else e/=2;return Math.round(e)}function Us(n,t,e){if(!n)return null;let i=n.fragments[t-n.startSN];return i||(i=n.fragmentHint,i&&i.sn===t)?i:t<n.startSN&&e&&e.sn===t?e:null}function Ki(n,t,e){return n?Gs(n.partList,t,e):null}function Gs(n,t,e){if(n)for(let i=n.length;i--;){const s=n[i];if(s.index===e&&s.fragment.sn===t)return s}return null}function Vs(n){n.forEach((t,e)=>{var i;(i=t.details)==null||i.fragments.forEach(s=>{s.level=e,s.initSegment&&(s.initSegment.level=e)})})}function An(n,t){return n!==t&&t?Hi(n)!==Hi(t):!1}function Hi(n){return n.replace(/\?[^?]*$/,"")}class Ks extends It{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(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const s=e==null?void 0:e.renditionReports;if(s){let r=-1;for(let a=0;a<s.length;a++){const o=s[a];let u;try{u=new self.URL(o.URI,e.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),u=o.URI||""}if(u===t){r=a;break}else u===t.substring(0,u.length)&&(r=a)}if(r!==-1){const a=s[r],o=parseInt(a["LAST-MSN"])||e.lastPartSn;let u=parseInt(a["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(e.age-e.partTarget,e.targetduration);u>=0&&d>e.partTarget&&(u+=1)}const l=i&&Ri(i);return new Ye(o,u>=0?u:void 0,l)}}}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(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return t}playlistLoaded(t,e,i){const{details:s,stats:r}=e,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;s.advancedDateTime=Date.now()-o;const u=this.hls.config.timelineOffset;if(u!==s.appliedTimelineOffset){const d=Math.max(u||0,0);s.appliedTimelineOffset=d,s.fragments.forEach(h=>{h.setStart(h.playlistOffset+d)})}if(s.live||i!=null&&i.live){const d="levelInfo"in e?e.levelInfo:e.track;if(s.reloaded(i),i&&s.fragments.length>0){yn(i,s,this);const T=s.playlistParsingError;if(T){this.warn(T);const v=this.hls;if(!v.config.ignorePlaylistParsingErrors){var l;const{networkDetails:S}=e;v.trigger(E.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:T,reason:T.message,level:e.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:S,stats:r});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,c=h?h.end-h.len:0,f=(s.edge-c)*1e3,g=$s(s,f);if(s.requestScheduled+g<a?s.requestScheduled=a:s.requestScheduled+=g,this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let p,m,y;if(s.canBlockReload&&s.endSN&&s.advanced){const T=this.hls.config.lowLatencyMode,v=s.lastPartSn,S=s.endSN,A=s.lastPartIndex,C=A!==-1,x=v===S;C?x?(m=S+1,y=T?0:A):(m=v,y=T?A+1:s.maxPartIndex):m=S+1;const R=s.age,b=R+s.ageHeader;let I=Math.min(b-s.partTarget,s.targetduration*1.5);if(I>0){if(b>s.targetduration*3)this.log(`Playlist last advanced ${R.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,y=void 0;else if(i!=null&&i.tuneInGoal&&b-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${I} with playlist age: ${s.age}`),I=0;else{const _=Math.floor(I/s.targetduration);if(m+=_,y!==void 0){const w=Math.round(I%s.targetduration/s.partTarget);y+=w}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${I} skip sn ${_} to part ${y}`)}s.tuneInGoal=I}if(p=this.getDeliveryDirectives(s,e.deliveryDirectives,m,y),T||!x){s.requestScheduled=a,this.loadingPlaylist(d,p);return}}else(s.canBlockReload||s.canSkipUntil)&&(p=this.getDeliveryDirectives(s,e.deliveryDirectives,m,y));p&&m!==void 0&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(d,p,s)}else this.clearTimer()}scheduleLoading(t,e,i){const s=i||t.details;if(!s){this.loadingPlaylist(t,e);return}const r=self.performance.now(),a=s.requestScheduled;if(r>=a){this.loadingPlaylist(t,e);return}const o=a-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),o)}getDeliveryDirectives(t,e,i,s){let r=Ri(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=qt.No),new Ye(i,s,r)}checkRetry(t){const e=t.details,i=ve(t),s=t.errorAction,{action:r,retryCount:a=0,retryConfig:o}=s||{},u=!!s&&!!o&&(r===st.RetryRequest||!s.resolved&&r===st.SendAlternateToPenaltyBox);if(u){var l;if(a>=o.maxNumRetry)return!1;if(i&&(l=t.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const d=ai(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" in ${d}ms`)}t.levelRetry=!0,s.resolved=!0}return u}}var ut={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Rn{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.BUFFER_APPENDED,this.onBufferAppended,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.BUFFER_APPENDED,this.onBufferAppended,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.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 s=i.length;s--;){const r=i[s];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:s}=this,r=Object.keys(s);for(let a=r.length;a--;){const o=s[r[a]];if((o==null?void 0:o.body.type)===e&&(!i||o.buffered)){const u=o.body;if(u.start<=t&&t<=u.end)return u}}return null}detectEvictedFragments(t,e,i,s,r){this.timeRanges&&(this.timeRanges[t]=e);const a=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u||a>=u.body.sn)return;if(!u.buffered&&(!u.loaded||r)){u.body.type===i&&this.removeFragment(u.body);return}const l=u.range[t];if(l){if(l.time.length===0){this.removeFragment(u.body);return}l.time.some(d=>{const h=!this.isTimeBuffered(d.startPTS,d.endPTS,e);return h&&this.removeFragment(u.body),h})}})}detectPartialFragments(t){const e=this.timeRanges;if(!e||t.frag.sn==="initSegment")return;const i=t.frag,s=$t(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const a=!i.relurl;Object.keys(e).forEach(o=>{const u=i.elementaryStreams[o];if(!u)return;const l=e[o],d=a||u.partial===!0;r.range[o]=this.getBufferedTimes(i,t.part,d,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),ne(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(t,e){t.buffered=!0,(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Wi(i,s=>s.fragment.sn>=t))}fragBuffered(t,e){const i=$t(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,t))}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},a=t.start,o=t.end,u=t.minEndPTS||o,l=t.maxStartPTS||a;for(let d=0;d<s.length;d++){const h=s.start(d)-this.bufferPadding,c=s.end(d)+this.bufferPadding;if(l>=h&&u<=c){r.time.push({startPTS:Math.max(a,s.start(d)),endPTS:Math.min(o,s.end(d))});break}else if(a<c&&o>h){const f=Math.max(a,s.start(d)),g=Math.min(o,s.end(d));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=h)break}return r}getPartialFragment(t){let e=null,i,s,r,a=0;const{bufferPadding:o,fragments:u}=this;return Object.keys(u).forEach(l=>{const d=u[l];d&&ne(d)&&(s=d.body.start-o,r=d.body.end+o,t>=s&&t<=r&&(i=Math.min(t-s,r-t),a<=i&&(e=d.body,a=i)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||ne(e))}getState(t){const e=$t(t),i=this.fragments[e];return i?i.buffered?ne(i)?ut.PARTIAL:ut.OK:ut.APPENDING:ut.NOT_LOADED}isTimeBuffered(t,e,i){let s,r;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,r=i.end(a)+this.bufferPadding,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(e.frag.sn==="initSegment"||e.frag.bitrateTest)return;const i=e.frag,s=e.part?null:e,r=$t(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r,type:a}=e;if(i.sn==="initSegment")return;const o=i.type;if(s){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(s)}this.timeRanges=r;const u=r[a];this.detectEvictedFragments(a,u,o,s)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=$t(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){const r=e[i[s]];if((r==null?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}removeFragmentsInRange(t,e,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const u=o.body;u.type!==i||s&&!u.gap||u.start<e&&u.end>t&&(o.buffered||r)&&this.removeFragment(u)})}removeFragment(t){const e=$t(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const s=t.sn;this.activePartLists[t.type]=Wi(i,r=>r.fragment.sn!==s)}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=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;e&&e.forEach(i=>i.clearElementaryStreamInfo())}}function ne(n){var t,e,i;return n.buffered&&!!(n.body.gap||(t=n.range.video)!=null&&t.partial||(e=n.range.audio)!=null&&e.partial||(i=n.range.audiovideo)!=null&&i.partial)}function $t(n){return`${n.type}_${n.level}_${n.sn}`}function Wi(n,t){return n.filter(e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i})}class bn{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 kt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case kt.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}`)}}}function In(n){const t=n.byteLength,e=t&&new DataView(n.buffer).getUint8(t-1);return e?n.slice(0,t-e):n}class Dn{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 s=0;s<4;s++)i[s]=e.getUint32(s*4);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],r=i[1],a=i[2],o=i[3],u=this.invSubMix,l=u[0],d=u[1],h=u[2],c=u[3],f=new Uint32Array(256);let g=0,p=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let y=p^p<<1^p<<2^p<<3^p<<4;y=y>>>8^y&255^99,t[g]=y,e[y]=g;const T=f[g],v=f[T],S=f[v];let A=f[y]*257^y*16843008;s[g]=A<<24|A>>>8,r[g]=A<<16|A>>>16,a[g]=A<<8|A>>>24,o[g]=A,A=S*16843009^v*65537^T*257^g*16843008,l[y]=A<<24|A>>>8,d[y]=A<<16|A>>>16,h[y]=A<<8|A>>>24,c[y]=A,g?(g=T^f[f[f[S^T]]],p^=f[f[p]]):g=p=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const r=this.keySize=e.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,u;const l=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),h=this.sBox,c=this.rcon,f=this.invSubMix,g=f[0],p=f[1],m=f[2],y=f[3];let T,v;for(o=0;o<a;o++){if(o<r){T=l[o]=e[o];continue}v=T,o%r===0?(v=v<<8|v>>>24,v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[v&255],v^=c[o/r|0]<<24):r>6&&o%r===4&&(v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[v&255]),l[o]=T=(l[o-r]^v)>>>0}for(u=0;u<a;u++)o=a-u,u&3?v=l[o]:v=l[o-4],u<4||o<=4?d[u]=v:d[u]=g[h[v>>>24]]^p[h[v>>>16&255]]^m[h[v>>>8&255]]^y[h[v&255]],d[u]=d[u]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,u=o[0],l=o[1],d=o[2],h=o[3],c=this.uint8ArrayToUint32Array_(i);let f=c[0],g=c[1],p=c[2],m=c[3];const y=new Int32Array(t),T=new Int32Array(y.length);let v,S,A,C,x,R,b,I,_,w,$,V,N,P;const G=this.networkToHostOrderSwap;for(;e<y.length;){for(_=G(y[e]),w=G(y[e+1]),$=G(y[e+2]),V=G(y[e+3]),x=_^r[0],R=V^r[1],b=$^r[2],I=w^r[3],N=4,P=1;P<s;P++)v=u[x>>>24]^l[R>>16&255]^d[b>>8&255]^h[I&255]^r[N],S=u[R>>>24]^l[b>>16&255]^d[I>>8&255]^h[x&255]^r[N+1],A=u[b>>>24]^l[I>>16&255]^d[x>>8&255]^h[R&255]^r[N+2],C=u[I>>>24]^l[x>>16&255]^d[R>>8&255]^h[b&255]^r[N+3],x=v,R=S,b=A,I=C,N=N+4;v=a[x>>>24]<<24^a[R>>16&255]<<16^a[b>>8&255]<<8^a[I&255]^r[N],S=a[R>>>24]<<24^a[b>>16&255]<<16^a[I>>8&255]<<8^a[x&255]^r[N+1],A=a[b>>>24]<<24^a[I>>16&255]<<16^a[x>>8&255]<<8^a[R&255]^r[N+2],C=a[I>>>24]<<24^a[x>>16&255]<<16^a[R>>8&255]<<8^a[b&255]^r[N+3],T[e]=G(v^f),T[e+1]=G(C^g),T[e+2]=G(A^p),T[e+3]=G(S^m),f=_,g=w,p=$,m=V,e=e+4}return T.buffer}}class Cn{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=_n(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}function _n(n){switch(n){case kt.cbc:return"AES-CBC";case kt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const Pn=16;class li{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 i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}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?In(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,s){return this.useSoftware?new Promise((r,a)=>{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,e,i,s);const u=this.flush();u?r(u.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:r,currentResult:a,remainderData:o}=this;if(s!==kt.cbc||e.byteLength!==16)return J.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=pt(o,t),this.remainderData=null);const u=this.getValidChunk(t);if(!u.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Dn),l.expandKey(e);const d=a;return this.currentResult=l.decrypt(u.buffer,0,i),this.currentIV=u.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new Cn(this.subtle,e,s)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bn(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(J.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%Pn;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(J.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Yi=Math.pow(2,17);class kn{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 Lt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,a=s.loader;return new Promise((o,u)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(g=>g[0]==="GAP")){u(qi(t));return}else t.gap=!1;const l=this.loader=r?new r(s):new a(s),d=ji(t);t.loader=l;const h=_i(s.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Yi};t.stats=l.stats;const f={onSuccess:(g,p,m,y)=>{this.resetLoader(t,l);let T=g.data;m.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:t,part:null,payload:T,networkDetails:y})},onError:(g,p,m,y)=>{this.resetLoader(t,l),u(new Lt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:ft({url:i,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:m,stats:y}))},onAbort:(g,p,m)=>{this.resetLoader(t,l),u(new Lt({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:m,stats:g}))},onTimeout:(g,p,m)=>{this.resetLoader(t,l),u(new Lt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:m,stats:g}))}};e&&(f.onProgress=(g,p,m,y)=>e({frag:t,part:null,payload:m,networkDetails:y})),l.load(d,c,f)})}loadPart(t,e,i){this.abort();const s=this.config,r=s.fLoader,a=s.loader;return new Promise((o,u)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){u(qi(t,e));return}const l=this.loader=r?new r(s):new a(s),d=ji(t,e);t.loader=l;const h=_i(s.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Yi};e.stats=l.stats,l.load(d,c,{onSuccess:(f,g,p,m)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const y={frag:t,part:e,payload:f.data,networkDetails:m};i(y),o(y)},onError:(f,g,p,m)=>{this.resetLoader(t,l),u(new Lt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:ft({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),u(new Lt({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(t,l),u(new Lt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const u=Math.round(t.duration/e.duration),l=Math.min(Math.round(i.loaded/r),u),h=(u-l)*Math.round(i.loaded/l);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function ji(n,t=null){const e=t||n,i={frag:n,part:t,responseType:"arraybuffer",url:e.url,headers:{},rangeStart:0,rangeEnd:0},s=e.byteRangeStartOffset,r=e.byteRangeEndOffset;if(B(s)&&B(r)){var a;let o=s,u=r;if(n.sn==="initSegment"&&On((a=n.decryptdata)==null?void 0:a.method)){const l=r-s;l%16&&(u=r+(16-l%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=u}return i}function qi(n,t){const e=new Error(`GAP ${n.gap?"tag":"attribute"} found`),i={type:Y.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:n,error:e,networkDetails:null};return t&&(i.part=t),(t||n).stats.aborted=!0,new Lt(i)}function On(n){return n==="AES-128"||n==="AES-256"}class Lt extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Hs extends It{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?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ui{constructor(t,e,i,s=0,r=-1,a=!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=ae(),this.buffering={audio:ae(),video:ae(),audiovideo:ae()},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=a}}function ae(){return{start:0,executeStart:0,executeEnd:0,end:0}}const zi={length:0,start:()=>0,end:()=>0};class q{static isBuffered(t,e){if(t){const i=q.getBuffered(t);for(let s=i.length;s--;)if(e>=i.start(s)&&e<=i.end(s))return!0}return!1}static bufferedRanges(t){if(t){const e=q.getBuffered(t);return q.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 s=q.bufferedRanges(t);if(s.length)return q.bufferedInfo(s,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((d,h)=>d.start-h.start||h.end-d.end);let s=-1,r=[];if(i)for(let d=0;d<t.length;d++){e>=t[d].start&&e<=t[d].end&&(s=d);const h=r.length;if(h){const c=r[h-1].end;t[d].start-c<i?t[d].end>c&&(r[h-1].end=t[d].end):r.push(t[d])}else r.push(t[d])}else r=t;let a=0,o,u=e,l=e;for(let d=0;d<r.length;d++){const h=r[d].start,c=r[d].end;if(s===-1&&e>=h&&e<=c&&(s=d),e+i>=h&&e<c)u=h,l=c,a=l-e;else if(e+i<h){o=h;break}}return{len:a,start:u||0,end:l||0,nextStart:o,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||zi}catch(e){return J.log("failed to get media.buffered",e),zi}}}function Qt(n,t){for(let i=0,s=n.length;i<s;i++){var e;if(((e=n[i])==null?void 0:e.cc)===t)return n[i]}return null}function Fn(n,t){return!!(n&&t.startCC<n.endCC&&t.endCC>n.startCC)}function Xi(n,t){const e=n.start+t;n.startPTS=e,n.setStart(e),n.endPTS=e+n.duration}function Ws(n,t){const e=t.fragments;for(let i=0,s=e.length;i<s;i++)Xi(e[i],n);t.fragmentHint&&Xi(t.fragmentHint,n),t.alignedSliding=!0}function wn(n,t){n&&(Mn(t,n),t.alignedSliding||Nn(t,n),!t.alignedSliding&&!t.skippedSegments&&Bs(n,t,!1))}function Mn(n,t){if(!Fn(t,n))return;const e=Math.min(t.endCC,n.endCC),i=Qt(t.fragments,e),s=Qt(n.fragments,e);if(!i||!s)return;J.log(`Aligning playlist at start of dicontinuity sequence ${e}`);const r=i.start-s.start;Ws(r,n)}function Nn(n,t){if(!n.hasProgramDateTime||!t.hasProgramDateTime)return;const e=n.fragments,i=t.fragments;if(!e.length||!i.length)return;let s,r;const a=Math.min(t.endCC,n.endCC);t.startCC<a&&n.startCC<a&&(s=Qt(i,a),r=Qt(e,a)),(!s||!r)&&(s=i[Math.floor(i.length/2)],r=Qt(e,s.cc)||e[Math.floor(e.length/2)]);const o=s.programDateTime,u=r.programDateTime;if(!o||!u)return;const l=(u-o)/1e3-(r.start-s.start);Ws(l,n)}function Ft(n,t,e){Pt(n,t,e),n.addEventListener(t,e)}function Pt(n,t,e){n.removeEventListener(t,e)}const Bn={toString:function(n){let t="";const e=n.length;for(let i=0;i<e;i++)t+=`[${n.start(i).toFixed(3)}-${n.end(i).toFixed(3)}]`;return t}},k={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"};class Ys extends Hs{constructor(t,e,i,s,r){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=k.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:a,fragCurrent:o,media:u,mediaBuffer:l,state:d}=this,h=u?u.currentTime:0,c=q.bufferInfo(l||u,h,a.maxBufferHole),f=!c.len;if(this.log(`Media seeking to ${B(h)?h.toFixed(3):h}, state: ${d}, ${f?"out of":"in"} buffer`),this.state===k.ENDED)this.resetLoadingState();else if(o){const g=a.maxFragLookUpTolerance,p=o.start-g,m=o.start+o.duration+g;if(f||m<c.start||p>c.end){const y=h>m;(h<p||y)&&(y&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(u){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(h>g&&(this.lastCurrentTime=h),!this.loadingParts){const p=Math.max(c.end,h),m=this.shouldLoadParts(this.getLevelDetails(),p);m&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=m)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),f&&this.state===k.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new kn(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new li(t.config)}registerListeners(){const{hls:t}=this;t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===k.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=k.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return e===-1&&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,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=q.bufferedInfo(r,t.start,0));const a=t.nextStart;if(a&&a>s&&a<e.edge||this.media.currentTime<t.start)return!1;const u=e.partList;if(u!=null&&u.length){const d=u[u.length-1];return q.isBuffered(this.media,d.start+d.duration/2)}const l=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;if(t){var e;return((e=this.getLevelDetails())==null?void 0:e.appliedTimelineOffset)||t}return 0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;Ft(i,"seeking",this.onMediaSeeking),Ft(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===k.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Pt(s,"seeking",this.onMediaSeeking),Pt(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(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=k.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){const s=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(t,e,i,s).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===k.FRAG_LOADING||!this.fragCurrent&&a===k.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=k.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(E.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===ut.APPENDING){const r=t.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(t.duration,a?a.len:this.config.maxBufferLength),u=this.backtrackFragment;((u?t.sn-u.sn:0)===1||this.reduceMaxBufferLength(o,t.duration))&&i.removeFragment(t)}else((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===ut.PARTIAL&&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(e==null?void 0:e.live)&&e.type!=="EVENT"&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(E.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(i=>{const s=i==null?void 0:i.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{frag:r,payload:a}=i,o=r.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Xt(o.method)){const u=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,ws(o.method)).catch(l=>{throw s.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const d=self.performance.now();return s.trigger(E.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:u,tdecrypt:d}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(i),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!==k.STOPPED&&(this.state=k.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,s;const r=t.tracks;if(r&&!e.encrypted&&((i=r.audio)!=null&&i.encrypted||(s=r.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error("EME not supported (light build)");return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,fatal:!0,error:o,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?Bn.toString(q.getBuffered(i)):"(detached)"})`),ct(t)){var s;if(t.type!==W.SUBTITLE){const a=t.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=k.IDLE;return}}const r=(s=this.levels)==null?void 0:s[t.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=k.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:r}=t,a=!r||r.length===0||r.some(u=>!u),o=new ui(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);e.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var r;this.fragCurrent=t;const a=e.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(t.encrypted&&!((r=t.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=k.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(E.KEY_LOADED,c),this.state===k.KEY_LOADING&&(this.state=k.IDLE),c}),this.hls.trigger(E.KEY_LOADING,{frag:t}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else t.encrypted||(o=this.keyLoader.loadClear(t,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const u=this.fragPrevious;if(ct(t)&&(!u||t.sn!==u.sn)){const c=this.shouldLoadParts(e.details,t.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} loading sn ${u==null?void 0:u.sn}->${t.sn}`),this.loadingParts=c)}if(i=Math.max(t.start,i||0),this.loadingParts&&ct(t)){const c=a.partList;if(c&&s){i>a.fragmentEnd&&a.fragmentHint&&(t=a.fragmentHint);const f=this.getNextPart(c,t,i);if(f>-1){const g=c[f];t=this.fragCurrent=g.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${g.index} (${f}/${c.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=k.FRAG_LOADING;let p;return o?p=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(t,g,e,s)).catch(m=>this.handleFragLoadError(m)):p=this.doFragPartsLoad(t,g,e,s).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(E.FRAG_LOADING,{frag:t,part:g,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!t.url||this.loadedEndOfParts(c,i))return Promise.resolve(null)}}if(ct(t)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(c=>c.loaded).map(c=>`[${c.start}-${c.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))}`),B(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=k.FRAG_LOADING;const d=this.config.progressive&&t.type!==W.SUBTITLE;let h;return d&&o?h=o.then(c=>!c||this.fragContextChanged(c.frag)?null:this.fragmentLoader.load(t,s)).catch(c=>this.handleFragLoadError(c)):h=Promise.all([this.fragmentLoader.load(t,d?s:void 0),o]).then(([c])=>(!d&&s&&s(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(E.FRAG_LOADING,{frag:t,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,i,s){return new Promise((r,a)=>{var o;const u=[],l=(o=i.details)==null?void 0:o.partList,d=h=>{this.fragmentLoader.loadPart(t,h,s).then(c=>{u[h.index]=c;const f=c.part;this.hls.trigger(E.FRAG_LOADED,c);const g=Ki(i.details,t.sn,h.index+1)||Gs(l,t.sn,h.index+1);if(g)d(g);else return r({frag:t,part:f,partsLoaded:u})}).catch(a)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===Y.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(E.ERROR,e)}else this.hls.trigger(E.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==k.PARSING){!this.fragCurrent&&this.state!==k.STOPPED&&this.state!==k.ERROR&&(this.state=k.IDLE);return}const{frag:i,part:s,level:r}=e,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);const o=this.getLevelDetails(),l=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(i,s,r,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i;const r=t.partList[0];if(r.fragment.type===W.SUBTITLE)return!1;const a=r.end+(((i=t.fragmentHint)==null?void 0:i.duration)||0);if(e>=a){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:a}=t;if(!(e!=null&&e[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const o=e[s],u=o.details,l=a>-1?Ki(u,r,a):null,d=l?l.fragment:Us(u,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:o}):null}bufferFragmentData(t,e,i,s,r){if(this.state!==k.PARSING)return;const{data1:a,data2:o}=t;let u=a;if(o&&(u=pt(a,o)),!u.length)return;const l=this.initPTS[e.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:t.type,frag:e,part:i,chunkMeta:s,offset:d,parent:e.type,data:u};if(this.hls.trigger(E.BUFFER_APPENDING,h),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!q.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const i=e.currentTime,s=q.bufferInfo(e,i,0),r=t.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(t.start-a,s.end-a),i+a);t.start-o>a&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,e){var i;const s=this.getLoadPosition();if(!B(s))return null;const a=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,a)}getFwdBufferInfoAtPos(t,e,i,s){const r=q.bufferInfo(t,e,s);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(e,i);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-e,s);return q.bufferInfo(t,e,o)}}return r}getMaxBufferLength(t){const{config:e}=this;let i;return t?i=Math.max(8*e.maxBufferSize/t,e.maxBufferLength):i=e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e),r=Math.max(t-e*3,i.maxMaxBufferLength/2,s);return r>=s?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(t,e=W.MAIN){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,s=i.length;if(!s)return null;const{config:r}=this,a=i[0].start,o=r.lowLatencyMode&&!!e.partList;let u=null;if(e.live){const h=r.initialLiveManifestSize;if(s<h)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`),null;if(!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),u=this.getInitialLiveFragment(e);const c=this.hls.startPosition,f=this.hls.liveSyncPosition,g=u?(c!==-1&&c>=a?c:f)||u.start:t;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${c} liveSyncPosition: ${f} frag.start: ${(l=u)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else t<=a&&(u=i[0]);if(!u){const h=this.loadingParts?e.partEnd:e.fragmentEnd;u=this.getFragmentAtPosition(t,h,e)}let d=this.filterReplacedPrimary(u,e);if(!d&&u){const h=u.sn-e.startSN;d=this.filterReplacedPrimary(i[h+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===ut.OK||i===ut.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,s,r){let a=null;if(t.gap&&(a=this.getNextFragment(this.nextLoadPosition,e),a&&!a.gap&&i.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=r){const u=a.sn;return this.loopSn!==u&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${u}`),this.loopSn=u),null}}return this.loopSn=void 0,a}get primaryPrefetch(){return Qi(this.config),!1}filterReplacedPrimary(t,e){return t&&(Qi(this.config),t)}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!t.initSegment.data&&!this.bitrateTest?t.initSegment:t}getNextPart(t,e,i){let s=-1,r=!1,a=!0;for(let o=0,u=t.length;o<u;o++){const l=t[o];if(a=a&&!l.independent,s>-1&&i<l.start)break;const d=l.loaded;d?s=-1:(r||(l.independent||a)&&l.fragment===e)&&(l.fragment!==e&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`),s=o),r=d}return s}loadedEndOfParts(t,e){let i;for(let s=t.length;s--;){if(i=t[s],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,i=this.fragPrevious;let s=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=rn(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){const a=e[r-t.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=on(t,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(s=this.getFragmentAtPosition(r,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=i;const{fragmentHint:u}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,h=!!(this.loadingParts&&d!=null&&d.length&&u);h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(a=a.concat(u),o=u.sn);let c;if(t<e){var f;const p=t<this.lastCurrentTime||t>e-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;c=ni(r,a,t,p)}else c=a[a.length-1];if(c){const g=c.sn-i.startSN,p=this.fragmentTracker.getState(c);if((p===ut.OK||p===ut.PARTIAL&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!h||d[0].fragment.sn>c.sn||!i.live)&&c.level===r.level){const y=a[g+1];c.sn<o&&this.fragmentTracker.getState(y)!==ut.OK?c=y:c=null}}return c}alignPlaylists(t,e,i){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,a=!e,o=t.alignedSliding&&B(r);if(a||!o&&!r){wn(i,t);const u=t.fragmentStart;return this.log(`Live playlist sliding: ${u.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),u}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let i=this.startPosition;i<e&&(i=-1);const s=this.timelineOffset;if(i===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:t.startTimeOffset;a!==null&&B(a)?(i=e+a,a<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${r?"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+s}this.nextLoadPosition=i+s}getLoadPosition(){var t;const{media:e}=this;let i=0;return(t=this.hls)!=null&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&ct(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!==k.FRAG_LOADING_WAITING_RETRY)&&(this.state=k.IDLE)}onFragmentOrKeyLoadError(t,e){var i;if(e.chunkMeta&&!e.frag){const y=this.getCurrentContext(e.chunkMeta);y&&(e.frag=y.frag)}const s=e.frag;if(!s||s.type!==t||!this.levels)return;if(this.fragContextChanged(s)){var r;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const a=e.details===D.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);const o=e.errorAction;if(!o){this.state=k.ERROR;return}const{action:u,flags:l,retryCount:d=0,retryConfig:h}=o,c=!!h,f=c&&u===st.RetryRequest,g=c&&!o.resolved&&l===lt.MoveAllAlternatesMatchingHost,p=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&g&&ct(s)&&!s.endList&&p&&!Ps(e))this.resetFragmentErrors(t),this.treatAsGap(s),o.resolved=!0;else if((f||g)&&d<h.maxNumRetry){var m;const y=je((m=e.response)==null?void 0:m.code),T=ai(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=k.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,y){this.log("Waiting for connection (offline)"),this.retryDate=1/0,e.reason="offline";return}this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${T}ms`)}else if(h)if(this.resetFragmentErrors(t),d<h.maxNumRetry)!a&&u!==st.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${e.details} reached or exceeded max retry (${d})`);return}else u===st.SendAlternateToPenaltyBox?this.state=k.WAITING_LEVEL:this.state=k.ERROR;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!je(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=k.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===k.PARSING||this.state===k.PARSED){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(e==null?void 0:e.duration)||10);const a=!r;return a&&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(),a}return!1}resetFragmentErrors(t){t===W.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==k.STOPPED&&(this.state=k.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;const s=q.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===k.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==k.STOPPED&&(this.state=k.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((u,l)=>{const d=t.elementaryStreams[l];if(d){const h=d.endPTS-d.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${t.sn} ${l} duration reliably (${h})`),u||!1;const c=s?0:Ns(r,t,d.startPTS,d.endPTS,d.startDTS,d.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:r,level:i,drift:c,type:l,frag:t,start:d.startPTS,end:d.endPTS}),!0}return u},!1)){var o;const u=((o=this.transmuxer)==null?void 0:o.error)===null;if((i.fragmentError===0||u&&(i.fragmentError<2||t.endList))&&this.treatAsGap(t,i),u){const l=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=k.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(E.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===W.MAIN?"level":"track"}fragInfo(t,e=!0,i){var s,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${((s=e&&!i?t.startPTS:(i||t).start)!=null?s:NaN).toFixed(3)}-${((r=e&&!i?t.endPTS:(i||t).end)!=null?r:NaN).toFixed(3)}]${i&&t.type==="main"?"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;(t=this.transmuxer)==null||t.reset()}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Qi(n){return!1}class $n{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(this.queues===null||this.tracks===null)return;const s=this.queues[e];s.push(t),s.length===1&&!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(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=(e=t[0])==null?void 0:e.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(this.queues===null)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(r){var i;if(s.onError(r),this.queues===null||this.tracks===null)return;const a=(i=this.tracks[t])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return((e=this.queues)==null?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return t===null||e===null?"<destroyed>":`
17
+ ${this.list("video")}
18
+ ${this.list("audio")}
19
+ ${this.list("audiovideo")}}`}list(t){var e,i;return(e=this.queues)!=null&&e[t]||(i=this.tracks)!=null&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=(e=this.tracks)==null?void 0:e[t],s=i==null?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return((e=this.queues)==null?void 0:e[t].map(i=>i.label).join(", "))||""}}const Zi=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,js="HlsJsTrackRemovedError";class Un extends Error{constructor(t){super(t),this.name=js}}class qs extends It{constructor(t,e){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=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:s,mediaSource:r}=this;i&&this.log("Media source opened"),!(!s||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:s,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=Cr(bt(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.BUFFER_RESET,this.onBufferReset,this),t.on(E.BUFFER_APPENDING,this.onBufferAppending,this),t.on(E.BUFFER_CODECS,this.onBufferCodecs,this),t.on(E.BUFFER_EOS,this.onBufferEos,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.FRAG_PARSED,this.onFragParsed,this),t.on(E.FRAG_CHANGED,this.onFragChanged,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.BUFFER_RESET,this.onBufferReset,this),t.off(E.BUFFER_APPENDING,this.onBufferAppending,this),t.off(E.BUFFER_CODECS,this.onBufferCodecs,this),t.off(E.BUFFER_EOS,this.onBufferEos,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.FRAG_PARSED,this.onFragParsed,this),t.off(E.FRAG_CHANGED,this.onFragChanged,this),t.off(E.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===e?at(i,s.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(i[a]=at({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){const t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,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 s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const s=bt(this.appendSource);if(s){const r=!!e.mediaSource;(r||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const a=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(a),r)this._objectUrl=i.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const u=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||u&&a instanceof u,Ji(i),Gn(i,o),i.load()}catch{i.src=o}else i.src=o}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${((e=this.transferData)==null?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${(i=t.constructor)==null?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,s=e.tracks,r=s?Object.keys(s):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
20
+ required tracks: ${ot(i,(u,l)=>u==="initSegment"?void 0:l)};
21
+ transfer tracks: ${ot(s,(u,l)=>u==="initSegment"?void 0:l)}}`),!_r(s,i)){e.mediaSource=null,e.tracks=void 0;const u=t.currentTime,l=this.details,d=Math.max(u,(l==null?void 0:l.fragments[0].start)||0);if(d-u>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${u} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${u}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,e),t.currentTime=d;return}this.transferData=void 0,r.forEach(u=>{const l=u,d=s[l];if(d){const h=d.buffer;if(h){const c=this.fragmentTracker,f=d.id;if(c.hasFragments(f)||c.hasParts(f)){const m=q.getBuffered(h);c.detectEvictedFragments(l,m,f,null,!0)}const g=ke(l),p=[l,h];this.sourceBuffers[g]=p,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,d)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=(t=this.mediaSource)==null?void 0:t.readyState;return e==="open"||e==="ended"}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const u=r.sourceBuffers;for(let l=u.length;l--;)o&&u[l].abort(),r.removeSourceBuffer(u[l]);o&&r.endOfStream()}catch(u){this.warn(`onMediaDetaching: ${u.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&Ji(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=(e=this.tracks[t])==null?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${t}`,r)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[ke(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new $n(this.tracks)}onBufferCodecs(t,e){var i;const s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),o=!a&&this.sourceBufferCount&&this.media&&r.some(u=>!s[u]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`);return}r.forEach(u=>{var l,d;const h=e[u],{id:c,codec:f,levelCodec:g,container:p,metadata:m,supplemental:y}=h;let T=s[u];const v=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[u],S=v!=null&&v.buffer?v:T,A=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),C=S==null?void 0:S.levelCodec;T||(T=s[u]={buffer:void 0,listeners:[],codec:f,supplemental:y,container:p,levelCodec:g,metadata:m,id:c});const x=fe(A,C),R=x==null?void 0:x.replace(Zi,"$1");let b=fe(f,g);const I=(d=b)==null?void 0:d.replace(Zi,"$1");b&&x&&R!==I&&(u.slice(0,5)==="audio"&&(b=pe(b,this.appendSource)),this.log(`switching codec ${A} to ${b}`),b!==(T.pendingCodec||T.codec)&&(T.pendingCodec=b),T.container=p,this.appendChangeType(u,p,b))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&((i=e.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),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 s=`${e};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const a=this.tracks[t];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),o.changeType(s),a.codec=i,a.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${t} SourceBuffer type`,a)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,s=i+t.duration*.05;if(((e=this.fragmentTracker.getAppendedFrag(i,W.MAIN))==null?void 0:e.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const u=this.tracks.video;(this.lastVideoAppendEnd>s||u!=null&&u.buffer&&q.isBuffered(u.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,W.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:t},this.append(a,"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:s,type:r,parent:a,frag:o,part:u,chunkMeta:l,offset:d}=e,h=l.buffering[r],{sn:c,cc:f}=o,g=self.performance.now();h.start=g;const p=o.stats.buffering,m=u?u.stats.buffering:null;p.start===0&&(p.start=g),m&&m.start===0&&(m.start=g);const y=i.audio;let T=!1;r==="audio"&&(y==null?void 0:y.container)==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const v=i.video,S=v==null?void 0:v.buffer;if(S&&c!=="initSegment"){const x=u||o,R=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(v.ending||v.ended)){const I=x.start+x.duration*.05,_=S.buffered,w=this.currentOp("video");!_.length&&!w?this.blockAudio(x):!w&&!q.isBuffered(S,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(x)}else if(r==="video"){const b=x.end;if(R){const I=R.frag.start;(b>I||b<this.lastVideoAppendEnd||q.isBuffered(S,I))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}const A=(u||o).start,C={label:`append-${r}`,execute:()=>{var x;h.executeStart=self.performance.now();const R=(x=this.tracks[r])==null?void 0:x.buffer;R&&(T?this.updateTimestampOffset(R,A,.1,r,c,f):d!==void 0&&B(d)&&this.updateTimestampOffset(R,d,1e-6,r,c,f)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();h.executeEnd=h.end=x,p.first===0&&(p.first=x),m&&m.first===0&&(m.first=x);const R={};this.sourceBuffers.forEach(([b,I])=>{b&&(R[b]=q.getBuffered(I))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:r,frag:o,part:u,chunkMeta:l,parent:o.type,timeRanges:R})},onError:x=>{var R;const b={type:Y.MEDIA_ERROR,parent:o.type,details:D.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:u,chunkMeta:l,error:x,err:x,fatal:!1},I=(R=this.media)==null?void 0:R.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR||x.name=="QuotaExceededError"||"quota"in x)b.details=D.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)b.errorAction=zt(!0);else if(x.name===js&&this.sourceBufferCount===0)b.errorAction=zt(!0);else{const _=++this.appendErrors[r];this.warn(`Failed ${_}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(_>=this.hls.config.appendErrorMaxRetry||I)&&(b.fatal=!0)}this.hls.trigger(E.ERROR,b)}};this.log(`queuing "${r}" append sn: ${c}${u?" p: "+u.index:""} of ${o.type===W.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(C,r,this.isPending(this.tracks[r]))}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(E.BUFFER_FLUSHED,{type:t})},onError:s=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s)}}}onBufferFlushing(t,e){const{type:i,startOffset:s,endOffset:r}=e;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,r),a)})}onFragParsed(t,e){const{frag:i,part:s}=e,r=[],a=s?s.elementaryStreams:i.elementaryStreams;a[et.AUDIOVIDEO]?r.push("audiovideo"):(a[et.AUDIO]&&r.push("audio"),a[et.VIDEO]&&r.push("video"));const o=()=>{const u=self.performance.now();i.stats.buffering.end=u,s&&(s.stats.buffering.end=u);const l=s?s.stats:i.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:s,stats:l,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,r).catch(u=>{this.warn(`Fragment buffered callback ${u}`),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(([a])=>{if(a){const o=this.tracks[a];(!e.type||e.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):e.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){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===D.BUFFER_APPEND_ERROR&&e.frag){var i;const s=(i=e.errorAction)==null?void 0:i.nextAutoLevel;B(s)&&s!==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||e===null||!this.sourceBufferCount)return;const s=t.config,r=i.currentTime,a=e.levelTargetDuration,o=e.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(B(o)&&o>=0){const l=Math.max(o,a),d=Math.floor(r/a)*a-l;this.flushBackBuffer(r,a,d)}const u=s.frontBufferFlushThreshold;if(B(u)&&u>0){const l=Math.max(s.maxBufferLength,u),d=Math.max(l,a),h=Math.floor(r/a)*a+d;this.flushFrontBuffer(r,a,h)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const o=q.getBuffered(r);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:i});const u=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(u!=null&&u.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const a=q.getBuffered(r),o=a.length;if(o<2)return;const u=a.start(o-1),l=a.end(o-1);if(i>u||t>=u&&t<=l)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:s})}})}getDurationAndRange(){var t;const{details:e,mediaSource:i}=this;if(!e||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){const l=Math.max(0,e.fragmentStart),d=Math.max(l,s);return{duration:1/0,start:l,end:d}}return{duration:1/0}}const r=(t=this.overrides)==null?void 0:t.duration;if(r)return B(r)?{duration:r}:null;const a=this.media.duration,o=B(i.duration)?i.duration:0;return s>o&&s>a||!B(a)?{duration:s}:null}updateMediaSource({duration:t,start:e,end:i}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==t&&(B(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),s.duration=t),e!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${i}.`),s.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}) ${ot(i)}`),this.tracksReady){var s;const r=(s=this.transferData)==null?void 0:s.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(E.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.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 r in t){const a=r,o=t[a];if(this.isPending(o)){const u=this.getTrackCodec(o,a),l=`${o.container};codecs=${u}`;o.codec=u,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${ot(o)}`);try{const d=i.addSourceBuffer(l),h=ke(a),c=[a,d];e[h]=c,o.buffer=d}catch(d){var s;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let s=t.codec;i&&(e==="video"||e==="audiovideo")&&Zt(i,"video")&&(s=jr(s,i));const r=fe(s,t.levelCodec);return r?e.slice(0,5)==="audio"?pe(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,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",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var t,e;const i=((t=this.media)==null||(e=t.querySelector)==null?void 0:e.call(t,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}const i=this.currentOp(t);i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;const s=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,e),this.hls.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const r=this.currentOp(t);r&&r.onError(s)}updateTimestampOffset(t,e,i,s,r,a){const o=e-t.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${a})`),t.timestampOffset=e)}removeExecutor(t,e,i){const{media:s,mediaSource:r}=this,a=this.tracks[t],o=a==null?void 0:a.buffer;if(!s||!r||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const u=B(s.duration)?s.duration:1/0,l=B(r.duration)?r.duration:1/0,d=Math.max(0,e),h=Math.min(i,u,l);h>d&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${d},${h}] from the ${t} SourceBuffer`),o.remove(d,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],s=i==null?void 0:i.buffer;if(!s)throw new Un(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,s=e.map(a=>this.appendBlocker(a));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(a=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(e=>{var i;const s=(i=this.tracks[e])==null?void 0:i.buffer;!s||s.updating||this.shiftAndExecuteNext(e)})}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 s=this.tracks[t];if(!s)return;const r=s.buffer;if(!r)return;const a=i.bind(this,t);s.listeners.push({event:e,listener:a}),r.addEventListener(e,a)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(s=>{i.removeEventListener(s.event,s.listener)}),e.listeners.length=0)}}function Ji(n){const t=n.querySelectorAll("source");[].slice.call(t).forEach(e=>{n.removeChild(e)})}function Gn(n,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,n.appendChild(e)}function ke(n){return n==="audio"?1:0}class Ae{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(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.BUFFER_CODECS,this.onBufferCodecs,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.BUFFER_CODECS,this.onBufferCodecs,this),t.off(E.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&&B(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){this.clientRect=null;return}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((s,r)=>this.isLevelAllowed(s)&&r<=t);return this.clientRect=null,Ae.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{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(i=>t.bitrate===i.bitrate&&t.width===i.width&&t.height===i.height)}static getMaxLevelByMediaSize(t,e,i){if(!(t!=null&&t.length))return-1;const s=(o,u)=>u?o.width!==u.width||o.height!==u.height:!0;let r=t.length-1;const a=Math.max(e,i);for(let o=0;o<t.length;o+=1){const u=t[o];if((u.width>=a||u.height>=a)&&s(u,t[o+1])){r=o;break}}return r}}const Vn=3e5;class zs extends It{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(t.indexOf(e.pathwayId)===-1&&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=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(i=>i!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;i!==null&&(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((i==null?void 0:i.action)===st.SendAlternateToPenaltyBox&&i.flags===lt.MoveAllAlternatesMatchingHost){const s=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(e.context){const{groupId:o,pathwayId:u,type:l}=e.context;o&&s?a=this.getPathwayForGroupId(o,l,a):u&&(a=u)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&s&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),e.details===D.BUFFER_APPEND_ERROR&&!e.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${ot(r)} penalized: ${ot(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){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 this.levels===null?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(r=>{s-i[r]>Vn&&delete i[r]});for(let r=0;r<t.length;r++){const a=t[r];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,u=this.hls.levels[o];if(e=this.getLevelsForPathway(a),e.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Vs(e),this.hls.trigger(E.LEVELS_UPDATED,{levels:e});const l=this.hls.levels[o];u&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==u.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==u.bitrate&&this.log(`Unstable Pathways change from bitrate ${u.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(e===X.AUDIO_TRACK&&s[r].hasAudioGroup(t)||e===X.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(t))return s[r].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":u}=r;if(e.some(d=>d.pathwayId===a))return;const l=this.getLevelsForPathway(o).map(d=>{const h=new tt(d.attrs);h["PATHWAY-ID"]=a;const c=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;c&&(i[h.AUDIO]=c,h.AUDIO=c),f&&(s[h.SUBTITLES]=f,h.SUBTITLES=f);const g=Xs(d.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",u),p=new ri({attrs:h,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:g,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let m=1;m<d.audioGroups.length;m++)p.addGroupId("audio",`${d.audioGroups[m]}_clone_${a}`);if(d.subtitleGroups)for(let m=1;m<d.subtitleGroups.length;m++)p.addGroupId("text",`${d.subtitleGroups[m]}_clone_${a}`);return p});e.push(...l),ts(this.audioTracks,i,u,a),ts(this.subtitleTracks,s,u,a)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;this.loader&&this.loader.destroy(),this.loader=new i(e);let s;try{s=new self.URL(t)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(s.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+d)}const r={responseType:"json",url:s.href},a=e.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},u={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(d,h,c,f)=>{this.log(`Loaded steering manifest: "${s}"`);const g=d.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":y}=g;if(p)try{this.uri=new self.URL(p,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||c.url),m&&this.clonePathways(m);const T={steeringManifest:g,url:s.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,T),y&&this.updatePathwayPriority(y)},onError:(d,h,c,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${h.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const m=p.getResponseHeader("Retry-After");m&&(g=parseFloat(m)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(d,h,c)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,u,l)}scheduleRefresh(t,e=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},e)}}function ts(n,t,e,i){n&&Object.keys(t).forEach(s=>{const r=n.filter(a=>a.groupId===s).map(a=>{const o=at({},a);return o.details=void 0,o.attrs=new tt(o.attrs),o.url=o.attrs.URI=Xs(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),o.groupId=o.attrs["GROUP-ID"]=t[s],o.attrs["PATHWAY-ID"]=i,o});n.push(...r)})}function Xs(n,t,e,i){const{HOST:s,PARAMS:r,[e]:a}=i;let o;t&&(o=a==null?void 0:a[t],o&&(n=o));const u=new self.URL(n);return s&&!o&&(u.host=s),r&&Object.keys(r).sort().forEach(l=>{l&&u.searchParams.set(l,r[l])}),u.href}class Qs{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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.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 s=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(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 s=performance.now();if(e){if(this.lastTime){const r=s-this.lastTime,a=i-this.lastDroppedFrames,o=e-this.lastDecodedFrames,u=1e3*a/r,l=this.hls;if(l.trigger(E.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),u>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let d=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d=d-1,l.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,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)}}function Kn(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const r=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(s=="x"?r:r&3|8).toString(16)})}}}var Oe={exports:{}},es;function Hn(){return es||(es=1,(function(n){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function s(u,l,d){this.fn=u,this.context=l,this.once=d||!1}function r(u,l,d,h,c){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new s(d,h||u,c),g=e?e+l:l;return u._events[g]?u._events[g].fn?u._events[g]=[u._events[g],f]:u._events[g].push(f):(u._events[g]=f,u._eventsCount++),u}function a(u,l){--u._eventsCount===0?u._events=new i:delete u._events[l]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],d,h;if(this._eventsCount===0)return l;for(h in d=this._events)t.call(d,h)&&l.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},o.prototype.listeners=function(l){var d=e?e+l:l,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var c=0,f=h.length,g=new Array(f);c<f;c++)g[c]=h[c].fn;return g},o.prototype.listenerCount=function(l){var d=e?e+l:l,h=this._events[d];return h?h.fn?1:h.length:0},o.prototype.emit=function(l,d,h,c,f,g){var p=e?e+l:l;if(!this._events[p])return!1;var m=this._events[p],y=arguments.length,T,v;if(m.fn){switch(m.once&&this.removeListener(l,m.fn,void 0,!0),y){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,d),!0;case 3:return m.fn.call(m.context,d,h),!0;case 4:return m.fn.call(m.context,d,h,c),!0;case 5:return m.fn.call(m.context,d,h,c,f),!0;case 6:return m.fn.call(m.context,d,h,c,f,g),!0}for(v=1,T=new Array(y-1);v<y;v++)T[v-1]=arguments[v];m.fn.apply(m.context,T)}else{var S=m.length,A;for(v=0;v<S;v++)switch(m[v].once&&this.removeListener(l,m[v].fn,void 0,!0),y){case 1:m[v].fn.call(m[v].context);break;case 2:m[v].fn.call(m[v].context,d);break;case 3:m[v].fn.call(m[v].context,d,h);break;case 4:m[v].fn.call(m[v].context,d,h,c);break;default:if(!T)for(A=1,T=new Array(y-1);A<y;A++)T[A-1]=arguments[A];m[v].fn.apply(m[v].context,T)}}return!0},o.prototype.on=function(l,d,h){return r(this,l,d,h,!1)},o.prototype.once=function(l,d,h){return r(this,l,d,h,!0)},o.prototype.removeListener=function(l,d,h,c){var f=e?e+l:l;if(!this._events[f])return this;if(!d)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===d&&(!c||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var p=0,m=[],y=g.length;p<y;p++)(g[p].fn!==d||c&&!g[p].once||h&&g[p].context!==h)&&m.push(g[p]);m.length?this._events[f]=m.length===1?m[0]:m:a(this,f)}return this},o.prototype.removeAllListeners=function(l){var d;return l?(d=e?e+l:l,this._events[d]&&a(this,d)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=e,o.EventEmitter=o,n.exports=o})(Oe)),Oe.exports}var Wn=Hn(),Zs=ms(Wn);class Yn{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;if(t.length)t.length===1?i=t[0]:i=jn(t,e);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function jn(n,t){const e=new Uint8Array(t);let i=0;for(let s=0;s<n.length;s++){const r=n[s];e.set(r,i),i+=r.length}return e}function Js(n,t){return t+10<=n.length&&n[t]===51&&n[t+1]===68&&n[t+2]===73&&n[t+3]<255&&n[t+4]<255&&n[t+6]<128&&n[t+7]<128&&n[t+8]<128&&n[t+9]<128}function di(n,t){return t+10<=n.length&&n[t]===73&&n[t+1]===68&&n[t+2]===51&&n[t+3]<255&&n[t+4]<255&&n[t+6]<128&&n[t+7]<128&&n[t+8]<128&&n[t+9]<128}function Re(n,t){let e=0;return e=(n[t]&127)<<21,e|=(n[t+1]&127)<<14,e|=(n[t+2]&127)<<7,e|=n[t+3]&127,e}function Te(n,t){const e=t;let i=0;for(;di(n,t);){i+=10;const s=Re(n,t+6);i+=s,Js(n,t+10)&&(i+=10),t+=i}if(i>0)return n.subarray(e,e+i)}function qn(n,t,e,i){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=t[e+2],a=r>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);n.emit(E.ERROR,E.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,u=t[e+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,d=s[a];let h=a;(o===5||o===29)&&(h-=3);const c=[o<<3|(h&14)>>1,(h&1)<<7|u<<3];return J.log(`manifest codec:${i}, parsed codec:${l}, channels:${u}, rate:${d} (ADTS object type:${o} sampling index:${a})`),{config:c,samplerate:d,channelCount:u,codec:l,parsedCodec:l,manifestCodec:i}}function tr(n,t){return n[t]===255&&(n[t+1]&246)===240}function er(n,t){return n[t+1]&1?7:9}function hi(n,t){return(n[t+3]&3)<<11|n[t+4]<<3|(n[t+5]&224)>>>5}function zn(n,t){return t+5<n.length}function Se(n,t){return t+1<n.length&&tr(n,t)}function Xn(n,t){return zn(n,t)&&tr(n,t)&&hi(n,t)<=n.length-t}function Qn(n,t){if(Se(n,t)){const e=er(n,t);if(t+e>=n.length)return!1;const i=hi(n,t);if(i<=e)return!1;const s=t+i;return s===n.length||Se(n,s)}return!1}function ir(n,t,e,i,s){if(!n.samplerate){const r=qn(t,e,i,s);if(!r)return;at(n,r)}}function sr(n){return 1024*9e4/n}function Zn(n,t){const e=er(n,t);if(t+e<=n.length){const i=hi(n,t)-e;if(i>0)return{headerLength:e,frameLength:i}}}function rr(n,t,e,i,s){const r=sr(n.samplerate),a=i+s*r,o=Zn(t,e);let u;if(o){const{frameLength:h,headerLength:c}=o,f=c+h,g=Math.max(0,e+f-t.length);g?(u=new Uint8Array(f-c),u.set(t.subarray(e+c,t.length),0)):u=t.subarray(e+c,e+f);const p={unit:u,pts:a};return g||n.samples.push(p),{sample:p,length:f,missing:g}}const l=t.length-e;return u=new Uint8Array(l),u.set(t.subarray(e,t.length),0),{sample:{unit:u,pts:a},length:l,missing:-1}}function Jn(n,t){return di(n,t)&&Re(n,t+6)+10<=n.length-t}function ta(n){return n instanceof ArrayBuffer?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function Fe(n,t=0,e=1/0){return ea(n,t,e,Uint8Array)}function ea(n,t,e,i){const s=ia(n);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const a=sa(n)?n.byteOffset:0,o=(a+n.byteLength)/r,u=(a+t)/r,l=Math.floor(Math.max(0,Math.min(u,o))),d=Math.floor(Math.min(l+Math.max(e,0),o));return new i(s,l,d-l)}function ia(n){return n instanceof ArrayBuffer?n:n.buffer}function sa(n){return n&&n.buffer instanceof ArrayBuffer&&n.byteLength!==void 0&&n.byteOffset!==void 0}function ra(n){const t={key:n.type,description:"",data:"",mimeType:null,pictureType:null},e=3;if(n.size<2)return;if(n.data[0]!==e){console.log("Ignore frame with unrecognized character encoding");return}const i=n.data.subarray(1).indexOf(0);if(i===-1)return;const s=mt(Fe(n.data,1,i)),r=n.data[2+i],a=n.data.subarray(3+i).indexOf(0);if(a===-1)return;const o=mt(Fe(n.data,3+i,a));let u;return s==="-->"?u=mt(Fe(n.data,4+i+a)):u=ta(n.data.subarray(4+i+a)),t.mimeType=s,t.pictureType=r,t.description=o,t.data=u,t}function na(n){if(n.size<2)return;const t=mt(n.data,!0),e=new Uint8Array(n.data.subarray(t.length+1));return{key:n.type,info:t,data:e.buffer}}function aa(n){if(n.size<2)return;if(n.type==="TXXX"){let e=1;const i=mt(n.data.subarray(e),!0);e+=i.length+1;const s=mt(n.data.subarray(e));return{key:n.type,info:i,data:s}}const t=mt(n.data.subarray(1));return{key:n.type,info:"",data:t}}function oa(n){if(n.type==="WXXX"){if(n.size<2)return;let e=1;const i=mt(n.data.subarray(e),!0);e+=i.length+1;const s=mt(n.data.subarray(e));return{key:n.type,info:i,data:s}}const t=mt(n.data);return{key:n.type,info:"",data:t}}function la(n){return n.type==="PRIV"?na(n):n.type[0]==="W"?oa(n):n.type==="APIC"?ra(n):aa(n)}function ua(n){const t=String.fromCharCode(n[0],n[1],n[2],n[3]),e=Re(n,4),i=10;return{type:t,size:e,data:n.subarray(i,i+e)}}const oe=10,da=10;function nr(n){let t=0;const e=[];for(;di(n,t);){const i=Re(n,t+6);n[t+5]>>6&1&&(t+=oe),t+=oe;const s=t+i;for(;t+da<s;){const r=ua(n.subarray(t)),a=la(r);a&&e.push(a),t+=r.size+oe}Js(n,t)&&(t+=oe)}return e}function ar(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function ha(n){if(n.data.byteLength===8){const t=new Uint8Array(n.data),e=t[3]&1;let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,e&&(i+=4772185884e-2),Math.round(i)}}function or(n){const t=nr(n);for(let e=0;e<t.length;e++){const i=t[e];if(ar(i))return ha(i)}}let dt=(function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n})({});function Tt(n="",t=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class lr{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,s){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=pt(this.cachedData,t),this.cachedData=null);let i=Te(t,0),s=i?i.length:0,r;const a=this._audioTrack,o=this._id3Track,u=i?or(i):void 0,l=t.length;for((this.basePTS===null||this.frameIndex===0&&B(u))&&(this.basePTS=ca(u,e,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:dt.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(t,s)){const d=this.appendFrame(a,t,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,r=s):s=l}else Jn(t,s)?(i=Te(t,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:dt.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===l&&r!==l){const d=t.slice(r);this.cachedData?this.cachedData=pt(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:Tt(),id3Track:o,textTrack:Tt()}}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:Tt(),id3Track:this._id3Track,textTrack:Tt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ca=(n,t,e)=>{if(B(n))return n*90;const i=e?e.baseTime*9e4/e.timescale:0;return t*9e4+i};let le=null;const fa=[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],ga=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ma=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],pa=[0,1,1,4];function ur(n,t,e,i,s){if(e+24>t.length)return;const r=dr(t,e);if(r&&e+r.frameLength<=t.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=i+s*a,u={unit:t.subarray(e,e+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(u),{sample:u,length:r.frameLength,missing:0}}}function dr(n,t){const e=n[t+1]>>3&3,i=n[t+1]>>1&3,s=n[t+2]>>4&15,r=n[t+2]>>2&3;if(e!==1&&s!==0&&s!==15&&r!==3){const a=n[t+2]>>1&1,o=n[t+3]>>6,u=e===3?3-i:i===3?3:4,l=fa[u*14+s-1]*1e3,h=ga[(e===3?0:e===2?1:2)*3+r],c=o===3?1:2,f=ma[e][i],g=pa[i],p=f*8*g,m=Math.floor(f*l/h+a)*g;if(le===null){const v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);le=v?parseInt(v[1]):0}return!!le&&le<=87&&i===2&&l>=224e3&&o===0&&(n[t+3]=n[t+3]|128),{sampleRate:h,channelCount:c,frameLength:m,samplesPerFrame:p}}}function ci(n,t){return n[t]===255&&(n[t+1]&224)===224&&(n[t+1]&6)!==0}function hr(n,t){return t+1<n.length&&ci(n,t)}function Ea(n,t){return ci(n,t)&&4<=n.length-t}function cr(n,t){if(t+1<n.length&&ci(n,t)){const i=dr(n,t);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const r=t+s;return r===n.length||hr(n,r)}return!1}class va extends lr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=Te(t,0);let s=(i==null?void 0:i.length)||0;if(cr(t,s))return!1;for(let r=t.length;s<r;s++)if(Qn(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return Xn(t,e)}appendFrame(t,e,i){ir(t,this.observer,e,i,t.manifestCodec);const s=rr(t,e,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const ya=(n,t)=>{let e=0,i=5;t+=i;const s=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=n[t];const o=Math.min(i,8),u=8-o;r[0]=4278190080>>>24+u<<u,s[0]=(a[0]&r[0])>>u,e=e?e<<o|s[0]:s[0],t+=1,i-=o}return e};class Ta extends lr{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Te(t,0);let i=(e==null?void 0:e.length)||0;if(e&&t[i]===11&&t[i+1]===119&&or(e)!==void 0&&ya(t,i)<=16)return!1;for(let s=t.length;i<s;i++)if(cr(t,i))return J.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return Ea(t,e)}appendFrame(t,e,i){if(this.basePTS!==null)return ur(t,e,i,this.basePTS,this.frameIndex)}}const Sa=/\/emsg[-/]ID3/i;class xa{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,s){const r=this.videoTrack=Tt("video",1),a=this.audioTrack=Tt("audio",1),o=this.txtTrack=Tt("text",1);if(this.id3Track=Tt("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const u=xs(t);if(u.video){const{id:l,timescale:d,codec:h,supplemental:c}=u.video;r.id=l,r.timescale=o.timescale=d,r.codec=h,r.supplemental=c}if(u.audio){const{id:l,timescale:d,codec:h}=u.audio;a.id=l,a.timescale=d,a.codec=h}o.id=ys.text,r.sampleDuration=0,r.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return Fr(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=pt(this.remainderData,t));const o=Vr(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const a=this.extractID3Track(s,e);return r.samples=Si(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=Si(t,e),{videoTrack:e,audioTrack:Tt(),id3Track:s,textTrack:Tt()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=j(t.samples,["emsg"]);s&&s.forEach(r=>{const a=Hr(r);if(Sa.test(a.schemeIdUri)){const o=is(a,e);let u=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;u<=.001&&(u=Number.POSITIVE_INFINITY);const l=a.payload;i.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:dt.emsg,duration:u})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=is(a,e);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:dt.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}}function is(n,t){return B(n.presentationTime)?n.presentationTime/n.timeScale:t+n.presentationTimeDelta/n.timeScale}class La{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new li(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,kt.cbc)}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const u=new Uint8Array(o);s.set(u,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length){i();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=Math.floor((t.length-48)/160)*16+16,i=new Int8Array(e);let s=0;for(let r=32;r<t.length-16;r+=160,s+=16)i.set(t.subarray(r,r+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let r=32;r<t.length-16;r+=160,s+=16)t.set(i.subarray(s,s+16),r);return t}decryptAvcSample(t,e,i,s,r){const a=Rs(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(u=>{r.data=this.getAvcDecryptedUnit(a,u),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)}).catch(s)}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length){s();return}const r=t[e].units;for(;!(i>=r.length);i++){const a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(t,e,i,s,a),!this.decrypter.isSync()))return}}}}class Aa{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=this.VideoSample,s;if((!i||i.units.length===0)&&(i=t[t.length-1]),(e=i)!=null&&e.units){const r=i.units;s=r[r.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(t.pts===void 0){const i=e.samples,s=i.length;if(s){const r=i[s-1];t.pts=r.pts,t.dts=r.dts}else{e.dropped++;return}}e.samples.push(t)}}parseNALu(t,e,i){const s=e.byteLength;let r=t.naluState||0;const a=r,o=[];let u=0,l,d,h,c=-1,f=0;for(r===-1&&(c=0,f=this.getNALuType(e,0),r=0,u=1);u<s;){if(l=e[u++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(d=u-r-1,c>=0){const g={data:e.subarray(c,d),type:f};o.push(g)}else{const g=this.getLastNalUnit(t.samples);g&&(a&&u<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),d>0&&(g.data=pt(g.data,e.subarray(0,d)),g.state=0))}u<s?(h=this.getNALuType(e,u),c=u,f=h,r=0):r=-1}else r=0}if(c>=0&&r>=0){const g={data:e.subarray(c,s),type:f,state:r};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(t.samples);g&&(g.data=pt(g.data,e))}return t.naluState=r,o}}class ss{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,s=new Uint8Array(4),r=Math.min(4,e);if(r===0)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>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&&J.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");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)!==0)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 this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Ra extends Aa{parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let a=this.VideoSample,o,u=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(l=>{var d,h;switch(l.type){case 1:{let p=!1;o=!0;const m=l.data;if(u&&m.length>4){const y=this.readSliceType(m);(y===2||y===4||y===7||y===9)&&(p=!0)}if(p){var c;(c=a)!=null&&c.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=p;break}case 5:o=!0,(d=a)!=null&&d.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:{o=!0,As(l.data,1,i.pts,e.samples);break}case 7:{var f,g;o=!0,u=!0;const p=l.data,m=this.readSPS(p);if(!t.sps||t.width!==m.width||t.height!==m.height||((f=t.pixelRatio)==null?void 0:f[0])!==m.pixelRatio[0]||((g=t.pixelRatio)==null?void 0:g[1])!==m.pixelRatio[1]){t.width=m.width,t.height=m.height,t.pixelRatio=m.pixelRatio,t.sps=[p];const y=p.subarray(1,4);let T="avc1.";for(let v=0;v<3;v++){let S=y[v].toString(16);S.length<2&&(S="0"+S),T+=S}t.codec=T}break}case 8:o=!0,t.pps=[l.data];break;case 9:o=!0,t.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),s&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return t[e]&31}readSliceType(t){const e=new ss(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i=8,s=8,r;for(let a=0;a<t;a++)s!==0&&(r=e.readEG(),s=(i+r+256)%256),i=s===0?i:s}readSPS(t){const e=new ss(t);let i=0,s=0,r=0,a=0,o,u,l;const d=e.readUByte.bind(e),h=e.readBits.bind(e),c=e.readUEG.bind(e),f=e.readBoolean.bind(e),g=e.skipBits.bind(e),p=e.skipEG.bind(e),m=e.skipUEG.bind(e),y=this.skipScalingList.bind(this);d();const T=d();if(h(5),g(3),d(),m(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const R=c();if(R===3&&g(1),m(),m(),g(1),f())for(u=R!==3?8:12,l=0;l<u;l++)f()&&(l<6?y(16,e):y(64,e))}m();const v=c();if(v===0)c();else if(v===1)for(g(1),p(),p(),o=c(),l=0;l<o;l++)p();m(),g(1);const S=c(),A=c(),C=h(1);C===0&&g(1),g(1),f()&&(i=c(),s=c(),r=c(),a=c());let x=[1,1];if(f()&&f())switch(d()){case 1:x=[1,1];break;case 2:x=[12,11];break;case 3:x=[10,11];break;case 4:x=[16,11];break;case 5:x=[40,33];break;case 6:x=[24,11];break;case 7:x=[20,11];break;case 8:x=[32,11];break;case 9:x=[80,33];break;case 10:x=[18,11];break;case 11:x=[15,11];break;case 12:x=[64,33];break;case 13:x=[160,99];break;case 14:x=[4,3];break;case 15:x=[3,2];break;case 16:x=[2,1];break;case 255:{x=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((S+1)*16-i*2-s*2),height:(2-C)*(A+1)*16-(C?2:4)*(r+a),pixelRatio:x}}}const rt=188;class _t{constructor(t,e,i,s){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=s,this.videoParser=null}static probe(t,e){const i=_t.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(t){const e=t.length;let i=Math.min(rt*5,e-rt)+1,s=0;for(;s<i;){let r=!1,a=-1,o=0;for(let u=s;u<e;u+=rt)if(t[u]===71&&(e-u===rt||t[u+rt]===71)){if(o++,a===-1&&(a=u,a!==0&&(i=Math.min(a+rt*99,t.length-rt)+1)),r||(r=ze(t,u)===0),r&&o>1&&(a===0&&o>2||u+rt>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:ys[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,i,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=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,s=!1){i||(this.sampleAes=null);let r;const a=this._videoTrack,o=this._audioTrack,u=this._id3Track,l=this._txtTrack;let d=a.pid,h=a.pesData,c=o.pid,f=u.pid,g=o.pesData,p=u.pesData,m=null,y=this.pmtParsed,T=this._pmtId,v=t.length;if(this.remainderData&&(t=pt(this.remainderData,t),v=t.length,this.remainderData=null),v<rt&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:u,textTrack:l};const S=Math.max(0,_t.syncOffset(t));v-=(v-S)%rt,v<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,v,t.buffer.byteLength-v));let A=0;for(let x=S;x<v;x+=rt)if(t[x]===71){const R=!!(t[x+1]&64),b=ze(t,x),I=(t[x+3]&48)>>4;let _;if(I>1){if(_=x+5+t[x+4],_===x+rt)continue}else _=x+4;switch(b){case d:R&&(h&&(r=Ut(h,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,r,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(_,x+rt)),h.size+=x+rt-_);break;case c:if(R){if(g&&(r=Ut(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break}g={data:[],size:0}}g&&(g.data.push(t.subarray(_,x+rt)),g.size+=x+rt-_);break;case f:R&&(p&&(r=Ut(p,this.logger))&&this.parseID3PES(u,r),p={data:[],size:0}),p&&(p.data.push(t.subarray(_,x+rt)),p.size+=x+rt-_);break;case 0:R&&(_+=t[_]+1),T=this._pmtId=ba(t,_);break;case T:{R&&(_+=t[_]+1);const w=Ia(t,_,this.typeSupported,i,this.observer,this.logger);d=w.videoPid,d>0&&(a.pid=d,a.segmentCodec=w.segmentVideoCodec),c=w.audioPid,c>0&&(o.pid=c,o.segmentCodec=w.segmentAudioCodec),f=w.id3Pid,f>0&&(u.pid=f),m!==null&&!y&&(this.logger.warn(`MPEG-TS PMT found at ${x} after unknown PID '${m}'. Backtracking to sync byte @${S} to parse all TS packets.`),m=null,x=S-188),y=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=b;break}}else A++;A>0&&xe(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=g,u.pesData=p;const C={audioTrack:o,videoTrack:a,id3Track:u,textTrack:l};return s&&this.extractRemainingSamples(C),C}flush(){const{remainderData:t}=this;this.remainderData=null;let e;return t?e=this.demux(t,-1,!1,!0):e={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:s,textTrack:r}=t,a=i.pesData,o=e.pesData,u=s.pesData;let l;if(a&&(l=Ut(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,l,!0),i.pesData=null)):i.pesData=a,o&&(l=Ut(o,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break}e.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=o;u&&(l=Ut(u,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=u}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),r=this.sampleAes=new La(this.observer,this.config,e);return this.decrypt(s,r)}readyVideoParser(t){this.videoParser===null&&t==="avc"&&(this.videoParser=new Ra)}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&s.segmentCodec==="aac"?e.decryptAacSamples(s.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.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 s=this.aacOverFlow;let r=e.data;if(s){this.aacOverFlow=null;const h=s.missing,c=s.sample.unit.byteLength;if(h===-1)r=pt(s.sample.unit,r);else{const f=c-h;s.sample.unit.set(r.subarray(0,h),f),t.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=r.length;a<o-1&&!Se(r,a);a++);if(a!==i){let h;const c=a<o-1;if(c?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",xe(this.observer,new Error(h),c,this.logger),!c)return}ir(t,this.observer,r,a,this.audioCodec);let u;if(e.pts!==void 0)u=e.pts;else if(s){const h=sr(t.samplerate);u=s.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,d;for(;a<o;)if(d=rr(t,r,a,u,l),a+=d.length,d.missing){this.aacOverFlow=d;break}else for(l++;a<o-1&&!Se(r,a);a++);}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,a=0;const o=e.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(hr(i,a)){const u=ur(t,i,a,o,r);if(u)a+=u.length,r++;else break}else a++}parseAC3PES(t,e){}parseID3PES(t,e){if(e.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=at({},e,{type:this._videoTrack?dt.emsg:dt.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function ze(n,t){return((n[t+1]&31)<<8)+n[t+2]}function ba(n,t){return(n[t+10]&31)<<8|n[t+11]}function Ia(n,t,e,i,s,r){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(n[t+1]&15)<<8|n[t+2],u=t+3+o-4,l=(n[t+10]&15)<<8|n[t+11];for(t+=12+l;t<u;){const d=ze(n,t),h=(n[t+3]&15)<<8|n[t+4];switch(n[t]){case 207:if(!i){we("ADTS AAC",r);break}case 15:a.audioPid===-1&&(a.audioPid=d);break;case 21:a.id3Pid===-1&&(a.id3Pid=d);break;case 219:if(!i){we("H.264",r);break}case 27:a.videoPid===-1&&(a.videoPid=d);break;case 3:case 4:!e.mpeg&&!e.mp3?r.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=d,a.segmentAudioCodec="mp3");break;case 193:if(!i){we("AC-3",r);break}case 129:r.warn("AC-3 in M2TS support not included in build");break;case 6:if(a.audioPid===-1&&h>0){let c=t+5,f=h;for(;f>2;){switch(n[c]){case 106:r.warn("AC-3 in M2TS support not included in build");break}const p=n[c+1]+2;c+=p,f-=p}}break;case 194:case 135:return xe(s,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:return xe(s,new Error("Unsupported HEVC in M2TS found"),void 0,r),a}t+=h+5}return a}function xe(n,t,e,i){i.warn(`parsing error: ${t.message}`),n.emit(E.ERROR,E.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:t,reason:t.message})}function we(n,t){t.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function Ut(n,t){let e=0,i,s,r,a,o;const u=n.data;if(!n||n.size===0)return null;for(;u[0].length<19&&u.length>1;)u[0]=pt(u[0],u[1]),u.splice(1,1);if(i=u[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>n.size-6)return null;const d=i[7];d&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,d&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(t.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=i[8];let h=r+9;if(n.size<=h)return null;n.size-=h;const c=new Uint8Array(n.size);for(let f=0,g=u.length;f<g;f++){i=u[f];let p=i.byteLength;if(h)if(h>p){h-=p;continue}else i=i.subarray(h),p-=h,h=0;c.set(i,e),e+=p}return s&&(s-=r+3),{data:c,pts:a,dts:o,len:s}}return null}class Da{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(e===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(e===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(e===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(e===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Dt=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in L.types)L.types.hasOwnProperty(t)&&(L.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]);L.HDLR_TYPES={video:e,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,a,u,a,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,s))}static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(t,4),s=0,i=8;s<r;s++)a.set(e[s],i),i+=e[s].byteLength;return a}static hdlr(t){return L.box(L.types.hdlr,L.HDLR_TYPES[t])}static mdat(t){return L.box(L.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Dt+1)),s=Math.floor(e%(Dt+1));return L.box(L.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,t&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return L.box(L.types.mdia,L.mdhd(t.timescale||0,t.duration||0),L.hdlr(t.type),L.minf(t))}static mfhd(t){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(t)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(t))}static moof(t,e,i){return L.box(L.types.moof,L.mfhd(t),L.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=L.trak(t[e]);return L.box.apply(null,[L.types.moov,L.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(L.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=L.trex(t[e]);return L.box.apply(null,[L.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Dt+1)),s=Math.floor(e%(Dt+1)),r=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,t&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return L.box(L.types.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,i)}static stbl(t){return L.box(L.types.stbl,L.stsd(t),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(t){let e=[],i=[],s,r,a;for(s=0;s<t.sps.length;s++)r=t.sps[s],a=r.byteLength,e.push(a>>>8&255),e.push(a&255),e=e.concat(Array.prototype.slice.call(r));for(s=0;s<t.pps.length;s++)r=t.pps[s],a=r.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(i))),u=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return L.box(L.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,u>>8&255,u&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,h>>24,h>>16&255,h>>8&255,h&255])))}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,e&255,0,0])}static mp4a(t){return L.box(L.types.mp4a,L.audioStsd(t),L.box(L.types.esds,L.esds(t)))}static mp3(t){return L.box(L.types[".mp3"],L.audioStsd(t))}static ac3(t){return L.box(L.types["ac-3"],L.audioStsd(t),L.box(L.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if(t.type==="audio"){if(e==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(t));if(e==="mp3"&&t.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(t))}else if(t.pps&&t.sps){if(e==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(t))}else throw new Error("video track missing pps or sps");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),s=t.width||0,r=t.height||0,a=Math.floor(i/(Dt+1)),o=Math.floor(i%(Dt+1));return L.box(L.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,e&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,r>>8&255,r&255,0,0]))}static traf(t,e){const i=L.sdtp(t),s=t.id,r=Math.floor(e/(Dt+1)),a=Math.floor(e%(Dt+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),L.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,L.box(L.types.trak,L.tkhd(t),L.mdia(t))}static trex(t){const e=t.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,a=new Uint8Array(r);let o,u,l,d,h,c;for(e+=8+r,a.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),o=0;o<s;o++)u=i[o],l=u.duration,d=u.size,h=u.flags,c=u.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,c>>>24&255,c>>>16&255,c>>>8&255,c&255],12+16*o);return L.box(L.types.trun,a)}static initSegment(t){L.types||L.init();const e=L.moov(t);return pt(L.FTYP,e)}static hvc1(t){return new Uint8Array}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const Ca=9e4;function _a(n,t,e=1,i=!1){const s=n*t*e;return i?Math.round(s):s}function jt(n,t=!1){return _a(n,1e3,1/Ca,t)}function rs(n){const{baseTime:t,timescale:e,trackId:i}=n;return`${t/e} (${t}/${e}) trackId: ${i}`}const Pa=10*1e3,ka=1024,Oa=1152,Fa=1536;let Gt=null,Me=null;function ns(n,t,e,i){return{duration:t,size:e,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1}}}class Ne extends It{constructor(t,e,i,s){if(super("mp4-remuxer",s),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,Gt===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Gt=a?parseInt(a[1]):0}if(Me===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Me=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;(!e||!t||t.trackId!==e.trackId||t.baseTime!==e.baseTime||t.timescale!==e.timescale)&&this.log(`Reset initPTS: ${e&&rs(e)} > ${t&&rs(t)}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t[0].pts,s=t.reduce((r,a)=>{let o=a.pts,u=o-r;return u<-4294967296&&(e=!0,o=ht(o,i),u=o-r),u>0?r:o},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,r,a,o,u){let l,d,h,c,f,g,p=r,m=r;const y=t.pid>-1,T=e.pid>-1,v=e.samples.length,S=t.samples.length>0,A=o&&v>0||v>1;if((!y||S)&&(!T||A)||this.ISGenerated||o){if(this.ISGenerated){var x,R,b,I;const V=this.videoTrackConfig;(V&&(e.width!==V.width||e.height!==V.height||((x=e.pixelRatio)==null?void 0:x[0])!==((R=V.pixelRatio)==null?void 0:R[0])||((b=e.pixelRatio)==null?void 0:b[1])!==((I=V.pixelRatio)==null?void 0:I[1]))||!V&&A||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,r,a));const _=this.isVideoContiguous;let w=-1,$;if(A&&(w=wa(e.samples),!_&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,w>0){this.warn(`Dropped ${w} out of ${v} video samples due to a missing keyframe`);const V=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(w),e.dropped+=w,m+=(e.samples[0].pts-V)/e.inputTimeScale,$=m}else w===-1&&(this.warn(`No keyframe found out of ${v} video samples`),g=!1);if(this.ISGenerated){if(S&&A){const V=this.getVideoStartPts(e.samples),P=(ht(t.samples[0].pts,V)-V)/e.inputTimeScale;p+=Math.max(0,P),m+=Math.max(0,-P)}if(S){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,r,a)),d=this.remuxAudio(t,p,this.isAudioContiguous,a,T||A||u===W.AUDIO?m:void 0),A){const V=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,r,a)),l=this.remuxVideo(e,m,_,V)}}else A&&(l=this.remuxVideo(e,m,_,0));l&&(l.firstKeyFrame=w,l.independent=w!==-1,l.firstKeyFramePTS=$)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=fr(i,r,this._initPTS,this._initDTS)),s.samples.length&&(c=gr(s,r,this._initPTS))),{audio:d,video:l,initSegment:h,independent:g,text:c,id3:f}}computeInitPts(t,e,i,s){const r=Math.round(i*e);let a=ht(t,r);if(a<r+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/e} ${s}`);a<r+e;)a+=8589934592;return a-r}generateIS(t,e,i,s){const r=t.samples,a=e.samples,o=this.typeSupported,u={},l=this._initPTS;let d=!l||s,h="audio/mp4",c,f,g,p=-1;if(d&&(c=f=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3";break}u.audio={id:"audio",container:h,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([t]),metadata:{channelCount:t.channelCount}},d&&(p=t.id,g=t.inputTimeScale,!l||g!==l.timescale?c=f=this.computeInitPts(r[0].pts,g,i,"audio"):d=!1)}if(e.sps&&e.pps&&a.length){if(e.timescale=e.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:L.initSegment([e]),metadata:{width:e.width,height:e.height}},d)if(p=e.id,g=e.inputTimeScale,!l||g!==l.timescale){const m=this.getVideoStartPts(a),y=ht(a[0].dts,m),T=this.computeInitPts(y,g,i,"video"),v=this.computeInitPts(m,g,i,"video");f=Math.min(f,T),c=Math.min(c,v)}else d=!1;this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,d?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${c/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${c/g} (${c}/${g}) trackId: ${p}`),this._initPTS={baseTime:c,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):c=g=void 0,{tracks:u,initPTS:c,timescale:g,trackId:p}}remuxVideo(t,e,i,s){const r=t.inputTimeScale,a=t.samples,o=[],u=a.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let h=this.nextVideoTs,c=8,f=this.videoSampleDuration,g,p,m=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,T=!1;if(!i||h===null){const O=d+e*r,F=a[0].pts-ht(a[0].dts,a[0].pts);Gt&&h!==null&&Math.abs(O-F-(h+d))<15e3?i=!0:h=O-F-d}const v=h+d;for(let O=0;O<u;O++){const F=a[O];F.pts=ht(F.pts,v),F.dts=ht(F.dts,v),F.dts<a[O>0?O-1:O].dts&&(T=!0)}T&&a.sort(function(O,F){const z=O.dts-F.dts,Z=O.pts-F.pts;return z||Z}),g=a[0].dts,p=a[a.length-1].dts;const S=p-g,A=S?Math.round(S/(u-1)):f||t.inputTimeScale/30;if(i){const O=g-v,F=O>A,z=O<-1;if((F||z)&&(F?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${jt(O,!0)} ms (${O}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${jt(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!z||v>=a[0].pts||Gt)){g=v;const Z=a[0].pts-O;if(F)a[0].dts=g,a[0].pts=Z;else{let Q=!0;for(let it=0;it<a.length&&!(a[it].dts>Z&&Q);it++){const Et=a[it].pts;if(a[it].dts-=O,a[it].pts-=O,it<a.length-1){const St=a[it+1].pts,Nt=a[it].pts,Ot=St<=Nt,Yt=St<=Et;Q=Ot==Yt}}}this.log(`Video: Initial PTS/DTS adjusted: ${jt(Z,!0)}/${jt(g,!0)}, delta: ${jt(O,!0)} ms`)}}g=Math.max(0,g);let C=0,x=0,R=g;for(let O=0;O<u;O++){const F=a[O],z=F.units,Z=z.length;let Q=0;for(let it=0;it<Z;it++)Q+=z[it].data.length;x+=Q,C+=Z,F.length=Q,F.dts<R?(F.dts=R,R+=A/4|0||1):R=F.dts,m=Math.min(F.pts,m),y=Math.max(F.pts,y)}p=a[u-1].dts;const b=x+4*C+8;let I;try{I=new Uint8Array(b)}catch(O){this.observer.emit(E.ERROR,E.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:b,reason:`fail allocating video mdat ${b}`});return}const _=new DataView(I.buffer);_.setUint32(0,b),I.set(L.types.mdat,4);let w=!1,$=Number.POSITIVE_INFINITY,V=Number.POSITIVE_INFINITY,N=Number.NEGATIVE_INFINITY,P=Number.NEGATIVE_INFINITY;for(let O=0;O<u;O++){const F=a[O],z=F.units;let Z=0;for(let Et=0,St=z.length;Et<St;Et++){const Nt=z[Et],Ot=Nt.data,Yt=Nt.data.byteLength;_.setUint32(c,Yt),c+=4,I.set(Ot,c),c+=Yt,Z+=4+Yt}let Q;if(O<u-1)f=a[O+1].dts-F.dts,Q=a[O+1].pts-F.pts;else{const Et=this.config,St=O>0?F.dts-a[O-1].dts:A;if(Q=O>0?F.pts-a[O-1].pts:A,Et.stretchShortVideoTrack&&this.nextAudioTs!==null){const Nt=Math.floor(Et.maxBufferHole*r),Ot=(s?m+s*r:this.nextAudioTs+d)-F.pts;Ot>Nt?(f=Ot-St,f<0?f=St:w=!0,this.log(`It is approximately ${Ot/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=St}else f=St}const it=Math.round(F.pts-F.dts);$=Math.min($,f),N=Math.max(N,f),V=Math.min(V,Q),P=Math.max(P,Q),o.push(ns(F.key,f,Z,it))}if(o.length){if(Gt){if(Gt<70){const O=o[0].flags;O.dependsOn=2,O.isNonSync=0}}else if(Me&&P-V<N-$&&A/N<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=g;for(let F=0,z=o.length;F<z;F++){const Z=O+o[F].duration,Q=O+o[F].cts;if(F<z-1){const it=Z+o[F+1].cts;o[F].duration=it-Q}else o[F].duration=F?o[F-1].duration:A;o[F].cts=0,O=Z}}}f=w||!f?A:f;const G=p+f;this.nextVideoTs=h=G-d,this.videoSampleDuration=f,this.isVideoContiguous=!0;const K={data1:L.moof(t.sequenceNumber++,g,at(t,{samples:o})),data2:I,startPTS:(m-d)/r,endPTS:(y+f-d)/r,startDTS:(g-d)/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,K}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return Oa;case"ac3":return Fa;default:return ka}}remuxAudio(t,e,i,s,r){const a=t.inputTimeScale,o=t.samplerate?t.samplerate:a,u=a/o,l=this.getSamplesPerFrame(t),d=l*u,h=this._initPTS,c=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let p=t.samples,m=c?0:8,y=this.nextAudioTs||-1;const T=h.baseTime*a/h.timescale,v=T+e*a;if(this.isAudioContiguous=i=i||p.length&&y>0&&(s&&Math.abs(v-(y+T))<9e3||Math.abs(ht(p[0].pts,v)-(y+T))<20*d),p.forEach(function(P){P.pts=ht(P.pts,v)}),!i||y<0){const P=p.length;if(p=p.filter(G=>G.pts>=0),P!==p.length&&this.warn(`Removed ${p.length-P} of ${P} samples (initPTS ${T} / ${a})`),!p.length)return;r===0?y=0:s&&!g?y=Math.max(0,v-T):y=p[0].pts-T}if(t.segmentCodec==="aac"){const P=this.config.maxAudioFramesDrift;for(let G=0,M=y+T;G<p.length;G++){const U=p[G],K=U.pts,O=K-M,F=Math.abs(1e3*O/a);if(O<=-P*d&&g)G===0&&(this.warn(`Audio frame @ ${(K/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*O/a)} ms.`),this.nextAudioTs=y=K-T,M=K);else if(O>=P*d&&F<Pa&&g){let z=Math.round(O/d);for(M=K-z*d;M<0&&z&&d;)z--,M+=d;G===0&&(this.nextAudioTs=y=M-T),this.warn(`Injecting ${z} audio frames @ ${((M-T)/a).toFixed(3)}s due to ${Math.round(1e3*O/a)} ms gap.`);for(let Z=0;Z<z;Z++){let Q=Da.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);Q||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Q=U.unit.subarray()),p.splice(G,0,{unit:Q,pts:M}),M+=d,G++}}U.pts=M,M+=d}}let S=null,A=null,C,x=0,R=p.length;for(;R--;)x+=p[R].unit.byteLength;for(let P=0,G=p.length;P<G;P++){const M=p[P],U=M.unit;let K=M.pts;if(A!==null){const F=f[P-1];F.duration=Math.round((K-A)/u)}else if(i&&t.segmentCodec==="aac"&&(K=y+T),S=K,x>0){x+=m;try{C=new Uint8Array(x)}catch(F){this.observer.emit(E.ERROR,E.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:x,reason:`fail allocating audio mdat ${x}`});return}c||(new DataView(C.buffer).setUint32(0,x),C.set(L.types.mdat,4))}else return;C.set(U,m);const O=U.byteLength;m+=O,f.push(ns(!0,l,O,0)),A=K}const b=f.length;if(!b)return;const I=f[f.length-1];y=A-T,this.nextAudioTs=y+u*I.duration;const _=c?new Uint8Array(0):L.moof(t.sequenceNumber++,S/u,at({},t,{samples:f}));t.samples=[];const w=(S-T)/a,$=this.nextAudioTs/a,N={data1:_,data2:C,startPTS:w,endPTS:$,startDTS:w,endDTS:$,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,N}}function ht(n,t){let e;if(t===null)return n;for(t<n?e=-8589934592:e=8589934592;Math.abs(n-t)>4294967296;)n+=e;return n}function wa(n){for(let t=0;t<n.length;t++)if(n[t].key)return t;return-1}function fr(n,t,e,i){const s=n.samples.length;if(!s)return;const r=n.inputTimeScale;for(let o=0;o<s;o++){const u=n.samples[o];u.pts=ht(u.pts-e.baseTime*r/e.timescale,t*r)/r,u.dts=ht(u.dts-i.baseTime*r/i.timescale,t*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function gr(n,t,e){const i=n.samples.length;if(!i)return;const s=n.inputTimeScale;for(let a=0;a<i;a++){const o=n.samples[a];o.pts=ht(o.pts-e.baseTime*s/e.timescale,t*s)/s}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class Ma extends It{constructor(t,e,i,s){super("passthrough-remuxer",s),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,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,s),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:s}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:a}=this.initData=xs(t);if(e)Br(t,e);else{const u=r||a;u!=null&&u.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${u.codec}")!`)}r&&(i=as(r,et.AUDIO,this)),a&&(s=as(a,et.VIDEO,this));const o={};r&&a?o.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:r?o.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,e,i,s,r,a){var o,u;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};B(d)||(d=this.lastEndTime=r||0);const c=e.samples;if(!c.length)return h;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(c),g=this.initData),!((u=g)!=null&&u.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=Gr(c,g,this),m=g.audio?p[g.audio.id]:null,y=g.video?p[g.video.id]:null,T=ue(y,1/0),v=ue(m,1/0),S=ue(y,0,!0),A=ue(m,0,!0);let C=r,x=0;const R=m&&(!y||!l&&v<T||l&&l.trackId===g.audio.id),b=R?m:y;if(b){const M=b.timescale,U=b.start-r*M,K=R?g.audio.id:g.video.id;C=b.start/M,x=R?A-v:S-T,(a||!l)&&(Na(l,C,r,x)||M!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${r} ${U/M} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${C-r} (${U}/${M}) trackId: ${K}`),l=null,f.initPTS=U,f.timescale=M,f.trackId=K)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=C,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const I=C-l.baseTime/l.timescale,_=I+x;x>0?this.lastEndTime=_:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!g.audio,$=!!g.video;let V="";w&&(V+="audio"),$&&(V+="video");const N=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),P={data1:c,startPTS:I,startDTS:I,endPTS:_,endDTS:_,type:V,hasAudio:w,hasVideo:$,nb:1,dropped:0,encrypted:N};h.audio=w&&!$?P:void 0,h.video=$?P:void 0;const G=y==null?void 0:y.sampleCount;if(G){const M=y.keyFrameIndex,U=M!==-1;P.nb=G,P.dropped=M===0||this.isVideoContiguous?0:U?M:G,P.independent=U,P.firstKeyFrame=M,U&&y.keyFrameStart&&(P.firstKeyFramePTS=(y.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=U),this.isVideoContiguous||(this.isVideoContiguous=U),P.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${M}/${G} dropped: ${P.dropped} start: ${P.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=fr(i,r,l,l),s.samples.length&&(h.text=gr(s,r,l)),h}}function ue(n,t,e=!1){return(n==null?void 0:n.start)!==void 0?(n.start+(e?n.duration:0))/n.timescale:t}function Na(n,t,e,i){if(n===null)return!0;const s=Math.max(i,1),r=t-n.baseTime/n.timescale;return Math.abs(r-e)>s}function as(n,t,e){const i=n.codec;return i&&i.length>4?i:t===et.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?pe(i,!1):(e.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(e.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let At;try{At=self.performance.now.bind(self.performance)}catch{At=Date.now}const Be=[{demux:xa,remux:Ma},{demux:_t,remux:Ne},{demux:va,remux:Ne},{demux:Ta,remux:Ne}];class os{constructor(t,e,i,s,r,a){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=r,this.logger=a}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const r=i.transmuxing;r.executeStart=At();let a=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:u}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:c,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:p,videoCodec:m,defaultInitPts:y,duration:T,initSegmentData:v}=u,S=Ba(a,e);if(S&&Xt(S.method)){const R=this.getDecrypter(),b=ws(S.method);if(R.isSync()){let I=R.softwareDecrypt(a,S.key.buffer,S.iv.buffer,b);if(i.part>-1){const w=R.flush();I=w&&w.buffer}if(!I)return r.executeEnd=At(),$e(i);a=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=R.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,b).then(I=>{const _=this.push(I,null,i);return this.decryptionPromise=null,_}),this.decryptionPromise}const A=this.needsProbing(d,h);if(A){const R=this.configureTransmuxer(a);if(R)return this.logger.warn(`[transmuxer] ${R.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),r.executeEnd=At(),$e(i)}(d||h||g||A)&&this.resetInitSegment(v,p,m,T,e),(d||g||A)&&this.resetInitialTimestamp(y),l||this.resetContiguity();const C=this.transmux(a,S,f,c,i);this.asyncResult=te(C);const x=this.currentTransmuxState;return x.contiguous=!0,x.discontinuity=!1,x.trackSwitch=!1,r.executeEnd=At(),C}flush(t){const e=t.transmuxing;e.executeStart=At();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const a=[],{timeOffset:o}=s;if(i){const h=i.flush();h&&a.push(this.push(h.buffer,null,t))}const{demuxer:u,remuxer:l}=this;if(!u||!l){e.executeEnd=At();const h=[$e(t)];return this.asyncResult?Promise.resolve(h):h}const d=u.flush(o);return te(d)?(this.asyncResult=!0,d.then(h=>(this.flushRemux(a,h,t),a))):(this.flushRemux(a,d,t),this.asyncResult?Promise.resolve(a):a)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:r,id3Track:a,textTrack:o}=e,{accurateTimeOffset:u,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===W.MAIN?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,a,o,l,u,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=At()}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,s,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(t,e,i,s),o.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,r){let a;return e&&e.method==="SAMPLE-AES"?a=this.transmuxSampleAes(t,e,i,s,r):a=this.transmuxUnencrypted(t,i,s,r),a}transmuxUnencrypted(t,e,i,s){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:u}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,u,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer.demuxSampleAes(t,e,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;let r;for(let h=0,c=Be.length;h<c;h++){var a;if((a=Be[h].demux)!=null&&a.probe(t,this.logger)){r=Be[h];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,u=this.remuxer,l=r.remux,d=r.demux;(!u||!(u instanceof l))&&(this.remuxer=new l(i,e,s,this.logger)),(!o||!(o instanceof d))&&(this.demuxer=new d(i,e,s,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new li(this.config)),t}}function Ba(n,t){let e=null;return n.byteLength>0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const $e=n=>({remuxResult:{},chunkMeta:n});function te(n){return"then"in n&&n.then instanceof Function}class $a{constructor(t,e,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class Ua{constructor(t,e,i,s,r,a){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=s,this.timeOffset=r,this.initSegmentChange=a}}function mr(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Ga=/(\d+)-(\d+)\/(\d+)/;class Xe{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||Wa,this.controller=new self.AbortController,this.stats=new Le}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(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=Va(t,this.controller.signal),a=t.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=u&&B(u)?u:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},e.timeout),(te(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var c;this.response=this.loader=h;const f=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},l-(f-s.loading.start)),!h.ok){const{status:p,statusText:m}=h;throw new Ya(m||"fetch, bad network response",p,h)}s.loading.first=f,s.total=Ha(h.headers)||s.total;const g=(c=this.callbacks)==null?void 0:c.onProgress;return g&&B(e.highWaterMark)?this.loadProgressively(h,s,t,e.highWaterMark,g):a?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var c,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=h[o];p&&(s.loaded=s.total=p);const m={url:g.url,data:h,code:g.status},y=(c=this.callbacks)==null?void 0:c.onProgress;y&&!B(e.highWaterMark)&&y(s,t,h,g),(f=this.callbacks)==null||f.onSuccess(m,s,t,g)}).catch(h=>{var c;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const f=h&&h.code||0,g=h?h.message:null;(c=this.callbacks)==null||c.onError({code:f,text:g},t,h?h.details:null,s)})}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,s=0,r){const a=new Yn,o=t.body.getReader(),u=()=>o.read().then(l=>{if(l.done)return a.dataLength&&r(e,i,a.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const d=l.value,h=d.length;return e.loaded+=h,h<s||a.dataLength?(a.push(d),a.dataLength>=s&&r(e,i,a.flush().buffer,t)):r(e,i,d.buffer,t),u()}).catch(()=>Promise.reject());return u()}}function Va(n,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(at({},n.headers))};return n.rangeEnd&&e.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),e}function Ka(n){const t=Ga.exec(n);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Ha(n){const t=n.get("Content-Range");if(t){const i=Ka(t);if(B(i))return i}const e=n.get("Content-Length");if(e)return parseInt(e)}function Wa(n,t){return new self.Request(n.url,t)}class Ya extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const ja=/^age:\s*[\d.]+\s*$/im;class fi{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 Le,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,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&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,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,e.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",e.url,!0),r(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const o in s)t.setRequestHeader(o,s[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=r&&B(r)?r:a,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 s=e.readyState,r=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const l=e.status,d=e.responseType==="text"?e.responseText:null;if(l>=200&&l<300){const g=d??e.response;if(g!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=e.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=p,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const m=(a=this.callbacks)==null?void 0:a.onProgress;m&&m(i,t,g,e);const y={url:e.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(y,i,t,e);return}}const h=r.loadPolicy.errorRetry,c=i.retry,f={url:t.url,data:void 0,code:l};if(ye(h,c,!1,f))this.retry(h);else{var u;J.error(`${l} while loading ${t.url}`),(u=this.callbacks)==null||u.onError({code:l,text:e.statusText},t,e,i)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(ye(t,e,!0))this.retry(t);else{var i;J.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=ai(t,i.retry),i.retry++,J.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e==null?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&&ja.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 ls={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},qa=ft(ft({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:fi,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Ds,bufferController:qs,capLevelController:Ae,errorController:ks,fpsController:Qs,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:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!1,preserveManualLevelOnError:!1,certLoadPolicy:{default:ls},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:ls},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},za()),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:zs,interstitialsController:void 0});function za(){return{cueHandler:Mt,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Xa(n,t,e){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Qe(n),s=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,u=t[o]===void 0,l=[];r.forEach(d=>{const h=`${a}Loading${d}`,c=t[h];if(c!==void 0&&u){l.push(h);const f=i[o].default;switch(t[o]={default:f},d){case"TimeOut":f.maxLoadTimeMs=c,f.maxTimeToFirstByteMs=c;break;case"MaxRetry":f.errorRetry.maxNumRetry=c,f.timeoutRetry.maxNumRetry=c;break;case"RetryDelay":f.errorRetry.retryDelayMs=c,f.timeoutRetry.retryDelayMs=c;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=c,f.timeoutRetry.maxRetryDelayMs=c;break}}}),l.length&&e.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ot(t[o])}`)}),ft(ft({},i),t)}function Qe(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(Qe):Object.keys(n).reduce((t,e)=>(t[e]=Qe(n[e]),t),{}):n}function Qa(n,t){const e=n.loader;e!==Xe&&e!==fi?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):mr()&&(n.loader=Xe,n.progressive=!0,n.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const ge=2,Za=.1,Ja=.05,to=100;class eo extends Hs{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 i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.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(to),this.mediaSource=e.mediaSource;const i=this.media=e.media;Ft(i,"playing",this.onMediaPlaying),Ft(i,"waiting",this.onMediaWaiting),Ft(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(Pt(i,"playing",this.onMediaPlaying),Pt(i,"waiting",this.onMediaWaiting),Pt(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(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var i,s;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,u=this.seeking&&!o,l=!this.seeking&&o,d=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,t!==e){e&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),this.waiting===0&&this.stallResolved(t);return}if(l||u){u&&this.stallResolved(t);return}if(d){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&a.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(a).length){this.nudgeRetry=0;return}const h=q.bufferInfo(a,t,0),c=h.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const C=us(this.hls.inFlightFragments,t),x=h.len>ge,R=!c||C||c-t>ge&&!f.getPartialFragment(t);if(x||R)return;this.moved=!1}const g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!c)return;const x=Math.max(c,h.start||0)-t,b=!!(g!=null&&g.live)?g.targetduration*2:ge,I=de(t,f);if(x>0&&(x<=b||I)){a.paused||this._trySkipBufferHole(I);return}}const p=r.detectStallWithCurrentTimeMs,m=self.performance.now(),y=this.waiting;let T=this.stalled;if(T===null)if(y>0&&m-y<p)T=this.stalled=y;else{this.stalled=m;return}const v=m-T;if(!o&&(v>=p||y)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(t-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const A=q.bufferInfo(a,t,r.maxBufferHole);this._tryFixBufferStall(A,v,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(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&t>s.end(0)){const r=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),t,0);if(r.len>1&&e>=r.start){const a=q.timeRangesToArray(s),o=q.bufferedInfo(a,e,0).bufferedIndex;if(o>-1&&o<a.length-1){const u=q.bufferedInfo(a,t,0).bufferedIndex,l=a[o].end,d=a[o+1].start;if((u===-1||u>o)&&d-l<1&&t-l<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${l} -> ${d} buffered index: ${u}`);this.warn(h.message),this.media.currentTime+=1e-6;let c=de(t,this.fragmentTracker);c&&"fragment"in c?c=c.fragment:c||(c=void 0);const f=q.bufferInfo(this.media,t,0);this.hls.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:c,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(t,e,i){var s,r;const{fragmentTracker:a,media:o}=this,u=(s=this.hls)==null?void 0:s.config;if(!o||!a||!u)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,d=de(i,a);if((d||l!=null&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const h=t.buffered,c=this.adjacentTraversal(t,i);(h&&h.length>1&&t.len>u.maxBufferHole||t.nextStart&&(t.nextStart-i<u.maxBufferHole||c))&&(e>u.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,s=t.nextStart;if(i&&s){const r=i.getFragAtPos(e,W.MAIN),a=i.getFragAtPos(s,W.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:s,stalled:r}=this;if(!s&&r!==null&&i&&e){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ot(t)})`);this.warn(a.message),e.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:s}=this,r=(e=this.hls)==null?void 0:e.config;if(!s||!i||!r)return 0;const a=s.currentTime,o=q.bufferInfo(s,a,0),u=a<o.start?o.start:o.nextStart;if(u&&this.hls){const d=o.len<=r.maxBufferHole,h=o.len>0&&o.len<1&&s.readyState<3,c=u-a;if(c>0&&(d||h)){if(c>r.maxBufferHole){let g=!1;if(a===0){const p=i.getAppendedFrag(0,W.MAIN);p&&u<p.end&&(g=!0)}if(!g&&t){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||us(this.hls.inFlightFragments,u))return 0;let m=!1,y=t.end;for(;y<u;){const T=de(y,i);if(T)y+=T.duration;else{m=!0;break}}if(m)return 0}}const f=Math.max(u+Ja,a+Za);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,s.currentTime=f,!(t!=null&&t.gap)){const g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};t&&("fragment"in t?p.part=t:p.frag=t),this.hls.trigger(E.ERROR,p)}return f}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:s}=this,r=e==null?void 0:e.config;if(!i||!r)return 0;const a=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const o=a+(s+1)*r.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(u.message),i.currentTime=o,e.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1,buffer:t.len,bufferInfo:t})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),e.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:t.len,bufferInfo:t})}}}function us(n,t){const e=ds(n.main);if(e&&e.start<=t)return e;const i=ds(n.audio);return i&&i.start<=t?i:null}function ds(n){if(!n)return null;switch(n.state){case k.IDLE:case k.STOPPED:case k.ENDED:case k.ERROR:return null}return n.frag}function de(n,t){return t.getAppendedFrag(n,W.MAIN)||t.getPartialFragment(n)}function io(n,t){let e;try{e=new Event("addtrack")}catch{e=document.createEvent("Event"),e.initEvent("addtrack",!1,!1)}e.track=n,t.dispatchEvent(e)}function so(n,t){const e=n.mode;if(e==="disabled"&&(n.mode="hidden"),n.cues)for(let i=n.cues.length;i--;)t&&n.cues[i].removeEventListener("enter",t),n.removeCue(n.cues[i]);e==="disabled"&&(n.mode=e)}function ro(n,t,e,i){const s=n.mode;if(s==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=ao(n.cues,t,e);for(let a=0;a<r.length;a++)(!i||i(r[a]))&&n.removeCue(r[a])}s==="disabled"&&(n.mode=s)}function no(n,t){if(t<=n[0].startTime)return 0;const e=n.length-1;if(t>n[e].endTime)return-1;let i=0,s=e,r;for(;i<=s;)if(r=Math.floor((s+i)/2),t<n[r].startTime)s=r-1;else if(t>n[r].startTime&&i<e)i=r+1;else return r;return n[i].startTime-t<t-n[s].startTime?i:s}function ao(n,t,e){const i=[],s=no(n,t);if(s>-1)for(let r=s,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=t&&o.endTime<=e)i.push(o);else if(o.startTime>e)return i}return i}const oo=.25;function Ze(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function hs(n,t,e,i,s){let r=new n(t,e,"");try{r.value=i,s&&(r.type=s)}catch{r=new n(t,e,ot(s?ft({type:s},i):i))}return r}const he=(()=>{const n=Ze();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class lo{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(E.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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,((i=e.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;const e=(t=this.hls)==null?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null,!e.transferMedia&&(this.id3Track&&(this.removeCues&&so(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(i.kind==="metadata"&&i.label==="id3")return io(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Ze();if(a)for(let o=0;o<r.length;o++){const u=r[o].type;if(u===dt.emsg&&!i||!s)continue;const l=nr(r[o].data),d=r[o].pts;let h=d+r[o].duration;h>he&&(h=he),h-d<=0&&(h=d+oo);for(let f=0;f<l.length;f++){const g=l[f];if(!ar(g)){this.updateId3CueEnds(d,u);const p=hs(a,d,h,g,u);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(t,e){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let r=s.length;r--;){const a=s[r];a.type===e&&a.startTime<t&&a.endTime===he&&(a.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:u}}=a;if(r&&(o||u)){let l;s==="audio"?l=d=>d.type===dt.audioId3&&u:s==="video"?l=d=>d.type===dt.emsg&&o:l=d=>d.type===dt.audioId3&&u||d.type===dt.emsg&&o,ro(r,e,i,l)}}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:s,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=Ze();if(!t.hasProgramDateTime)return;const{id3Track:u}=this,{dateRanges:l}=t,d=Object.keys(l);let h=this.dateRangeCuesAppended;if(u&&e){var c;if((c=u.cues)!=null&&c.length){const p=Object.keys(h).filter(m=>!d.includes(m));for(let m=p.length;m--;){var f;const y=p[m],T=(f=h[y])==null?void 0:f.cues;delete h[y],T&&Object.keys(T).forEach(v=>{const S=T[v];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{u.removeCue(S)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const g=t.fragments[t.fragments.length-1];if(!(d.length===0||!B(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<d.length;p++){const m=d[p],y=l[m],T=y.startTime,v=h[m],S=(v==null?void 0:v.cues)||{};let A=(v==null?void 0:v.durationKnown)||!1,C=he;const{duration:x,endDate:R}=y;if(R&&x!==null)C=T+x,A=!0;else if(y.endOnNext&&!A){const I=d.reduce((_,w)=>{if(w!==y.id){const $=l[w];if($.class===y.class&&$.startDate>y.startDate&&(!_||y.startDate<_.startDate))return $}return _},null);I&&(C=I.startTime,A=!0)}const b=Object.keys(y.attr);for(let I=0;I<b.length;I++){const _=b[I];if(!hn(_))continue;const w=S[_];if(w)A&&!(v!=null&&v.durationKnown)?w.endTime=C:Math.abs(w.startTime-T)>.01&&(w.startTime=T,w.endTime=C);else if(o){let $=y.attr[_];cn(_)&&($=ps($));const N=hs(o,T,C,{key:_,data:$},dt.dateRange);N&&(N.id=m,this.id3Track.addCue(N),S[_]=N)}}h[m]={cues:S,dateRange:y,durationKnown:A}}}}}class uo{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:e}=this,i=this.levelDetails;if(!e||!i)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=this.config;if(!r||a===1||!i.live)return;const o=this.targetLatency;if(o===null)return;const u=s-o,l=Math.min(this.maxLatency,o+i.targetduration);if(u<l&&u>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,a)),c=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,f=Math.min(h,Math.max(1,c));this.changeMediaPlaybackRate(e,f)}else e.playbackRate!==1&&e.playbackRate!==0&&this.changeMediaPlaybackRate(e,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,u=this.hls.userConfig;let l=o&&i||e;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:a*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(t===null||e===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,r=t-e-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const e=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;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(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.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===D.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,s;t.playbackRate!==e&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}class ho extends Ks{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.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,s=[],r={},a={};let o=!1,u=!1,l=!1;e.levels.forEach(d=>{const h=d.attrs;let{audioCodec:c,videoCodec:f}=d;c&&(d.audioCodec=c=pe(c,i)||void 0),f&&(f=d.videoCodec=qr(f));const{width:g,height:p,unknownCodecs:m}=d,y=(m==null?void 0:m.length)||0;if(o||(o=!!(g&&p)),u||(u=!!f),l||(l=!!c),y||c&&!this.isAudioSupported(c)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:T,"FRAME-RATE":v,"HDCP-LEVEL":S,"PATHWAY-ID":A,RESOLUTION:C,"VIDEO-RANGE":x}=h,b=`${`${A||"."}-`}${d.bitrate}-${C}-${v}-${T}-${x}-${S}`;if(r[b])if(r[b].uri!==d.url&&!d.attrs["PATHWAY-ID"]){const I=a[b]+=1;d.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const _=this.createLevel(d);r[b]=_,s.push(_)}else r[b].addGroupId("audio",h.AUDIO),r[b].addGroupId("text",h.SUBTITLES);else{const I=this.createLevel(d);r[b]=I,a[b]=1,s.push(I)}}),this.filterAndSortMediaOptions(s,e,o,u,l)}createLevel(t){const e=new ri(t),i=t.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),e.supportedResult=wt.getUnsupportedResult(s,[])}return e}isAudioSupported(t){return Zt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Zt(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,s,r){var a;let o=[],u=[],l=t;const d=((a=e.stats)==null?void 0:a.parsing)||{};if((i||s)&&r&&(l=l.filter(({videoCodec:T,videoRange:v,width:S,height:A})=>(!!T||!!(S&&A))&&Qr(v))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",v=T;e.levels.length&&(v=`one or more CODECS in variant not supported: ${ot(e.levels.map(A=>A.attrs.CODECS).filter((A,C,x)=>x.indexOf(A)===C))}`,this.warn(v),T+=` (${v})`);const S=new Error(T);this.hls.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:S,reason:v})}}),d.end=performance.now();return}e.audioTracks&&(o=e.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),cs(o)),e.subtitles&&(u=e.subtitles,cs(u));const h=l.slice(0);l.sort((T,v)=>{if(T.attrs["HDCP-LEVEL"]!==v.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(v.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&T.height!==v.height)return T.height-v.height;if(T.frameRate!==v.frameRate)return T.frameRate-v.frameRate;if(T.videoRange!==v.videoRange)return Ee.indexOf(T.videoRange)-Ee.indexOf(v.videoRange);if(T.videoCodec!==v.videoCodec){const S=xi(T.videoCodec),A=xi(v.videoCodec);if(S!==A)return A-S}if(T.uri===v.uri&&T.codecSet!==v.codecSet){const S=me(T.codecSet),A=me(v.codecSet);if(S!==A)return A-S}return T.averageBitrate!==v.averageBitrate?T.averageBitrate-v.averageBitrate:0});let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length)){for(let T=0;T<h.length;T++)if(h[T].pathwayId===l[0].pathwayId){c=h[T];break}}this._levels=l;for(let T=0;T<l.length;T++)if(l[T]===c){var f;this._firstLevel=T;const v=c.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${v}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const A=Math.min(v,this.hls.config.abrEwmaDefaultEstimateMax);A>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const g=r&&!s,p=this.hls.config,m=!!(p.audioStreamController&&p.audioTrackController),y={levels:l,audioTracks:o,subtitleTracks:u,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:s,altAudio:m&&!g&&o.some(T=>!!T.url)};d.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,y)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){const d=new Error("invalid level idx"),h=t<0;if(this.hls.trigger(E.ERROR,{type:Y.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:t,fatal:h,error:d,reason:d.message}),h)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,a=e[t],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=a,i===t&&s&&r===o)return;this.log(`Switching to level ${t} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const u={level:t,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,u);const l=a.details;if(!l||l.live){const d=this.switchParams(a.uri,s==null?void 0:s.details,l);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?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(s=>e.indexOf(s)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);return}this.steering.pathwayPriority=i}}onError(t,e){e.fatal||!e.context||e.context.type===X.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e!==void 0&&e.type===W.MAIN){const i=e.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const s=this._levels[e.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,a=e.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=e.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||e.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let u=a.details;u===e.details&&u.advanced&&(u=void 0),this.playlistLoaded(s,e,u)}else(i=e.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],a=t.details,o=a==null?void 0:a.age;this.log(`Loading level index ${s}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(E.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(this._levels.length===1)return;const i=this._levels.filter((r,a)=>a!==t?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Vs(i),this._levels=i,this.currentLevelIndex>-1&&(e=this.currentLevel)!=null&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(E.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(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function cs(n){const t={};n.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}const ee="1.6.15",Wt={};function co(){return typeof __HLS_WORKER_BUNDLE__=="function"}function fo(){const n=Wt[ee];if(n)return n.clientCount++,n;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t),s={worker:new self.Worker(e),objectURL:e,clientCount:1};return Wt[ee]=s,s}function go(n){const t=Wt[n];if(t)return t.clientCount++,t;const e=new self.URL(n,self.location.href).href,s={worker:new self.Worker(e),scriptURL:e,clientCount:1};return Wt[n]=s,s}function mo(n){const t=Wt[n||ee];if(t&&t.clientCount--===1){const{worker:i,objectURL:s}=t;delete Wt[n||ee],s&&self.URL.revokeObjectURL(s),i.terminate()}}let fs=0;class po{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=fs++,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=u=>{const l=u.data,d=this.hls;if(!(!d||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var h;const c=(h=this.workerContext)==null?void 0:h.objectURL;c&&self.URL.revokeObjectURL(c);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{d.logger[l.data.logType]&&d.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,d.trigger(l.event,l.data);break}}},this.onWorkerError=u=>{if(!this.hls)return;const l=new Error(`${u.message} (${u.filename}:${u.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(u,l)=>{l=l||{},l.frag=this.frag||void 0,u===E.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(u,l)};this.observer=new Zs,this.observer.on(E.FRAG_DECRYPTED,a),this.observer.on(E.ERROR,a);const o=Ai(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const u=this.hls.logger;if(r.workerPath||co()){try{r.workerPath?(u.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=go(r.workerPath)):(u.log(`injecting Web Worker for "${e}"`),this.workerContext=fo());const{worker:d}=this.workerContext;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:e,config:ot(r)})}catch(d){u.warn(`Error setting up "${e}" Web Worker, fallback to inline`,d),this.terminateWorker(),this.error=null,this.transmuxer=new os(this.observer,o,r,"",e,t.logger)}return}}this.transmuxer=new os(this.observer,o,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=fs++;const e=this.hls.config,i=Ai(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:ot(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),mo(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.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,s,r,a,o,u,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,p=a?a.start:r.start,m=r.decryptdata,y=this.frag,T=!(y&&r.cc===y.cc),v=!(y&&l.level===y.level),S=y?l.sn-y.sn:-1,A=this.part?l.part-this.part.index:-1,C=S===0&&l.id>1&&l.id===(y==null?void 0:y.stats.chunkCount),x=!v&&(S===1||S===0&&(A===1||C&&A<=0)),R=self.performance.now();(v||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=R),a&&(A||!x)&&(a.stats.parsing.start=R);const b=!(y&&((h=r.initSegment)==null?void 0:h.url)===((c=y.initSegment)==null?void 0:c.url)),I=new Ua(T,x,u,v,p,b);if(!x||T||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===W.MAIN?"level":"track"}: ${l.level} id: ${l.id}
22
+ discontinuity: ${T}
23
+ trackSwitch: ${v}
24
+ contiguous: ${x}
25
+ accurateTimeOffset: ${u}
26
+ timeOffset: ${p}
27
+ initSegmentChange: ${b}`);const _=new $a(i,s,e,o,d);this.configureTransmuxer(_)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:I},t instanceof ArrayBuffer?[t]:[]);else if(g){const _=g.push(t,m,l,I);te(_)?_.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(_)}}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 s=i.flush(t);te(s)?s.then(r=>{this.handleFlushResult(r,t)}).catch(r=>{this.transmuxerError(r,t,"transmuxer-interface flush error")}):this.handleFlushResult(s,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(E.ERROR,{type:Y.MEDIA_ERROR,details:D.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(i=>{this.handleTransmuxComplete(i)}),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)}}function pr(){return self.SourceBuffer||self.WebKitSourceBuffer}function gi(){if(!bt())return!1;const t=pr();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function Er(){if(!gi())return!1;const n=bt();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>n.isTypeSupported(Jt(t,"video")))||["mp4a.40.2","fLaC"].some(t=>n.isTypeSupported(Jt(t,"audio"))))}function Eo(){var n;const t=pr();return typeof(t==null||(n=t.prototype)==null?void 0:n.changeType)=="function"}const vo=100;class yo extends Ys{constructor(t,e,i){super(t,e,i,"stream-controller",W.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,r=s?s.currentTime:null;if(r===null||!B(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(s,r,W.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(E.BUFFER_CREATED,this.onBufferCreated,this),t.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(E.BUFFER_CREATED,this.onBufferCreated,this),t.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.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:s}=this;if(this.stopLoad(),this.setInterval(vo),this.level=-1,!this.startFragRequested){let r=s.startLevel;r===-1&&(s.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=s.firstAutoLevel),s.nextLoadLevel=r,this.level=s.loadLevel,this._hasEnoughToStart=!!e}i>0&&t===-1&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=k.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=k.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case k.WAITING_LEVEL:{const{levels:t,level:e}=this,i=t==null?void 0:t[e],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=k.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=k.IDLE;break}break}case k.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===k.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(e===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(i!=null&&i[r]))return;const a=i[r],o=this.getMainFwdBufferInfo();if(o===null)return;const u=this.getLevelDetails();if(u&&this._streamEnded(o,u)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(E.BUFFER_EOS,p),this.state=k.ENDED;return}if(!this.buffering)return;t.loadLevel!==r&&t.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=a.details;if(!l||this.state===k.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=k.WAITING_LEVEL,this.startFragRequested=!1;return}const d=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&ct(f)&&this.fragmentTracker.getState(f)!==ut.OK){var g;const m=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,y=l.fragments[m-1];y&&f.cc===y.cc&&(f=y,this.fragmentTracker.removeFragment(y))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){const m=this.audioOnly&&!this.altAudio?et.AUDIO:et.VIDEO,y=(m===et.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,W.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,W.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,c))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===ut.NOT_LOADED||s===ut.PARTIAL?ct(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,W.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(e!=null&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!e.paused&&t){const o=this.hls.nextLoadLevel,u=t[o],l=this.fragLastKbps;l&&this.fragCurrent?i=this.fragCurrent.duration*u.maxBitrate/(1e3*l)+1:i=0}else i=0;const a=this.getBufferedFrag(e.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const u=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,d=Math.max(a.end,u+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,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 k.KEY_LOADING:case k.FRAG_LOADING:case k.FRAG_LOADING_WAITING_RETRY:case k.PARSING:case k.PARSED:this.state=k.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio===2?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;Ft(i,"playing",this.onMediaPlaying),Ft(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(Pt(i,"playing",this.onMediaPlaying),Pt(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(E.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,s=!1;for(let r=0;r<e.levels.length;r++){const a=e.levels[r].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!Eo(),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!==k.IDLE)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=k.WAITING_LEVEL)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:r}=this,a=e.level,o=e.details,u=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${u}`);const l=e.levelInfo,d=this.fragCurrent;d&&(this.state===k.FRAG_LOADING||this.state===k.FRAG_LOADING_WAITING_RETRY)&&d.level!==e.level&&d.loader&&this.abortCurrentFrag();let h=0;if(o.live||(i=l.details)!=null&&i.live){var c;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,l.details,(c=this.levelLastLoaded)==null?void 0:c.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,h),this.hls.trigger(E.LEVEL_UPDATED,{details:o,level:a}),this.state===k.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=k.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),a=t.fragmentStart,o=t.edge,u=r>=a-e.maxFragLookUpTolerance&&r<=o;if(s!==null&&i.duration>s&&(r<s||!u)){const d=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!u&&i.readyState<4||r<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const h=q.bufferInfo(i,s,0);if(!((l=h.buffered)!=null&&l.length)){i.currentTime=s;return}if(h.start<=r){i.currentTime=s;return}const{nextStart:f}=q.bufferedInfo(h.buffered,r,0);f&&(i.currentTime=f)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const u=o.details;if(!u){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const l=o.videoCodec,d=u.PTSKnown||!u.live,h=(e=i.initSegment)==null?void 0:e.data,c=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new po(this.hls,W.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,p=g!==-1,m=new ui(i.level,i.sn,i.stats.chunkCount,r.byteLength,g,p),y=this.initPTS[i.cc];f.push(r,h,c,l,i,s,u.totalduration,d,m,y)}onAudioTrackSwitching(t,e){const i=this.hls,s=this.altAudio!==0;if(Ii(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 a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,e)}),i.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(E.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=Ii(e.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,a=!1;for(const o in i){const u=i[o];if(u.id==="main"){if(r=o,s=u,o==="video"){const l=i[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e,r=i.type===W.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===k.PARSED&&(this.state=k.IDLE);return}const o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ct(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const a=this.media;a&&(!this._hasEnoughToStart&&q.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal){this.state=k.ERROR;return}switch(e.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.MAIN,e);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===k.WAITING_LEVEL&&((i=e.context)==null?void 0:i.type)===X.LEVEL&&(this.state=k.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onFragLoadEmergencyAborted(){this.state=k.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==et.AUDIO||!this.altAudio){const i=(e===et.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,e,W.MAIN),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&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){this.log(`could not seek to ${i}, already seeking at ${e}`);return}const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),a=q.getBuffered(t),o=a.length?a.start(0):0,u=o-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||u>0&&(u<l||this.loadingParts&&u<2*((r==null?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${u} to match buffer start`),i+=u,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${o}`),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e.indexOf("mp4a.40.5")!==-1?e="mp4a.40.2":e="mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(i=>{const{hls:s}=this,r=i==null?void 0:i.frag;if(!r||this.fragContextChanged(r))return;e.fragmentError=0,this.state=k.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(E.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(i),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=t,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:u,level:l}=a,{video:d,text:h,id3:c,initSegment:f}=s,{details:g}=l,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=k.PARSING,f){const m=f.tracks;if(m){const S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,m,S,r),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:e,tracks:m})}const y=f.initPTS,T=f.timescale,v=this.initPTS[o.cc];if(B(y)&&(!v||v.baseTime!==y||v.timescale!==T)){const S=f.trackId;this.initPTS[o.cc]={baseTime:y,timescale:T,trackId:S},i.trigger(E.INIT_PTS_FOUND,{frag:o,id:e,initPTS:y,timescale:T,trackId:S})}}if(d&&g){p&&d.type==="audiovideo"&&this.logMuxedErr(o);const m=g.fragments[o.sn-1-g.startSN],y=o.sn===g.startSN,T=!m||o.cc>m.cc;if(s.independent!==!1){const{startPTS:v,endPTS:S,startDTS:A,endDTS:C}=d;if(u)u.elementaryStreams[d.type]={startPTS:v,endPTS:S,startDTS:A,endDTS:C};else if(d.firstKeyFrame&&d.independent&&r.id===1&&!T&&(this.couldBacktrack=!0),d.dropped&&d.independent){const x=this.getMainFwdBufferInfo(),R=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,b=d.firstKeyFramePTS?d.firstKeyFramePTS:v;if(!y&&R<b-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(d.type,o.start,S,o.start,C,!0)}else y&&v-(g.appliedTimelineOffset||0)>ge&&(o.gap=!0);o.setElementaryStreamInfo(d.type,v,S,A,C),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,u,r,y||T)}else if(y||T)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:m,endPTS:y,startDTS:T,endDTS:v}=p;u&&(u.elementaryStreams[et.AUDIO]={startPTS:m,endPTS:y,startDTS:T,endDTS:v}),o.setElementaryStreamInfo(et.AUDIO,m,y,T,v),this.bufferFragmentData(p,o,u,r)}if(g&&c!=null&&c.samples.length){const m={id:e,frag:o,details:g,samples:c.samples};i.trigger(E.FRAG_PARSING_METADATA,m)}if(g&&h){const m={id:e,frag:o,details:g,samples:h.samples};i.trigger(E.FRAG_PARSING_USERDATA,m)}}logMuxedErr(t){this.warn(`${ct(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==k.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:a,audiovideo:o}=e;if(r){const l=t.audioCodec;let d=fe(r.codec,l);d==="mp4a"&&(d="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");const c=r.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),l&&l!==d&&this.log(`Swapping manifest audio codec "${l}" for "${d}"`),r.levelCodec=d,r.id=W.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${d||""}/${l||""}/${r.codec}]`),delete e.audiovideo}if(a){a.levelCodec=t.videoCodec,a.id=W.MAIN;const l=a.codec;if((l==null?void 0:l.length)===4)switch(l){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";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${t.videoCodec||""}/${l}]${a.codec!==l?" 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);const u=Object.keys(e);if(u.length){if(this.hls.trigger(E.BUFFER_CODECS,e),!this.hls)return;u.forEach(l=>{const h=e[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:l,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,W.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,i=t==null?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=k.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const i=t.currentTime;if(q.isBuffered(t,i)?e=this.getAppendedFrag(i):q.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const s=this.fragPlaying,r=e.level;(!s||e.sn!==s.sn||s.level!==r)&&(this.fragPlaying=e,this.hls.trigger(E.FRAG_CHANGED,{frag:e}),(!s||s.level!==r)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return B(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(B(e)){const i=this.getLevelDetails(),s=this.currentFrag||(i?ni(null,i.fragments,e):null);if(s){const r=s.programDateTime;if(r!==null){const a=r+(e-s.start)*1e3;return new Date(a)}}}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 To extends It{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var e;if(t&&t!==((e=s.context)==null?void 0:e.frag.type))return;s.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=D.KEY_LOAD_ERROR,i,s,r){return new Lt({type:Y.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:i,networkDetails:s})}loadClear(t,e,i){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,s;const r=t.decryptdata;if(!r){const l=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,l))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Ue(r);let u=this.keyIdToKeyInfo[o];if((i=u)!=null&&i.decryptdata.key)return r.key=u.decryptdata.key,Promise.resolve({frag:t,keyInfo:u});if(this.emeController&&(s=u)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(u.decryptdata)){case"usable":case"usable-in-future":return u.keyLoadPromise.then(d=>{const{keyInfo:h}=d;return r.key=h.decryptdata.key,{frag:t,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Vt(r.keyId):""} URI: ${r.uri} from ${t.type} ${t.level}`),u=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(u,t):this.loadKeyEME(u,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(u,t);default:return Promise.reject(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var s;if(!t.decryptdata.keyId&&(s=e.initSegment)!=null&&s.data){const a=$r(e.initSegment.data);if(a.length){let o=a[0];o.some(u=>u!==0)?(this.log(`Using keyId found in init segment ${Vt(o)}`),Ht.setKeyIdForUri(t.decryptdata.uri,o)):(o=Ht.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${Vt(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!ct(e))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(t.keyLoadPromise=r.then(a=>(t.mediaKeySessionContext=a,i))).catch(a=>{throw t.keyLoadPromise=null,"data"in a&&(a.data.frag=e),a})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=i.loader,r=new s(i);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise((a,o)=>{const u={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=i.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(c,f,g,p)=>{const{frag:m,keyInfo:y}=g,T=Ue(y.decryptdata);if(!m.decryptdata||y!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(m,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));y.decryptdata.key=m.decryptdata.key=new Uint8Array(c.data),m.keyLoader=null,y.loader=null,a({frag:m,keyInfo:y})},onError:(c,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${c.code} loading key ${c.text}`),g,ft({url:u.url,data:void 0},c)))},onTimeout:(c,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(e,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(c,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(e,D.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(u,d,h)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=null,i.loader=null);const a=Ue(i.decryptdata)||s;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function Ue(n){return n.uri}function gs(n){const{type:t}=n;switch(t){case X.AUDIO_TRACK:return W.AUDIO;case X.SUBTITLE_TRACK:return W.SUBTITLE;default:return W.MAIN}}function Ge(n,t){let e=n.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class So{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_LOADING,this.onLevelLoading,this),t.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=i||s,a=new r(e);return this.loaders[t.type]=a,a}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:X.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:u}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:X.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:u})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:a,track:o}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:X.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:a,track:o}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:X.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(t,e){const i=this.loaders[X.LEVEL];if(i){const s=i.context;s&&!e.levels.some(r=>r===s.levelOrTrack)&&(i.abort(),delete this.loaders[X.LEVEL])}}load(t){var e;const i=this.hls.config;let s=this.getInternalLoader(t);if(s){const l=this.hls.logger,d=s.context;if(d&&d.levelOrTrack===t.levelOrTrack&&(d.url===t.url||d.deliveryDirectives&&!t.deliveryDirectives)){d.url===t.url?l.log(`[playlist-loader]: ignore ${t.url} ongoing request`):l.log(`[playlist-loader]: ignore ${t.url} in favor of ${d.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let r;if(t.type===X.MANIFEST?r=i.manifestLoadPolicy.default:r=at({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),B((e=t.deliveryDirectives)==null?void 0:e.part)){let l;if(t.type===X.LEVEL&&t.level!==null?l=this.hls.levels[t.level].details:t.type===X.AUDIO_TRACK&&t.id!==null?l=this.hls.audioTracks[t.id].details:t.type===X.SUBTITLE_TRACK&&t.id!==null&&(l=this.hls.subtitleTracks[t.id].details),l){const d=l.partTarget,h=l.targetduration;if(d&&h){const c=Math.max(d*3,h*.8)*1e3;r=at({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},u={onSuccess:(l,d,h,c)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=l.data;d.parsing.start=performance.now(),gt.isMediaPlaylist(g)||h.type!==X.MANIFEST?this.handleTrackOrLevelPlaylist(l,d,h,c||null,f):this.handleMasterPlaylist(l,d,h,c)},onError:(l,d,h,c)=>{this.handleNetworkError(d,h,!1,l,c)},onTimeout:(l,d,h)=>{this.handleNetworkError(d,h,!0,void 0,l)}};s.load(t,o,u)}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,s){const r=this.hls,a=t.data,o=Ge(t,i),u=gt.parseMasterPlaylist(a,o);if(u.playlistParsingError){e.parsing.end=performance.now(),this.handleManifestParsingError(t,i,u.playlistParsingError,s,e);return}const{contentSteering:l,levels:d,sessionData:h,sessionKeys:c,startTimeOffset:f,variableList:g}=u;this.variableList=g,d.forEach(T=>{const{unknownCodecs:v}=T;if(v){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:A,videoCodec:C}=T;for(let x=v.length;x--;){const R=v[x];Zt(R,"audio",S)?(T.audioCodec=A=A?`${A},${R}`:R,Kt.audio[A.substring(0,4)]=2,v.splice(x,1)):Zt(R,"video",S)&&(T.videoCodec=C=C?`${C},${R}`:R,Kt.video[C.substring(0,4)]=2,v.splice(x,1))}}});const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":y}=gt.parseMasterPlaylistMedia(a,o,u);p.length&&!p.some(v=>!v.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new tt({}),bitrate:0,url:""})),r.trigger(E.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:m,captions:y,contentSteering:l,url:o,stats:e,networkDetails:s,sessionData:h,sessionKeys:c,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,i,s,r){const a=this.hls,{id:o,level:u,type:l}=i,d=Ge(t,i),h=B(u)?u:B(o)?o:0,c=gs(i),f=gt.parseLevelPlaylist(t.data,d,h,c,0,this.variableList);if(l===X.MANIFEST){const g={attrs:new tt({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=e.loading.start+$s(f,0),a.trigger(E.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:d,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,t,e,i,s,r)}handleManifestParsingError(t,e,i,s,r){this.hls.trigger(E.ERROR,{type:Y.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:e.type===X.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:r})}handleNetworkError(t,e,i=!1,s,r){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===X.LEVEL?a+=`: ${t.level} id: ${t.id}`:(t.type===X.AUDIO_TRACK||t.type===X.SUBTITLE_TRACK)&&(a+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let u=D.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case X.MANIFEST:u=i?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,l=!0;break;case X.LEVEL:u=i?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,l=!1;break;case X.AUDIO_TRACK:u=i?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case X.SUBTITLE_TRACK:u=i?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,l=!1;break}d&&this.resetInternalLoader(t.type);const h={type:Y.NETWORK_ERROR,details:u,fatal:l,url:t.url,loader:d,context:t,error:o,networkDetails:e,stats:r};if(s){const c=(e==null?void 0:e.url)||t.url;h.response=ft({url:c,data:void 0},s)}this.hls.trigger(E.ERROR,h)}handlePlaylistLoaded(t,e,i,s,r,a){const o=this.hls,{type:u,level:l,levelOrTrack:d,id:h,groupId:c,deliveryDirectives:f}=s,g=Ge(e,s),p=gs(s);let m=typeof s.level=="number"&&p===W.MAIN?l:void 0;const y=t.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(E.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:e,context:s,level:m,parent:p,networkDetails:r,stats:i});return}t.playlistParsingError=null}if(!t.fragments.length){const T=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:e,context:s,level:m,parent:p,networkDetails:r,stats:i});return}switch(t.live&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),u){case X.MANIFEST:case X.LEVEL:if(m){if(!d)m=0;else if(d!==o.levels[m]){const T=o.levels.indexOf(d);T>-1&&(m=T)}}o.trigger(E.LEVEL_LOADED,{details:t,levelInfo:d||o.levels[0],level:m||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:u===X.MANIFEST});break;case X.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:f});break;case X.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:f});break}}}const xo={supported:!0,powerEfficient:!0,smooth:!0},Lo={supported:!1,smooth:!1,powerEfficient:!1},Ao={supported:!0,configurations:[],decodingInfoResults:[xo]};function Ro(n,t){return{supported:!1,configurations:t,decodingInfoResults:[Lo],error:n}}function bo(n,t,e,i={}){const s=n.videoCodec;if(!s&&!n.audioCodec||!e)return Promise.resolve(Ao);const r=[],a=Io(n),o=a.length,u=Do(n,t,o>0),l=u.length;for(let d=o||1*l||1;d--;){const h={type:"media-source"};if(o&&(h.video=a[d%o]),l){h.audio=u[d%l];const c=h.audio.bitrate;h.video&&c&&(h.video.bitrate-=c)}r.push(h)}if(s){const d=navigator.userAgent;if(s.split(",").some(h=>ei(h))&&bs())return Promise.resolve(Ro(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),r))}return Promise.all(r.map(d=>{const h=_o(d);return i[h]||(i[h]=e.decodingInfo(d))})).then(d=>({supported:!d.some(h=>!h.supported),configurations:r,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:r,decodingInfoResults:[],error:d}))}function Io(n){var t;const e=(t=n.videoCodec)==null?void 0:t.split(","),i=vr(n),s=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return e?e.map(u=>{const l={contentType:Jt(zr(u),"video"),width:s,height:r,bitrate:i,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function Do(n,t,e){var i;const s=(i=n.audioCodec)==null?void 0:i.split(","),r=vr(n);return s&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var u;const l=o?(u=t.groups[o])==null?void 0:u.tracks:null;return l?l.reduce((d,h)=>{if(h.groupId===o){const c=parseFloat(h.channels||"");s.forEach(f=>{const g={contentType:Jt(f,"audio"),bitrate:e?Co(f,r):r};c&&(g.channels=""+c),d.push(g)})}return d},a):a},[]):[]}function Co(n,t){if(t<=1)return 1;let e=128e3;return n==="ec-3"?e=768e3:n==="ac-3"&&(e=64e4),Math.min(t/2,e)}function vr(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function _o(n){let t="";const{audio:e,video:i}=n;if(i){const s=He(i.contentType);t+=`${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(e){const s=He(e.contentType);t+=`${i?"_":""}${s}_c${e.channels}`}return t}class Rt{static get version(){return ee}static isMSESupported(){return gi()}static isSupported(){return Er()}static getMediaSource(){return bt()}static get Events(){return E}static get MetadataSchema(){return dt}static get ErrorTypes(){return Y}static get ErrorDetails(){return D}static get DefaultConfig(){return Rt.defaultConfig?Rt.defaultConfig:qa}static set DefaultConfig(t){Rt.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 Zs,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=Ir(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=Xa(Rt.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Qa(i,e);const{abrController:s,bufferController:r,capLevelController:a,errorController:o,fpsController:u}=i,l=new o(this),d=this.abrController=new s(this),h=new Rn(this),c=i.interstitialsController,f=c?this.interstitialsController=new c(this,Rt):null,g=this.bufferController=new r(this,h),p=this.capLevelController=new a(this),m=new u(this),y=new So(this),T=i.contentSteeringController,v=T?new T(this):null,S=this.levelController=new ho(this,v),A=new lo(this),C=new To(this.config,this.logger),x=this.streamController=new yo(this,h,C),R=this.gapController=new eo(this,h);p.setStreamController(x),m.setStreamController(x);const b=[y,S,x];f&&b.splice(1,0,f),v&&b.splice(1,0,v),this.networkControllers=b;const I=[d,g,R,p,m,A,h];this.audioTrackController=this.createController(i.audioTrackController,b);const _=i.audioStreamController;_&&b.push(this.audioStreamController=new _(this,h,C)),this.subtitleTrackController=this.createController(i.subtitleTrackController,b);const w=i.subtitleStreamController;w&&b.push(this.subtititleStreamController=new w(this,h,C)),this.createController(i.timelineController,I),C.emeController=this.emeController=this.createController(i.emeController,I),this.cmcdController=this.createController(i.cmcdController,I),this.latencyController=this.createController(uo,I),this.coreComponents=I,b.push(l);const $=l.onErrorOut;typeof $=="function"&&this.on(E.ERROR,$,l),this.on(E.MANIFEST_LOADED,y.onManifestLoaded,y)}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,s){this._emitter.off(t,e,i,s)}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(i){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=t===E.ERROR;this.trigger(E.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:s,event:t,error:i}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.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 r=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(E.ERROR,{type:Y.OTHER_ERROR,details:D.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(E.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,s=this._url=Je.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(E.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={[W.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[W.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[W.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=t==null?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=Kn()),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 t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(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){Xr(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}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 s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(e===-1&&t!=null&&t.length?s=t.length-1:s=e,i)for(let r=s;r--;){const a=t[r].attrs["HDCP-LEVEL"];if(a&&a<=i)return r}return s}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((e=this.audioTrackController)==null?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return((e=this.subtitleTrackController)==null?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:!1}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!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){const i=Is(e);return bo(t,i,navigator.mediaCapabilities)}}Rt.defaultConfig=void 0;var Po=wt.KeySystemFormats,ko=wt.KeySystems,Oo=wt.SubtitleStreamController,Fo=wt.TimelineController,wo=wt.requestMediaKeySystemAccess;exports.AbrController=Ds;exports.AttrList=tt;exports.AudioStreamController=Mt;exports.AudioTrackController=Mt;exports.BasePlaylistController=Ks;exports.BaseSegment=ti;exports.BaseStreamController=Ys;exports.BufferController=qs;exports.CMCDController=Mt;exports.CapLevelController=Ae;exports.ChunkMetadata=ui;exports.ContentSteeringController=zs;exports.Cues=Mt;exports.DateRange=oi;exports.EMEController=Mt;exports.ErrorActionFlags=lt;exports.ErrorController=ks;exports.ErrorDetails=D;exports.ErrorTypes=Y;exports.Events=E;exports.FPSController=Qs;exports.FetchLoader=Xe;exports.Fragment=ce;exports.Hls=Rt;exports.HlsSkip=qt;exports.HlsUrlParameters=Ye;exports.KeySystemFormats=Po;exports.KeySystems=ko;exports.Level=ri;exports.LevelDetails=Os;exports.LevelKey=Ht;exports.LoadStats=Le;exports.M3U8Parser=gt;exports.MetadataSchema=dt;exports.NetworkErrorAction=st;exports.Part=Es;exports.PlaylistLevelType=W;exports.SubtitleStreamController=Oo;exports.SubtitleTrackController=Mt;exports.TimelineController=Fo;exports.XhrLoader=fi;exports.default=Rt;exports.fetchSupported=mr;exports.getMediaSource=bt;exports.isMSESupported=gi;exports.isSupported=Er;exports.requestMediaKeySystemAccess=wo;