hr-design-system-handlebars 1.114.138 → 1.114.140

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 (106) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/assets/index.css +6 -10
  3. package/dist/assets/js/components/mediaplayer/ardPlayerLoader.subfeature.js +2 -2
  4. package/dist/assets/vendor/ardplayer/{ardplayer-SANDLibrary.6faa2a2b.chunk.js → ardplayer-SANDLibrary.1a644373.chunk.js} +17 -72
  5. package/dist/assets/vendor/ardplayer/ardplayer-hr-7.2.0.07145e1b.js +1 -0
  6. package/dist/assets/vendor/ardplayer/ardplayer-hr-7.2.0.bdf782df.css +1 -0
  7. package/dist/assets/vendor/ardplayer/ardplayer-libimsc.34d59351.chunk.js +12 -0
  8. package/dist/assets/vendor/ardplayer/ardplayer-pluginchromecast.017a470e.chunk.js +1 -0
  9. package/dist/assets/vendor/ardplayer/ardplayer-plugindash.6abc107d.chunk.js +10 -0
  10. package/dist/assets/vendor/ardplayer/ardplayer-pluginhls.e7b33d74.chunk.js +1 -0
  11. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmla.7a21b373.chunk.js +1 -0
  12. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmlv.8e08609e.chunk.js +1 -0
  13. package/dist/assets/vendor/ardplayer/assets/47bf64197ce0a282ef55-ardplayer-audio.woff +0 -0
  14. package/dist/assets/vendor/ardplayer/assets/553e21224d0386ee58f0-ardplayer.woff +0 -0
  15. package/dist/assets/vendor/ardplayer/assets/img/sr-f5ae5aae.svg +1 -0
  16. package/dist/views/components/content/copytext/components/media/media_figure.hbs +3 -3
  17. package/dist/views/components/teaser/components/teaser_media_player.hbs +1 -1
  18. package/dist/views_static/components/content/copytext/components/media/media_figure.hbs +3 -3
  19. package/dist/views_static/components/teaser/components/teaser_media_player.hbs +1 -1
  20. package/package.json +1 -1
  21. package/src/assets/fixtures/audio/audios.inc.json +8 -8
  22. package/src/assets/fixtures/page/podcast/podcast_player_episode.json +4 -4
  23. package/src/assets/fixtures/video/videos.inc.json +8 -8
  24. package/src/assets/vendor/ardplayer/{ardplayer-SANDLibrary.6faa2a2b.chunk.js → ardplayer-SANDLibrary.1a644373.chunk.js} +17 -72
  25. package/src/assets/vendor/ardplayer/ardplayer-hr-7.2.0.07145e1b.js +1 -0
  26. package/src/assets/vendor/ardplayer/ardplayer-hr-7.2.0.bdf782df.css +1 -0
  27. package/src/assets/vendor/ardplayer/ardplayer-libimsc.34d59351.chunk.js +12 -0
  28. package/src/assets/vendor/ardplayer/ardplayer-pluginchromecast.017a470e.chunk.js +1 -0
  29. package/src/assets/vendor/ardplayer/ardplayer-plugindash.6abc107d.chunk.js +10 -0
  30. package/src/assets/vendor/ardplayer/ardplayer-pluginhls.e7b33d74.chunk.js +1 -0
  31. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmla.7a21b373.chunk.js +1 -0
  32. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmlv.8e08609e.chunk.js +1 -0
  33. package/src/assets/vendor/ardplayer/assets/47bf64197ce0a282ef55-ardplayer-audio.woff +0 -0
  34. package/src/assets/vendor/ardplayer/assets/553e21224d0386ee58f0-ardplayer.woff +0 -0
  35. package/src/assets/vendor/ardplayer/assets/img/dolby_atmos_horizontal-469f0a42.png +0 -0
  36. package/src/assets/vendor/ardplayer/assets/img/sr-f5ae5aae.svg +1 -0
  37. package/src/assets/vendor/ardplayer/schema/MediaCollection.v1.json +36 -1
  38. package/src/stories/views/components/content/copytext/components/media/media_figure.hbs +3 -3
  39. package/src/stories/views/components/content/copytext/fixtures/copytext_audio-livestream.json +8 -8
  40. package/src/stories/views/components/content/copytext/fixtures/copytext_audio.json +1 -1
  41. package/src/stories/views/components/content/copytext/fixtures/copytext_audio_livestream.json +1 -1
  42. package/src/stories/views/components/content/copytext/fixtures/copytext_image.json +1 -1
  43. package/src/stories/views/components/content/copytext/fixtures/copytext_livestream.json +1 -1
  44. package/src/stories/views/components/content/copytext/fixtures/copytext_media_components.json +1 -1
  45. package/src/stories/views/components/content/copytext/fixtures/copytext_non_media_components.json +1 -1
  46. package/src/stories/views/components/content/copytext/fixtures/copytext_podcastepisode.json +1 -1
  47. package/src/stories/views/components/content/copytext/fixtures/copytext_video.json +1 -1
  48. package/src/stories/views/components/content/copytext/fixtures/copytext_video_vertical.json +1 -1
  49. package/src/stories/views/components/mediaplayer/ardPlayerLoader.subfeature.js +2 -2
  50. package/src/stories/views/components/mediaplayer/fixtures/mediaplayer.json +1 -1
  51. package/src/stories/views/components/mediaplayer/fixtures/mediaplayer_snapshots.json +1 -1
  52. package/src/stories/views/components/page/fixtures/page.json +1 -1
  53. package/src/stories/views/components/page/podcast/fixtures/podcast_player_episode.json +1 -1
  54. package/src/stories/views/components/page/podcast/fixtures/podcast_player_playlist.json +1 -1
  55. package/src/stories/views/components/page/story/fixtures/story.json +1 -1
  56. package/src/stories/views/components/page/story/fixtures/story_with_audio.json +1 -1
  57. package/src/stories/views/components/page/story/fixtures/story_with_label.json +1 -1
  58. package/src/stories/views/components/page/story/fixtures/story_with_livestream.json +1 -1
  59. package/src/stories/views/components/page/story/fixtures/story_with_square_image.json +1 -1
  60. package/src/stories/views/components/page/story/fixtures/story_with_video.json +1 -1
  61. package/src/stories/views/components/pagination/fixtures/page_pagination.json +1 -1
  62. package/src/stories/views/components/teaser/components/teaser_media_player.hbs +1 -1
  63. package/src/stories/views/components/teaser/fixtures/teaser_alternative_av.json +1 -1
  64. package/src/stories/views/components/teaser/fixtures/teaser_cluster.json +1 -1
  65. package/src/stories/views/components/teaser/fixtures/teaser_group_100.json +1 -1
  66. package/src/stories/views/components/teaser/fixtures/teaser_group_100_highlight.json +1 -1
  67. package/src/stories/views/components/teaser/fixtures/teaser_group_100_highlight_2.json +1 -1
  68. package/src/stories/views/components/teaser/fixtures/teaser_group_related_content_100.json +1 -1
  69. package/src/stories/views/components/teaser/fixtures/teaser_index.json +1 -1
  70. package/src/stories/views/components/teaser/fixtures/teaser_podcast.json +1 -1
  71. package/src/stories/views/components/teaser/fixtures/teaser_podcast_50.json +1 -1
  72. package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist.json +1 -1
  73. package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist_50.json +1 -1
  74. package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist_filter.json +1 -1
  75. package/src/stories/views/components/teaser/fixtures/teaser_standard_av.json +1 -1
  76. package/src/stories/views/components/teaser/fixtures/teaser_tabbox.json +1 -1
  77. package/src/stories/views/components/teaser/fixtures/teaser_ticker_alternative.json +1 -1
  78. package/src/stories/views/components/teaser/fixtures/teaser_ticker_standard.json +1 -1
  79. package/src/stories/views/components/teaser/fixtures/teaser_vertical_video.json +1 -1
  80. package/src/stories/views/components/voting/fixtures/voting.json +1 -1
  81. package/src/stories/views/components/voting/fixtures/voting_media_audio_horizontal.json +1 -1
  82. package/src/stories/views/components/voting/fixtures/voting_media_audio_vertical.json +1 -1
  83. package/src/stories/views/components/voting/fixtures/voting_media_video_horizontal.json +1 -1
  84. package/src/stories/views/components/voting/fixtures/voting_media_video_vertical.json +1 -1
  85. package/dist/assets/vendor/ardplayer/ardplayer-hr-6.9.2.3be63dd6.css +0 -1
  86. package/dist/assets/vendor/ardplayer/ardplayer-hr-6.9.2.930e5d37.js +0 -1
  87. package/dist/assets/vendor/ardplayer/ardplayer-libimsc.94ff92e7.chunk.js +0 -12
  88. package/dist/assets/vendor/ardplayer/ardplayer-pluginchromecast.064b468f.chunk.js +0 -1
  89. package/dist/assets/vendor/ardplayer/ardplayer-plugindash.f3029c65.chunk.js +0 -10
  90. package/dist/assets/vendor/ardplayer/ardplayer-pluginhls.d2363d5c.chunk.js +0 -1
  91. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmla.fc2a72c0.chunk.js +0 -1
  92. package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmlv.90153612.chunk.js +0 -1
  93. package/dist/assets/vendor/ardplayer/assets/c760ddea7c5679abc52d-ardplayer.woff +0 -0
  94. package/dist/assets/vendor/ardplayer/assets/d45e654a921039ff64c9-ardplayer-audio.woff +0 -0
  95. package/dist/assets/vendor/ardplayer/assets/img/sr-63f113c4.svg +0 -1
  96. package/src/assets/vendor/ardplayer/ardplayer-hr-6.9.2.3be63dd6.css +0 -1
  97. package/src/assets/vendor/ardplayer/ardplayer-hr-6.9.2.930e5d37.js +0 -1
  98. package/src/assets/vendor/ardplayer/ardplayer-libimsc.94ff92e7.chunk.js +0 -12
  99. package/src/assets/vendor/ardplayer/ardplayer-pluginchromecast.064b468f.chunk.js +0 -1
  100. package/src/assets/vendor/ardplayer/ardplayer-plugindash.f3029c65.chunk.js +0 -10
  101. package/src/assets/vendor/ardplayer/ardplayer-pluginhls.d2363d5c.chunk.js +0 -1
  102. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmla.fc2a72c0.chunk.js +0 -1
  103. package/src/assets/vendor/ardplayer/ardplayer-pluginhtmlv.90153612.chunk.js +0 -1
  104. package/src/assets/vendor/ardplayer/assets/c760ddea7c5679abc52d-ardplayer.woff +0 -0
  105. package/src/assets/vendor/ardplayer/assets/d45e654a921039ff64c9-ardplayer-audio.woff +0 -0
  106. package/src/assets/vendor/ardplayer/assets/img/sr-63f113c4.svg +0 -1
@@ -0,0 +1 @@
1
+ (globalThis.webpackChunkardplayer=globalThis.webpackChunkardplayer||[]).push([[965],{96789:(e,t,i)=>{"use strict";i.d(t,{F:()=>v});var r=i(39906),s=i(36185),n=i(55762),a=i(58732),o=i(20738),l=i(15867),h=i.n(l),d=i(78940),u=i(5677),c=function(e,t,i){for(var r=arguments.length>2,s=0;s<t.length;s++)i=r?t[s].call(e,i):t[s].call(e);return r?i:void 0},f=function(e,t,i,r,s,n){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?r.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(e){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(e||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},g=function(e,t,i){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:i?"".concat(i," ",t):t})},m=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},p=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};let v=(()=>{var e,t,i,l,v,y,E,T,S,A,L,R,I,b,D,k,_,P,C,w;let x,O,M,F,N,U,B,G=[d.JW],$=[],K=[];O=class{get executionContextProvider(){var e;return null!==(e=this.player)&&void 0!==e?e:null}get model(){return this.player.model}get pc(){return this.model.playerConfig}get mc(){return this.model.mediaCollection}get vc(){return this.player.viewCtrl}get videoScale(){return this.model.videoScaleMode}set videoScale(e){this.model.videoScaleMode!==e&&(this.model.videoScaleMode=e,this.applyVideoScale(e))}set remotePlaybackDevice(t){m(this,e,"f")!==t&&(this.player.loop.dispatchEvent(r.a.REMOTE_PLAYBACK_CHANGED,(0,u.cl)(t)?{isRemote:!1}:{isRemote:!0,device:t}),this.player.isLive&&!this.player.isAudio&&this.vc.setLiveInitialBufferState()),p(this,e,t,"f")}get remotePlaybackDevice(){return m(this,e,"f")}get isRemotePlayback(){return!(0,u.cl)(m(this,e,"f"))}get isPlayingSpatialAudio(){return!1}get playbackStalled(){return m(this,v,"f")}get __cumulativeDrift(){return m(this,I,"f")}constructor(s,a){this.minDisplayedLiveOffset=(c(this,K),7),this.subtitleListeners=[],this.audioTrackListeners=[],this.audioTracks=[],this.audioTrack=null,e.set(this,null),t.set(this,0),i.set(this,0),l.set(this,!1),v.set(this,!1),y.set(this,0),E.set(this,!1),T.set(this,!1),this._duration=0,this._dvrModeEnabled=!1,S.set(this,-1),A.set(this,-1),L.set(this,0),R.set(this,0),I.set(this,0),this.isAtEnd=!1,this._useAndroidInitialSeekFallback=!1,b.set(this,-1),D.set(this,-1),k.set(this,!1),this._ready=!1,this._pendingSeek=0,_.set(this,-1),P.set(this,!1),this._dvrEnabled=!1,this._dvrIsLive=!1,this._dvrWindow=0,this.expectedAudios=[],C.set(this,!1),this.pinnedDvrSync=null,this.dvrWindowUnstable=!1,this[w]=this.getClassTypeString(),this.player=s,this.mediaElement=a,this.applyVideoScale(this.videoScale),this.player.loop.dispatchEvent(r.a.EVENT_INIT,{}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"init"}),this.emap=new(h()),this.addEventListeners(),n.x.for(this.player).storageListeners.add(this),a instanceof HTMLMediaElement&&(a.textTracks.onaddtrack=e=>{this.onTextTracksChanged(e)},a.textTracks.onremovetrack=e=>{this.onTextTracksChanged(e)}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"ready"})}debugString(){return"none"}debugQualityLevel(){return[-1,1]}debugResolution(){return this.isRemotePlayback||this.player.isAudio?"-":`${this.mediaElement.videoWidth}x${this.mediaElement.videoHeight}`}debugFrames(){if(this.mediaElement instanceof HTMLVideoElement){const e=this.mediaElement.getVideoPlaybackQuality();return`${e.droppedVideoFrames} dropped of ${e.totalVideoFrames}`}return"no video info available"}get subQualities(){return this.error("using base implementation for subQuality listing!"),[{level:-1,label:"Auto",width:-1,height:-1}]}selectSubQuality(e){this.error("using base implementation for subQuality selection!")}get currentSubQuality(){return this.error("using base implementation for currentSubQuality!"),-1}log(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.player.console.log(`[${this.getClassTypeString()}]`,...t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.player.console.info(`[${this.getClassTypeString()}]`,...t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.player.console.warn(`[${this.getClassTypeString()}]`,...t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.player.console.error(`[${this.getClassTypeString()}]`,...t)}onTextTracksChanged(e){this.subtitleListeners.forEach((t=>{t.onTextTracksChanged(e)}))}addSubtitleListener(e){this.subtitleListeners.includes(e)||this.subtitleListeners.push(e)}removeSubtitleListener(e){const t=this.subtitleListeners.indexOf(e);-1!==t&&(this.subtitleListeners=this.subtitleListeners.splice(t,1))}onAudioTracksChanged(){1===this.audioTracks.length&&1===this.expectedAudios.length&&"audio-description"===this.expectedAudios[0].kind&&(this.audioTracks[0].isAudioDescription=!0),this.player.loop.dispatchEvent(r.a.AUDIO_TRACK_LIST_CHANGED,{audioTracks:this.audioTracks}),this.audioTrackListeners.forEach((e=>{e.onAudioTracksChanged(this.audioTracks)}))}addAudioTrackListener(e){this.audioTrackListeners.includes(e)||this.audioTrackListeners.push(e)}removeAudioTrackListener(e){const t=this.audioTrackListeners.indexOf(e);-1!==t&&(this.audioTrackListeners=this.audioTrackListeners.splice(t,1))}addEventListeners(){this.emap.map(this.mediaElement,"loadstart",this.onLoadStart,this),this.emap.map(this.mediaElement,"canplay",this.onCanPlay,this),this.emap.map(this.mediaElement,"play",this.onPlay,this),this.emap.map(this.mediaElement,"pause",this.onPause,this),this.emap.map(this.mediaElement,"error",this.onError,this),this.emap.map(this.mediaElement,"waiting",this.onWaiting,this),this.emap.map(this.mediaElement,"ended",this.onEnded,this),this.emap.map(this.mediaElement,"timeupdate",this.onTimeUpdate,this),this.emap.map(this.mediaElement,"seeking",this.onSeeking,this),this.emap.map(this.mediaElement,"seeked",this.onSeekEnd,this),this.emap.map(this.mediaElement,"loadedmetadata",this.onLoadedMetadata,this),this.emap.map(this.mediaElement,"loadeddata",this.onLoadedData,this),this.emap.map(this.mediaElement,"durationchange",this.onDurationChange,this),this.emap.map(this.mediaElement,"progress",this.onProgress,this),this.emap.map(this.mediaElement,"stalled",this.onStalled,this),this.emap.map(this.mediaElement,"volumechange",this.onLocalVolumeChange,this)}onLoadStart(){var e,t;s.O.isAndroidDevice&&(null!==(t=null===(e=this.mediaElement)||void 0===e?void 0:e.currentSrc)&&void 0!==t?t:"").toLowerCase().indexOf(".m3u8")>0&&(this._useAndroidInitialSeekFallback=!0)}onCanPlay(){this.mediaElement instanceof HTMLMediaElement&&!(this.mediaElement.readyState>=this.mediaElement.HAVE_FUTURE_DATA)||this.bufferingEventHandler(!1),p(this,v,!1,"f"),this.setPlaybackRate(this.model.playbackRate)}onPlay(){this.startTicker(),this.playEventHandler(),this.bufferingEventHandler(!1),this.vc.setOutDelayed()}onPause(e){this.pauseEventHandler(e,!isNaN(this.mediaElement.currentTime)&&!isNaN(this.mediaElement.duration)&&this.mediaElement.currentTime>=this.mediaElement.duration&&("ios"!==s.O.platform||!this.player.isLive))}onError(e){this.handleError(e)}onWaiting(e){this.mediaElement instanceof HTMLMediaElement&&this.bufferingEventHandler(this.mediaElement.readyState<this.mediaElement.HAVE_FUTURE_DATA),p(this,v,!0,"f")}onEnded(e){this.stopTicker(),this.mediaElement.pause(),this.endEventHandler(e),this.onTimeChange(this._duration,0)}onTimeUpdate(e){if(this.onProgress(null),this.updateTicker(),this.isSeeking()&&!m(this,k,"f")){const e=this.getCurrentTime();Math.abs(m(this,D,"f")-e)<Math.abs(m(this,b,"f")-e)&&this.onSeekEnd(null)}}onSeeking(){p(this,k,!0,"f"),m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_START,{from:m(this,b,"f"),to:m(this,D,"f")}),this.bufferingEventHandler(!0)}onSeekEnd(e){this.isSeeking()&&(m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_END,{lastPosition:m(this,b,"f"),position:this.getCurrentTime()}),p(this,E,!1,"f"),p(this,b,-1,"f"),p(this,D,-1,"f"),m(this,k,"f")||this.bufferingEventHandler(!1),p(this,k,!1,"f"),this.bufferingEventHandler(!1),this.player.clearExecutionContext(r.a.EVENT_SEEK_START,r.a.EVENT_SEEK_START_INTENT,r.a.EVENT_SEEK_END,r.a.EVENT_BUFFERING))}isSeeking(){return m(this,k,"f")||-1!==m(this,D,"f")&&-1!==m(this,b,"f")}onLoadedMetadata(){this._ready=!0,this.evalInitialSeek()}onLoadedData(){this.evalInitialSeek(),this.onProgress(null)}onDurationChange(e){const t=this.mediaElement.duration;isNaN(t)||(this._duration=t),this._ready=!0,this.onProgress(null)}onLocalVolumeChange(e){const t=this.mediaElement.muted,i=this.mediaElement.volume;this.getVolume()/100===i&&m(this,C,"f")===t||(this.player.setMutedInternal(t,!0,!1,!0,!0),this.player.setVolumeInternal(100*i,!0,!1,!1))}onProgress(e){var t;if(!this.mediaElement||"waiting"===(null==e?void 0:e.type)&&this.isSeeking())return;const i=this.getCurrentTime(),r=this.getDuration();let s=-1;const n=null===(t=this.mediaElement)||void 0===t?void 0:t.buffered;if(n)for(let e=0;e<n.length;e++)if(n.start(e)<=i&&n.end(e)>=i){s=n.end(e);break}if(-1===s)return;const a=Math.round(s/r*100);this.bufferProgressHandler(a)}onStalled(e){this.onProgress(e)}onSourceError(e){this.stopTicker(),this.handleError(e)}onTimeChange(e,t){this.model.duration!==e&&e>0&&this.model.duration>0&&null!=this.pinnedDvrSync&&(this.pinnedDvrSync=null,this.dvrWindowUnstable=!0,this.warn("DVR window unstable, disabled sync info pinning")),this.updateDuration(e),this.updateTime(Math.max(t,0))}bufferingEventHandler(e){this.onProgress(null),e&&!this.isAtEnd?this.vc.showBufferingIndicator():this.vc.hideBufferingIndicator(),e!==m(this,l,"f")&&(p(this,l,e,"f"),this.player.loop.dispatchEvent(r.a.EVENT_BUFFERING,{isBuffering:e}))}bufferProgressHandler(e){this.vc.timeline.setBufferProgress(e),p(this,y,e,"f")}playEventHandler(){var e;if(this.stopOtherPlayingPlayers(),this.model.playstate=o.R.PLAYSTATE_PLAYING,this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"play"}),this.isAtEnd){const t=this.getCurrentTimeWithoutSeek();null===(e=this.executionContextProvider)||void 0===e||e.preserveExecutionContext(r.a.EVENT_INITIAL_FRAME,500);const i=e=>{e.currentTime!==t&&(this.player.loop.dispatchEvent(r.a.EVENT_INITIAL_FRAME,{}),m(this,l,"f")||this.bufferingEventHandler(!1))},s=()=>{this.player.loop.removeEventListener(r.a.EVENT_UPDATE_STREAM_TIME,i),this.player.loop.removeEventListener(r.a.EVENT_INITIAL_FRAME,s)};this.player.loop.addEventListener(r.a.EVENT_UPDATE_STREAM_TIME,i),this.player.loop.addEventListener(r.a.EVENT_INITIAL_FRAME,s)}this.isAtEnd=!1,this.player.pixelController.replayTrigger(),this.player.pixelController.initialPlayTrigger(),this.player.loop.dispatchEvent(r.a.EVENT_PLAY_STREAM,{})}pauseEventHandler(e,t){void 0===t&&(t=!1),this.model.playstate=o.R.PLAYSTATE_PAUSED,this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"pause"}),this.player.loop.dispatchEvent(r.a.EVENT_PAUSE_STREAM,{ended:t})}endEventHandler(e){this.isAtEnd=!0,this.jumpToStart(),this.player.pixelController.triggerPixel(a.k.CLIP_ENDED),this.pauseEventHandler(e,!0),this.vc.hidePosterFrame(),this.mc.isLive||this.vc.showPlayAgain(),this.vc.hideBufferingIndicator(),"web"===s.O.platform&&this.player.setFullscreenInternal(!1),this.player.pixelController&&(this.player.pixelController._isReplay=!0),this.player.loop.dispatchEvent(r.a.EVENT_END_STREAM,{})}evalInitialSeek(){if(this._pendingSeek>0){if(this.canSeek()){p(this,E,!0,"f");const e=this._pendingSeek;this._pendingSeek=0,this.setCurrentTime(e,m(this,T,"f"),!1,!0),m(this,T,"f")||this.play()}}else m(this,T,"f")||this.play()}updateDuration(e){this.model.duration!==e&&(this.model.duration=e,this.player.loop.dispatchEvent(r.a.EVENT_UPDATE_STREAM_DURATION,{duration:e}))}restartMedia(){this.jumpToStart(),this.play()}resetStartAndEndTime(){this.pc.generic.vodStartSeconds=0,this.pc.generic.vodEndSeconds=0}updateTime(e){this.model.time=e,this.vc.updateTime(e),this.vc.updateTimeline(e,this.model.duration);const s=Date.now();if(s>=m(this,i,"f")+1e3){p(this,i,s,"f");let t=0;const r=Math.round(this.model.duration),n=Math.round(e);this.vc._dvrEnabledAndRequested&&!this.vc._dvrIsLive&&(t=Math.min(Math.round(r-e),r)),this.player.pixelController.triggerCustomPixel(a.k.SUPER_PLAYHEAD_POSITION,!1,{currentTime:n,duration:r,dvrRelativeTime:-t})}const l=this.pc.generic.vodStartSeconds,h=this.pc.generic.vodEndSeconds;if(l>0&&e<l){const i=Math.round(e);Math.abs(m(this,t,"f")-i)>3&&(this.setCurrentTime(l,!1,!1,!0),p(this,t,i,"f"))}else h>0&&e>h&&(this.setCurrentTime(l,!1,!1,!0),this.pause());this.player.loop.dispatchEvent(r.a.EVENT_UPDATE_STREAM_TIME,{currentTime:e}),window.parent!==window&&n.x.AVAILABLE&&this.model.playstate===o.R.PLAYSTATE_PLAYING&&n.x.get(n.x.SUFFIX_GLOBAL,n.x.CURRENT_PLAYERID,!0)!==this.player.getId()&&this.pause()}removeEventListeners(){this.emap.all()}dispose(){this.log("dispose()"),this.removeEventListeners(),n.x.for(this.player).storageListeners.delete(this),this.mediaElement instanceof HTMLMediaElement&&(this.mediaElement.textTracks.onaddtrack=null,this.mediaElement.textTracks.onremovetrack=null),this.mediaElement.pause(),this.subtitleListeners=[],this.audioTrackListeners=[],this.stopTicker(),this.player.loop.dispatchEvent(r.a.EVENT_STOP_STREAM,{}),m(this,T,"f")&&0===this.model.playstate&&(this.model.playstate=3),this.audioTracks=[],this.audioTrack=null}stopOtherPlayingPlayers(){n.x.add(n.x.SUFFIX_GLOBAL,n.x.CURRENT_PLAYERID,this.player.getId(),!0,!0),o.R.autoPlayerAlreadyActive=this.player.getId()}onStorageValueChanged(e,t){e===n.x.CURRENT_PLAYERID&&"string"==typeof t&&this.isPlaying()&&t!==this.player.getId()&&this.pause()}loadStream(e){if(p(this,T,1===this.model.playstate||3===this.model.playstate,"f"),this.model.playstate=o.R.PLAYSTATE_UNSPECIFIED,m(this,T,"f")||this.stopOtherPlayingPlayers(),this.player.preserveExecutionContext(r.a.EVENT_LOAD_STREAM,5e3),this.player.loop.dispatchEvent(r.a.EVENT_LOAD_STREAM,{mediaStream:e}),this._pendingSeek=this.model.time,0===this._pendingSeek&&!this.mc.isLive){let e=this.pc.generic.vodInitialPlayheadSeconds;e<=0&&(e=this.pc.generic.vodStartSeconds),this._pendingSeek=e}if(this.mediaElement instanceof HTMLMediaElement)for(;this.mediaElement.children.length>0;)this.mediaElement.removeChild(this.mediaElement.children[0]);if(this.expectedAudios=e.audios,this.addSource(e),!s.O.isEmbedded){const e=n.x.volume(this.player),t=this.pc.generic.isMuted||n.x.muted(this.player);this.player.setVolumeInternal(e,!1,!0,!0),this.player.setMutedInternal(t,!1,!0,!1,!1)}if(m(this,T,"f")){const e=()=>{this.pause(),this.mediaElement.removeEventListener("canplay",e)};this.mediaElement.addEventListener("canplay",e)}this.mediaElement.load()}startTicker(){this.stopTicker(),this.updateTicker(),p(this,_,this.player.safeInterval((()=>{this.updateTicker()}),500),"f")}stopTicker(){clearInterval(m(this,_,"f")),p(this,_,-1,"f")}updateTicker(){this.onTimeChange(this.getDuration(),this.getCurrentTime())}play(){var e;this.player.preserveExecutionContext(r.a.EVENT_PLAY_STREAM),p(this,T,!1,"f"),m(this,P,"f")?this.handleError():null===(e=this.mediaElement.play())||void 0===e||e.then((()=>{var e;try{this.player.checkState()}catch(e){return void this.warn("aborting async",e)}null===(e=this.vc)||void 0===e||e.hidePosterFrame(),this.startTicker()})).catch((e=>{var t,i,s;try{this.player.checkState()}catch(e){return void this.warn("aborting async",e)}this.error("playback failure",e),null===(t=this.player)||void 0===t||t.loop.dispatchEvent(r.a.EVENT_AUTOPLAY_STREAM_PROHIBITED,{}),null===(i=this.vc)||void 0===i||i.showPlayBtn(),null===(s=this.vc)||void 0===s||s.showPosterFrame(),this.stopTicker()}))}pause(){this.player.preserveExecutionContext(r.a.EVENT_PAUSE_STREAM),this.model.playstate=o.R.PLAYSTATE_PAUSED,this.mediaElement.pause(),this.mc.isLive&&this.mc.isDvrEnabled||(this.updateTicker(),this.stopTicker())}togglePlay(){m(this,P,"f")?this.handleError():this.isPlaying()?this.pause():this.play()}isPlaying(){return this.model.playstate===o.R.PLAYSTATE_PLAYING}setVolume(e){e>=0&&e<=100&&(this.mediaElement.volume=e/100)}getVolume(){return n.x.volume(this.player)}setMuted(e){p(this,C,e,"f"),this.mediaElement.muted=e,this.mediaElement instanceof HTMLMediaElement&&(e?this.mediaElement.setAttribute("muted","muted"):this.mediaElement.removeAttribute("muted"))}setCurrentTime(e,t,i,s){void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===s&&(s=!1),this.player.preserveExecutionContext(r.a.EVENT_SEEK_START);let n=-1;this.canCalculateDvrUnixTime()&&e>=this.dvrRelToUnix(0)&&(n=e,e=this.dvrUnixToRel(e));const a=this.getDuration()>0?Math.min(e,this.getDuration()-.1):e;this.setSeekEventTimestamps(this.getCurrentTime(),a),this.setCurrentTimeRaw(a,n,t,i,s),this.player.model.time=a}setSeekEventTimestamps(e,t){p(this,b,e,"f"),p(this,D,t,"f")}setCurrentTimeRaw(e,t,i,s,n){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===n&&(n=!1),p(this,L,0,"f"),p(this,R,0,"f"),p(this,I,0,"f");const a=this.pc.generic.vodStartSeconds,o=this.pc.generic.vodEndSeconds;if(!n&&(a>0&&e<a||o>0&&e>o)&&this.resetStartAndEndTime(),this._ready){if(!this.canSeek())return;e=Math.max(0,e),this._pendingSeek=0,this.isAtEnd&&p(this,E,!0,"f");try{this.player.preserveExecutionContextAlias(r.a.EVENT_SEEK_START,-1,r.a.EVENT_SEEK_START_INTENT,r.a.EVENT_SEEK_END,r.a.EVENT_BUFFERING),m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_START_INTENT,{from:m(this,b,"f"),to:m(this,D,"f")}),s||(this.canSeekToUnixTime&&t>0?this.setCurrentUnixTime(t):this.mediaElement.currentTime=e)}catch(t){this._pendingSeek=e}}else this._pendingSeek=e;this.updateTicker(),this.isAtEnd&&!i&&this.play()}setCurrentUnixTime(e){throw new Error("method not implemented")}seekToLive(){this.canSeek()&&this.setCurrentTime(this.getDuration())}setPlaybackRate(e){const t=this.model.playbackRate!==e||this.mediaElement.playbackRate!==e;this.model.playbackRate=e,this.mediaElement.playbackRate!==e&&(this.mediaElement.playbackRate=e),t&&this.player.loop.dispatchEvent(r.a.PLAYBACK_RATE_CHANGE,{rate:e})}getDvrToDateSync(){return null}getSmoothDvrToDateSync(e){var t,i,r;return!this.dvrWindowUnstable&&e&&this.canCalculateDvrUnixTime()?(null==this.pinnedDvrSync&&(this.pinnedDvrSync=this.getDvrToDateSync(),0!==(null===(t=this.pinnedDvrSync)||void 0===t?void 0:t.rel)&&0!==(null===(i=this.pinnedDvrSync)||void 0===i?void 0:i.real)&&0!==(null===(r=this.pinnedDvrSync)||void 0===r?void 0:r.at)||(this.pinnedDvrSync=null)),this.pinnedDvrSync):this.getDvrToDateSync()}dvrRelToUnix(e,t){void 0===t&&(t=!1);const i=this.getSmoothDvrToDateSync(t);if(null!==i){if(t&&!this.dvrWindowUnstable)return this.__dvrRelToUnixRaw(e,i)|0;let r=m(this,I,"f");if(this.isPlaying()&&!this.playbackStalled){if(0!==m(this,L,"f")){const e=this.getCurrentTime();if(isFinite(e)&&e>0){const t=this.__dvrRelToUnixRaw(e,i)-m(this,L,"f");p(this,I,m(this,I,"f")+t,"f"),r+=t,this.info("PAUSE DRIFT",t)}p(this,L,0,"f"),p(this,R,0,"f")}const e=performance.now(),t=1e3*this.__dvrRelToUnixRaw(100,i);if(-1!==m(this,S,"f")&&-1!==m(this,A,"f")){const i=t-(m(this,A,"f")+(e-m(this,S,"f")));Math.abs(i)>=10&&(p(this,I,m(this,I,"f")+i/1e3,"f"),r+=i/1e3)}p(this,S,e,"f"),p(this,A,t,"f")}else p(this,S,-1,"f"),p(this,A,-1,"f"),0===m(this,R,"f")?(p(this,R,this.getCurrentTime(),"f"),p(this,L,this.__dvrRelToUnixRaw(m(this,R,"f"),i),"f")):r+=this.__dvrRelToUnixRaw(this.getCurrentTime(),i)-m(this,L,"f");return this.__dvrRelToUnixRaw(e,i)-r|0}return t&&!this.dvrWindowUnstable||(p(this,L,0,"f"),p(this,R,0,"f"),p(this,I,0,"f")),0}__dvrRelToUnixRaw(e,t){const i=t.rel-e,r=Date.now()-t.at;return(t.real+r)/1e3-i}dvrUnixToRel(e){return e-this.dvrRelToUnix(0)}canCalculateDvrUnixTime(){const e=this.getDvrToDateSync();return null!=e&&0!==e.real&&0!==e.rel&&0!==e.at}dvrUnixToRelNullable(e){const t=this.dvrRelToUnixNullable(0);return null==t?null:e-t}dvrRelToUnixNullable(e,t){return void 0===t&&(t=!1),null==this.getSmoothDvrToDateSync(t)?null:this.dvrRelToUnix(e,t)}get canSeekToUnixTime(){return!1}getPercentBuffered(){return m(this,y,"f")}getCurrentUnixTime(){return this._dvrEnabled&&this.canCalculateDvrUnixTime()?this.dvrRelToUnix(this.getCurrentTime()):-1}getCurrentUnixTimeWindowStart(){return this._dvrEnabled&&this.canCalculateDvrUnixTime()?this.dvrRelToUnix(0):-1}getCurrentUnixTimeWindowEnd(){return this._dvrEnabled&&this.canCalculateDvrUnixTime()?this.dvrRelToUnix(this.getDuration()):-1}getCurrentTime(){if(this._pendingSeek>0)return this._pendingSeek;const e=this.mediaElement.currentTime;return isNaN(e)?this.model.time:e}getCurrentTimeWithoutSeek(){return!m(this,E,"f")&&m(this,b,"f")>=0?m(this,b,"f"):this.getCurrentTime()}setTimeByPercent(e){const t=e/100*this.getDuration();return this.setCurrentTime(t),t}getDuration(){const e=this.mediaElement.duration;return isNaN(e)?0!==this._duration?this._duration:this.model.duration:e}stop(e){if(!this.isAtEnd){this.model.playstate=o.R.PLAYSTATE_STOPPED,this.isAtEnd=!0,this.player.loop.dispatchEvent(r.a.EVENT_STOP_STREAM,{}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"stop"});try{this.player.checkStateStrict(),this.pause(),s.O.isEmbedded||this.jumpToStart(),this.bufferingEventHandler(!1),this.updateTicker(),this.stopTicker()}catch(e){}}}jumpToStart(){this.setCurrentTime(0,!0)}onDVRCallback(e,t,i){this._dvrEnabled=e&&t>=120,this._dvrWindow=t,this._dvrIsLive=i,this.player.viewCtrl.onDVRCallback(this._dvrEnabled,this._dvrWindow,this._dvrIsLive),this.updateTicker(),this.player.loop.dispatchEvent(r.a.EVENT_DVR_CHANGE,{dvrEnabled:this._dvrEnabled,dvrIsLive:this._dvrIsLive,dvrWindow:this._dvrWindow})}getAudioTracks(){return[]}setAudioTrack(e){}setAudioTrackById(e){}getAudioTrack(){return null}handleError(e){var t;this.stopTicker(),p(this,P,!0,"f");let i=[];e&&(this.error(e),"string"==typeof e?i=[e]:"object"==typeof e&&("type"in e&&(0,u.Ed)(e.type)&&"error"!==e.type&&i.push(String(e.type)),"name"in e&&(0,u.Ed)(e.name)&&"error"!==e.name&&i.push(String(e.name)),(0,u.Ed)(e.message)&&i.push(String(e.message)))),null===(t=this.player.errorCtrl)||void 0===t||t.throwStreamError(...i)}toJSON(){return toString()}};return e=new WeakMap,t=new WeakMap,i=new WeakMap,l=new WeakMap,v=new WeakMap,y=new WeakMap,E=new WeakMap,T=new WeakMap,S=new WeakMap,A=new WeakMap,L=new WeakMap,R=new WeakMap,I=new WeakMap,b=new WeakMap,D=new WeakMap,k=new WeakMap,_=new WeakMap,P=new WeakMap,C=new WeakMap,M=[(0,d.C6)(r.a.EVENT_PAUSE_STREAM,{type:"other",initiator:"external-playback-pause"})],F=[(0,d.C6)(r.a.EVENT_PLAY_STREAM)],N=[(0,d.kF)({type:"lifecycle",initiator:"playback-end"})],U=[(0,d.C6)(r.a.EVENT_LOAD_STREAM)],B=[(0,d.kF)({type:"other",initiator:"dvrUpdate"})],w=Symbol.toStringTag,g(O,"AbstractPlayerCtrl"),(()=>{const e="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;f(O,null,M,{kind:"method",name:"onPause",static:!1,private:!1,access:{has:e=>"onPause"in e,get:e=>e.onPause},metadata:e},null,K),f(O,null,F,{kind:"method",name:"playEventHandler",static:!1,private:!1,access:{has:e=>"playEventHandler"in e,get:e=>e.playEventHandler},metadata:e},null,K),f(O,null,N,{kind:"method",name:"endEventHandler",static:!1,private:!1,access:{has:e=>"endEventHandler"in e,get:e=>e.endEventHandler},metadata:e},null,K),f(O,null,U,{kind:"method",name:"evalInitialSeek",static:!1,private:!1,access:{has:e=>"evalInitialSeek"in e,get:e=>e.evalInitialSeek},metadata:e},null,K),f(O,null,B,{kind:"method",name:"onDVRCallback",static:!1,private:!1,access:{has:e=>"onDVRCallback"in e,get:e=>e.onDVRCallback},metadata:e},null,K),f(null,x={value:O},G,{kind:"class",name:O.name,metadata:e},null,$),O=x.value,e&&Object.defineProperty(O,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:e}),c(O,$)})(),O})()},45055:(e,t,i)=>{"use strict";i.d(t,{X:()=>l,q:()=>h});var r=i(44198),s=i(78940),n=function(e,t,i,r,s,n){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?r.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(e){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(e||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},a=function(e,t,i){for(var r=arguments.length>2,s=0;s<t.length;s++)i=r?t[s].call(e,i):t[s].call(e);return r?i:void 0},o=function(e,t,i){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:i?"".concat(i," ",t):t})};let l=(()=>{let e,t,i=[s.JW],l=[];t=class{execute(e,t){var i,s;let n;n=e.model.mediaCollection.streams.some((e=>!e.isAudioOnly))?r.J.createVideo(e,!0):r.J.createAudio(e,!0);try{null===(i=e.viewCtrl)||void 0===i||i.removeMediaCanvas()}catch(e){}null!==n?t(n):null===(s=e.errorCtrl)||void 0===s||s.throwError("MEDIACANVAS_NOT_GENERATED",!0)}};return o(t,"DefaultMediaElementGenerator"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;n(null,e={value:t},i,{kind:"class",name:t.name,metadata:r},null,l),t=e.value,r&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r}),a(t,l)})(),t})(),h=(()=>{let e,t,i=[s.JW],l=[];t=class{execute(e,t){var i,s;const n=r.J.createVideo(e,!0);try{null===(i=e.viewCtrl)||void 0===i||i.removeMediaCanvas()}catch(e){}null!==n?t(n):null===(s=e.errorCtrl)||void 0===s||s.throwError("MEDIACANVAS_NOT_GENERATED",!0)}};return o(t,"DefaultVideoElementGenerator"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;n(null,e={value:t},i,{kind:"class",name:t.name,metadata:r},null,l),t=e.value,r&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r}),a(t,l)})(),t})()},46185:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>qo});var r=i(39906),s=i(20738),n=i(96789),a=i(78940),o=i(5677);const l=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},h=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=d},d=Number.MAX_SAFE_INTEGER||9007199254740991;let u=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),c=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),f=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var g="manifest",m="level",p="audioTrack",v="subtitleTrack",y="main",E="audio",T="subtitle";class S{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class A{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new S(e),this.fast_=new S(t),this.defaultTTFB_=r,this.ttfb_=new S(e)}update(e,t){const{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new S(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new S(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new S(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function L(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function R(){return R=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},R.apply(null,arguments)}function I(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function b(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?I(Object(i),!0).forEach((function(t){L(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):I(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class D{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=k,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}const k=function(){},_={trace:k,debug:k,log:k,warn:k,info:k,error:k};function P(){return R({},_)}function C(e,t,i){return t[e]?t[e].bind(t):function(e,t){const i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):k}(e,i)}const w=P();const x=w;function O(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function M(e,t){const i=Object.keys(e),r=Object.keys(t),s=i.length,n=r.length;return!s||!n||s===n&&!i.some((e=>-1===r.indexOf(e)))}function F(e,t=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(e);if(t){const e=i.indexOf("\0");return-1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}const i=e.length;let r,s,n,a="",o=0;for(;o<i;){if(r=e[o++],0===r&&t)return a;if(0!==r&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(r);break;case 12:case 13:s=e[o++],a+=String.fromCharCode((31&r)<<6|63&s);break;case 14:s=e[o++],n=e[o++],a+=String.fromCharCode((15&r)<<12|(63&s)<<6|63&n)}}return a}const N={hexDump:function(e){let t="";for(let i=0;i<e.length;i++){let r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t}};function U(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var B,G={exports:{}};var $,K,V,H,Y,W=(B||(B=1,$=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,K=/^(?=([^\/?#]*))\1([^]*)$/,V=/(?:\/|^)\.(?=\/)/g,H=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,G.exports=Y={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=Y.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=Y.normalizePath(r.path),Y.buildURLFromParts(r)}var s=Y.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=Y.normalizePath(s.path),Y.buildURLFromParts(s)):t;var n=Y.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=K.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=Y.normalizePath(h)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=i.alwaysNormalize?Y.normalizePath(s.path):s.path),Y.buildURLFromParts(o)},parseURL:function(e){var t=$.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(V,"");e.length!==(e=e.replace(H,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),G.exports);class j{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 q="audio",X="video",Q="audiovideo";class z{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const i=te(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let r;r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[q]:null,[X]:null,[Q]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new j),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=W.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[q]=null,e[X]=null,e[Q]=null}}function J(e){return"initSegment"!==e.sn}class Z extends z{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange){const e=this.byteRange[0],t=this.byteRange[1];if(l(e)&&l(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=l(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){l(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return J(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}}}class ee extends z{constructor(e,t,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function te(e,t){const i=Object.getPrototypeOf(e);if(i){const e=Object.getOwnPropertyDescriptor(i,t);return e||te(i,t)}}const ie=Math.pow(2,32)-1,re=[].push,se={video:1,audio:2,id3:3,text:4};function ne(e){return String.fromCharCode.apply(null,e)}function ae(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function oe(e,t){const i=he(e,t);return i<0?4294967296+i:i}function le(e,t){let i=oe(e,t);return i*=Math.pow(2,32),i+=oe(e,t+4),i}function he(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function de(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function ue(e,t){const i=[];if(!t.length)return i;const r=e.byteLength;for(let s=0;s<r;){const n=oe(e,s),a=n>1?s+n:r;if(ne(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{const r=ue(e.subarray(s+8,a),t.slice(1));r.length&&re.apply(i,r)}s=a}return i}function ce(e){const t=[],i=e[0];let r=8;const s=oe(e,r);r+=4;let n=0,a=0;0===i?(n=oe(e,r),a=oe(e,r+4),r+=8):(n=le(e,r),a=le(e,r+8),r+=16),r+=2;let o=e.length+a;const l=ae(e,r);r+=2;for(let i=0;i<l;i++){let i=r;const n=oe(e,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return x.warn("SIDX has hierarchical references (not supported)"),null;const l=oe(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function fe(e){const t=[],i=ue(e,["moov","trak"]);for(let e=0;e<i.length;e++){const r=i[e],s=ue(r,["tkhd"])[0];if(s){let e=s[0];const i=oe(s,0===e?12:20),n=ue(r,["mdia","mdhd"])[0];if(n){e=n[0];const s=oe(n,0===e?12:20),a=ue(r,["mdia","hdlr"])[0];if(a){const e=ne(a.subarray(8,12)),n={soun:q,vide:X}[e],o=ge(ue(r,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:s,type:n,stsd:o},t[n]=b({timescale:s,id:i},o)):t[i]={timescale:s,type:e,stsd:o}}}}}return ue(e,["moov","mvex","trex"]).forEach((e=>{const i=oe(e,4),r=t[i];r&&(r.default={duration:oe(e,12),flags:oe(e,20)})})),t}function ge(e){const t=e.subarray(8),i=t.subarray(86),r=ne(t.subarray(4,8));let s,n=r;const a="enca"===r||"encv"===r;if(a){const e=ue(t,[r])[0];ue(e.subarray("enca"===r?28:78),["sinf"]).forEach((e=>{const t=ue(e,["schm"])[0];if(t){const i=ne(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=ue(e,["frma"])[0];t&&(n=ne(t))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=ue(i,["avcC"])[0];e&&e.length>3&&(n+="."+ve(e[1])+ve(e[2])+ve(e[3]),s=me("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const e=ue(t,[r])[0],i=ue(e.subarray(28),["esds"])[0];if(i&&i.length>7){let e=4;if(3!==i[e++])break;e=pe(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=pe(i,e);const r=i[e++];if(64!==r)break;if(n+="."+ve(r),e+=12,5!==i[e++])break;e=pe(i,e);const s=i[e++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&i[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=ue(i,["hvcC"])[0];if(e&&e.length>12){const t=e[1],i=["","A","B","C"][t>>6],r=31&t,s=oe(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+i+r,n+="."+s.toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];if(t||h){h="."+t.toString(16).toUpperCase()+h}}n+=h}s=me("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=me(n,i)||n;break;case"vp09":{const e=ue(i,["vpcC"])[0];if(e&&e.length>6){const t=e[4],i=e[5],r=e[6]>>4&15;n+="."+ye(t)+"."+ye(i)+"."+ye(r)}break}case"av01":{const e=ue(i,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,r=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,d=(16&e[2])>>4,u=(8&e[2])>>3,c=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,v=0;n+="."+t+"."+ye(r)+a+"."+ye(h)+"."+d+"."+u+c+f+"."+ye(g)+"."+ye(m)+"."+ye(p)+"."+v,s=me("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:s}}function me(e,t){const i=ue(t,["dvvC"]),r=i.length?i[0]:ue(t,["dvcC"])[0];if(r){const t=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return e+"."+ye(t)+"."+ye(i)}}function pe(e,t){const i=t+5;for(;128&e[t++]&&t<i;);return t}function ve(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function ye(e){return(e<10?"0":"")+e}function Ee(e){const t=ue(e,["schm"])[0];if(t){const i=ne(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return ue(e,["schi","tenc"])[0]}return null}function Te(e){const t=oe(e,0);let i=8;1&t&&(i+=4),4&t&&(i+=4);let r=0;const s=oe(e,4);for(let n=0;n<s;n++){if(256&t){r+=oe(e,i),i+=4}512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4)}return r}function Se(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Ae(e,t){const i=[],r=t.samples,s=t.timescale,n=t.id;let a=!1;return ue(r,["moof"]).map((o=>{const l=o.byteOffset-8;ue(o,["traf"]).map((o=>{const h=ue(o,["tfdt"]).map((e=>{const t=e[0];let i=oe(e,4);return 1===t&&(i*=Math.pow(2,32),i+=oe(e,8)),i/s}))[0];return void 0!==h&&(e=h),ue(o,["tfhd"]).map((h=>{const d=oe(h,4),u=16777215&oe(h,0);let c=0;const f=!!(16&u);let g=0;const m=!!(32&u);let p=8;d===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=oe(h,p),p+=4),f&&(g=oe(h,p),p+=4),m&&(p+=4),"video"===t.type&&(a=Le(t.codec)),ue(o,["trun"]).map((n=>{const o=n[0],h=16777215&oe(n,0),d=!!(1&h);let u=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const A=oe(n,4);let L=8;d&&(u=oe(n,L),L+=4),f&&(L+=4);let R=u+l;for(let l=0;l<A;l++){if(m?(p=oe(n,L),L+=4):p=c,v?(y=oe(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?oe(n,L):he(n,L),L+=4),t.type===X){let t=0;for(;t<y;){const n=oe(r,R);if(R+=4,Re(a,r[R])){Ie(r.subarray(R,R+n),a?2:1,e+S/s,i)}R+=n,t+=n+4}}e+=p/s}})))}))}))})),i}function Le(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Re(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Ie(e,t,i,r){const s=be(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const e=s.length-n;let t=n;if(o<e)n+=o;else if(o>e){x.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===s[t++]){const e=ae(s,t);if(t+=2,49===e){const e=oe(s,t);if(t+=4,1195456820===e){const e=s[t++];if(3===e){const n=s[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=s[t++]}r.push({type:e,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let i=0;i<16;i++){const r=s[t++].toString(16);e.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=s[t++];r.push({payloadType:a,pts:i,uuid:e.join(""),userData:F(l),userDataBytes:l})}}}function be(e){const t=e.byteLength,i=[];let r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;const s=t-i.length,n=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=e[a];return n}function De(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");let r,s,n;r=0,s=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let r=8,s=i;for(;s--;)r+=t[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),s=0,r=8;s<i;s++)n.set(t[s],r),r+=t[s].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,s,a,i||new Uint8Array)}function ke(e){const t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};const s=e.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:t};const n=e.buffer,a=N.hexDump(new Uint8Array(n,i+12,16)),o=e.getUint32(28);let l=null,h=null;if(0===s){if(t-32<o||o<22)return{offset:i,size:t};h=new Uint8Array(n,i+32,o)}else if(1===s){if(!o||r<i+32+16*o+16)return{offset:i,size:t};l=[];for(let e=0;e<o;e++)l.push(new Uint8Array(n,i+32+16*e,16))}return{version:s,systemId:a,kids:l,data:h,offset:i,size:t}}const _e=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Pe={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 Ce(e,t){const i=Pe[t];return!!i&&!!i[e.slice(0,4)]}function we(e,t,i=!0){return!e.split(",").some((e=>!xe(e,t,i)))}function xe(e,t,i=!0){var r;const s=O(i);return null!=(r=null==s?void 0:s.isTypeSupported(Oe(e,t)))&&r}function Oe(e,t){return`${t}/mp4;codecs=${e}`}function Me(e){if(e){const t=e.substring(0,4);return Pe.video[t]}return 2}function Fe(e){const t=_e();return e.split(",").reduce(((e,i)=>{const r=t&&Le(i)?9:Pe.video[i];return r?(2*r+e)/(e?3:2):(Pe.audio[i]+e)/(e?2:1)}),0)}const Ne={};const Ue=/flac|opus|mp4a\.40\.34/i;function Be(e,t=!0){return e.replace(Ue,(e=>function(e,t=!0){if(Ne[e])return Ne[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let s=0;s<i.length;s++){var r;if(xe(i[s],"audio",t))return Ne[e]=i[s],i[s];if("mp3"===i[s]&&null!=(r=O(t))&&r.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)))}function Ge(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){const i=t.split(",");if(i.length>1){if(e)for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t];return i[0]}}return t||e}function $e(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}function Ke(e){const t=O(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ve(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const He={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ye(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}const We={};function je(e,t,i,r,s,n){const a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):o?1/0:2;let u=null;if(null!=a&&a.length)try{u=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,i)=>{if(i){const r=t.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((t=>{e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!u&&l(d)&&Object.keys(u).some((e=>parseInt(e)>d))}function qe(e,t,i){const r=e.videoCodec,s=e.audioCodec;if(!r&&!s||!i)return Promise.resolve(He);const n=[];if(r){const t={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},i=e.videoRange;"SDR"!==i&&(t.transferFunction=i.toLowerCase());const s=r.split(","),a=navigator.userAgent;if(s.some((e=>Le(e)))&&_e())return Promise.resolve(Ye(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${a})`),n));n.push.apply(n,s.map((e=>({type:"media-source",video:b(b({},t),{},{contentType:Oe($e(e),"video")})}))))}return s&&e.audioGroups&&e.audioGroups.forEach((e=>{var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",i=parseFloat(e);l(i)&&i>2&&n.push.apply(n,s.split(",").map((e=>({type:"media-source",audio:{contentType:Oe(e,"audio"),channels:""+i}}))))}})))})),Promise.all(n.map((e=>{const t=function(e){const{audio:t,video:i}=e,r=i||t;if(r){const e=Ve(r.contentType);if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${e}_${Math.ceil(i.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}(e);return We[t]||(We[t]=i.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:n,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e})))}const Xe=["NONE","TYPE-0","TYPE-1",null];const Qe=["SDR","PQ","HLG"];var ze="",Je="YES",Ze="v2";function et(e){const{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r<t/2?i?Ze:Je:ze}class tt{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class it{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return rt(this._audioGroups,e)}hasSubtitleGroup(e){return rt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function rt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function st(e,t){let i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){r=t.allowedVideoRanges||Qe.slice(0);const e="SDR"!==r.join("")&&!t.videoCodec;i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),i||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}const nt=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(i,r)=>{if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}})(t));function at(e,t){x.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function ot(e){return e.reduce(((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function lt(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:n}=e;return{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:n}}function ht(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r<t.length;r++){if(dt(e,t[r],i))return r}return-1}function dt(e,t,i){const{groupId:r,name:s,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===r||t.groupId===r)&&(void 0===s||t.name===s)&&(void 0===n||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some((e=>-1===r.indexOf(e)))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function ut(e,t){const{audioCodec:i,channels:r}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function ct(e,t,i){for(let r=t;r>-1;r--)if(i(e[r]))return r;for(let r=t+1;r<e.length;r++)if(i(e[r]))return r;return-1}function ft(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}const gt=function(e,t){let i=0,r=e.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=e[s];const a=t(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function mt(e,t,i=0,r=0,s=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===pt(i,r,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const r=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),i);return e.start<=r}return!1}(n,e,Math.min(s,r))))return n;const a=gt(t,pt.bind(null,i,r));return!a||a===e&&n?n:a}function pt(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function vt(e,t,i){const r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function yt(e,t){return gt(e,(e=>e.cc<t?1:e.cc>t?-1:0))}function Et(e){switch(e.details){case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_TIMEOUT:case c.LEVEL_LOAD_TIMEOUT:case c.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Tt(e,t){const i=Et(t);return e.default[(i?"timeout":"error")+"Retry"]}function St(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function At(e){return b(b({},e),{errorRetry:null,timeoutRetry:null})}function Lt(e,t,i,r){if(!e)return!1;const s=null==r?void 0:r.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}var Rt=0,It=2,bt=3,Dt=5,kt=0,_t=1,Pt=2;function Ct(e){const t={action:Rt,flags:kt};return e&&(t.resolved=!0),t}var wt="NOT_LOADED",xt="APPENDING",Ot="PARTIAL",Mt="OK";class Ft{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.BUFFER_APPENDED,this.onBufferAppended,this),e.on(f.FRAG_BUFFERED,this.onFragBuffered,this),e.on(f.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.BUFFER_APPENDED,this.onBufferAppended,this),e.off(f.FRAG_BUFFERED,this.onFragBuffered,this),e.off(f.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let t=i.length;t--;){const r=i[t];if(!r)break;const s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:r}=this,s=Object.keys(r);for(let n=s.length;n--;){const a=r[s[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r,s){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const a=this.fragments[r];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||s))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some((e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(a.body),i})):this.removeFragment(a.body))}))}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const i=e.frag,r=Ut(i),s=this.fragments[r];if(!s||s.buffered&&i.gap)return;const n=!i.relurl;if(Object.keys(t).forEach((r=>{const a=i.elementaryStreams[r];if(!a)return;const o=t[r],l=n||!0===a.partial;s.range[r]=this.getBufferedTimes(i,e.part,l,o)})),s.loaded=null,Object.keys(s.range).length){s.buffered=!0;(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),Nt(s)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(s.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Bt(i,(t=>t.fragment.sn>=e)))}fragBuffered(e,t){const i=Ut(e);let r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){const s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<r.length;e++){const t=r.start(e)-this.bufferPadding,i=r.end(e)+this.bufferPadding;if(l>=t&&o<=i){s.time.push({startPTS:Math.max(n,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(n<i&&a>t){const t=Math.max(n,r.start(e)),i=Math.min(a,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&Nt(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Nt(t))}getState(e){const t=Ut(e),i=this.fragments[t];return i?i.buffered?Nt(i)?Ot:Mt:xt:wt}isTimeBuffered(e,t,i){let r,s;for(let n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const i=t.frag,r=t.part?null:t,s=Ut(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:r,timeRanges:s,type:n}=t;if("initSegment"===i.sn)return;const a=i.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}this.timeRanges=s;const o=s[n];this.detectEvictedFragments(n,o,a,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ut(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){const s=t[i[r]];if((null==s?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=Ut(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=Bt(i,(e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;i&&i.forEach((e=>e.clearElementaryStreamInfo()))}}function Nt(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function Ut(e){return`${e.type}_${e.level}_${e.sn}`}function Bt(e,t){return e.filter((e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i}))}var Gt=0,$t=1;class Kt{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Gt:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case $t:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Vt{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=c[f],m=c[o],p=c[m];let v=257*c[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,u[i]=v,f?(f=o^c[c[c[p^o]]],g^=c[c[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)return;this.key=t;const s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,u=this.rcon,c=this.invSubMix,f=c[0],g=c[1],m=c[2],p=c[3];let v,y;for(a=0;a<n;a++)a<s?v=l[a]=t[a]:(y=v,a%s==0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=u[a/s|0]<<24):s>6&&a%s==4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-s]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){const r=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],u=this.uint8ArrayToUint32Array_(i);let c=u[0],f=u[1],g=u[2],m=u[3];const p=new Int32Array(e),v=new Int32Array(p.length);let y,E,T,S,A,L,R,I,b,D,k,_,P,C;const w=this.networkToHostOrderSwap;for(;t<p.length;){for(b=w(p[t]),D=w(p[t+1]),k=w(p[t+2]),_=w(p[t+3]),A=b^s[0],L=_^s[1],R=k^s[2],I=D^s[3],P=4,C=1;C<r;C++)y=o[A>>>24]^l[L>>16&255]^h[R>>8&255]^d[255&I]^s[P],E=o[L>>>24]^l[R>>16&255]^h[I>>8&255]^d[255&A]^s[P+1],T=o[R>>>24]^l[I>>16&255]^h[A>>8&255]^d[255&L]^s[P+2],S=o[I>>>24]^l[A>>16&255]^h[L>>8&255]^d[255&R]^s[P+3],A=y,L=E,R=T,I=S,P+=4;y=n[A>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&I]^s[P],E=n[L>>>24]<<24^n[R>>16&255]<<16^n[I>>8&255]<<8^n[255&A]^s[P+1],T=n[R>>>24]<<24^n[I>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^s[P+2],S=n[I>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^s[P+3],v[t]=w(y^c),v[t+1]=w(S^f),v[t+2]=w(T^g),v[t+3]=w(E^m),c=b,f=D,g=k,m=_,t+=4}return v.buffer}}class Ht{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=function(e){switch(e){case Gt:return"AES-CBC";case $t:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class Yt{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,r){return this.useSoftware?new Promise(((s,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,r);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){const{currentIV:s,currentResult:n,remainderData:a}=this;if(r!==Gt||16!==t.byteLength)return x.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Se(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Vt),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Ht(this.subtle,t,r)}return this.fastAesKey.expandKey().then((t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Kt(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)})).catch((s=>(x.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,r))))}onWebCryptoError(e,t,i,r){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);const s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(x.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Wt=Math.pow(2,17);class jt{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Qt({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(Xt(e));e.gap=!1}const l=this.loader=s?new s(r):new n(r),h=qt(e);e.loader=l;const d=At(r.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Wt};e.stats=l.stats;const g={onSuccess:(t,i,r,s)=>{this.resetLoader(e,l);let n=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:s})},onError:(t,r,s,n)=>{this.resetLoader(e,l),o(new Qt({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:b({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:n}))},onAbort:(t,i,r)=>{this.resetLoader(e,l),o(new Qt({type:u.NETWORK_ERROR,details:c.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,l),o(new Qt({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:r,stats:t}))}};t&&(g.onProgress=(i,r,s,n)=>t({frag:e,part:null,payload:s,networkDetails:n})),l.load(h,f,g)}))}loadPart(e,t,i){this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Xt(e,t));const l=this.loader=s?new s(r):new n(r),h=qt(e,t);e.loader=l;const d=At(r.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Wt};t.stats=l.stats,l.load(h,f,{onSuccess:(r,s,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:r.data,networkDetails:o};i(h),a(h)},onError:(i,r,s,n)=>{this.resetLoader(e,l),o(new Qt({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:b({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Qt({type:u.NETWORK_ERROR,details:c.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,l),o(new Qt({type:u.NETWORK_ERROR,details:c.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(e,t){const i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){const r=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function qt(e,t=null){const i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(l(s)&&l(n)){var a;let t=s,i=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-s;e%16&&(i=n+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=i}var o;return r}function Xt(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:u.MEDIA_ERROR,details:c.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Qt(r)}class Qt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class zt extends D{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Jt{constructor(e,t,i,r=0,s=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=n}}const Zt={length:0,start:()=>0,end:()=>0};class ei{static isBuffered(e,t){if(e){const i=ei.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=ei.getBuffered(e);return ei.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const r=ei.bufferedRanges(e);if(r.length)return ei.bufferedInfo(r,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort(((e,t)=>e.start-t.start||t.end-e.end));let r=-1,s=[];if(i)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(r=n);const a=s.length;if(a){const t=s[a-1].end;e[n].start-t<i?e[n].end>t&&(s[a-1].end=e[n].end):s.push(e[n])}else s.push(e[n])}else s=e;let n,a=0,o=t,l=t;for(let e=0;e<s.length;e++){const h=s[e].start,d=s[e].end;if(-1===r&&t>=h&&t<=d&&(r=e),t+i>=h&&t<d)o=h,l=d,a=l-t;else if(t+i<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||Zt}catch(e){return x.log("failed to get media.buffered",e),Zt}}}const ti=/\{\$([a-zA-Z0-9-_]+)\}/g;function ii(e){return ti.test(e)}function ri(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(ti,(t=>{const r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s}))}return t}function si(e,t,i){let r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function ni(e,t,i){const r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const ai=/^(\d+)x(\d+)$/,oi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class li{constructor(e,t){"string"==typeof e&&(e=li.parseAttrList(e,t)),R(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce(((e,t)=>(e[t.toLowerCase()]=!0,e)),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=ai.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const r={};for(oi.lastIndex=0;null!==(i=oi.exec(e));){const s=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=ri(t,n);else if(!o&&!a)switch(s){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":x.warn(`${e}: attribute ${s} is missing quotes`)}r[s]=n}return r}}function hi(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class di{constructor(e,t,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){x.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=R(new li({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);l(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(x.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(l(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&l(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class ui{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}get hasProgramDateTime(){return!!this.fragments.length&&l(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ci(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function fi(e){switch(e){case"AES-128":case"AES-256":return Gt;case"AES-256-CTR":return $t;default:throw new Error(`invalid full segment method ${e}`)}}function gi(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function mi(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}function pi(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],s=r[1];t?(e.splice(-1,1),i=gi(s)):i=function(e){const t=mi(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}const vi="undefined"!=typeof self?self:void 0;var yi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ei="org.w3.clearkey",Ti="com.apple.streamingkeydelivery",Si="com.microsoft.playready",Ai="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Li(e){switch(e){case Ti:return yi.FAIRPLAY;case Si:return yi.PLAYREADY;case Ai:return yi.WIDEVINE;case Ei:return yi.CLEARKEY}}var Ri="1077efecc0b24d02ace33c1e52e2fb4b",Ii="e2719d58a985b3c9781ab030af78d30e",bi="9a04f07998404286ab92e65be0885f95",Di="edef8ba979d64acea3c827dcd51d21ed";function ki(e){return e===Di?yi.WIDEVINE:e===bi?yi.PLAYREADY:e===Ri||e===Ii?yi.CLEARKEY:void 0}function _i(e){switch(e){case yi.FAIRPLAY:return Ti;case yi.PLAYREADY:return Si;case yi.WIDEVINE:return Ai;case yi.CLEARKEY:return Ei}}function Pi(e){const{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[yi.FAIRPLAY,yi.WIDEVINE,yi.PLAYREADY,yi.CLEARKEY].filter((e=>!!t[e])):[];return!r[yi.WIDEVINE]&&i&&r.push(yi.WIDEVINE),r}const Ci=null!=vi&&null!=(wi=vi.navigator)&&wi.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var wi;function xi(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),s=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){const e=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(e){const t=gi(e).subarray(0,16);return function(e){const t=function(e,t,i){const r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),t}}return null}let Oi={};class Mi{static clearKeyUriToKeyIdMap(){Oi={}}constructor(e,t,i,r=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!ci(e)}isSupported(){if(this.method){if(ci(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ti:case Ai:case Si:case Ei:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(ci(this.method)&&this.uri&&!this.iv){"number"!=typeof e&&(x.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=function(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e);return new Mi(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=pi(this.uri);if(t)switch(this.keyFormat){case Ai:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Si:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=De(e,0,t),this.keyId=xi(t);break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=Oi[this.uri];if(!e){const t=Object.keys(Oi).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),Oi[this.uri]=e}this.keyId=e}return this}}const Fi=/#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,Ni=/#EXT-X-MEDIA:(.*)/g,Ui=/^#EXT(?:INF|-X-TARGETDURATION):/m,Bi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Gi=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 $i{static findGroup(e,t){for(let i=0;i<e.length;i++){const r=e[i];if(r.id===t)return r}}static resolve(e,t){return W.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Ui.test(e)}static parseMasterPlaylist(e,t){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:ii(e)},r=[];let s;for(Fi.lastIndex=0;null!=(s=Fi.exec(e));)if(s[1]){var n;const e=new li(s[1],i),a=ri(i,s[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:$i.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Wi(e.CODECS,o);const h=e["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},Wi(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||r.push(o),i.levels.push(o)}else if(s[3]){const e=s[3],r=s[4];switch(e){case"SESSION-DATA":{const e=new li(r,i),t=e["DATA-ID"];t&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[t]=e);break}case"SESSION-KEY":{const e=Hi(r,t,i);e.encrypted&&e.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(e)):x.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":si(i,new li(r,i),t);break;case"CONTENT-STEERING":{const e=new li(r,i);i.contentSteering={uri:$i.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Yi(r)}}const a=r.length>0&&r.length<i.levels.length;return i.levels=a?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,i){let r;const s={},n=i.levels,a={AUDIO:n.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Ni.lastIndex=0;null!==(r=Ni.exec(e));){const e=new li(r[1],i),n=e.TYPE;if(n){const i=a[n],r=s[n]||[];s[n]=r;const l=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,u=e.CHARACTERISTICS,c=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?$i.resolve(e.URI,t):""};if(h&&(f.assocLang=h),d&&(f.channels=d),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=i&&i.length){const e=$i.findGroup(i,f.groupId)||i[0];ji(f,e,"audioCodec"),ji(f,e,"textCodec")}r.push(f)}}return s}static parseLevelPlaylist(e,t,i,r,s,n){var a;const o={url:t},h=new ui(t),d=h.fragments,u=[];let c,f,g,m,p=null,v=0,y=0,E=0,T=0,S=0,A=null,L=new Z(r,o),I=-1,b=!1,D=null;if(Bi.lastIndex=0,h.m3u8=e,h.hasVariableRefs=ii(e),"#EXTM3U"!==(null==(a=Bi.exec(e))?void 0:a[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(c=Bi.exec(e));){b&&(b=!1,L=new Z(r,o),L.playlistOffset=E,L.start=E,L.sn=v,L.cc=T,S&&(L.bitrate=S),L.level=i,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),D&&(L.setByteRange(D),D=null)));const e=c[1];if(e){L.duration=parseFloat(e);const t=(" "+c[2]).slice(1);L.title=t||null,L.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(l(L.duration)){L.playlistOffset=E,L.start=E,g&&Qi(L,g,h),L.sn=v,L.level=i,L.cc=T,d.push(L);const e=(" "+c[3]).slice(1);L.relurl=ri(h,e),qi(L,A,u),A=L,E+=L.duration,v++,y=0,b=!0}}else{if(c=c[0].match(Gi),!c){x.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<c.length&&void 0===c[f];f++);const e=(" "+c[f]).slice(1),s=(" "+c[f+1]).slice(1),a=c[f+2]?(" "+c[f+2]).slice(1):null;switch(e){case"BYTERANGE":A?L.setByteRange(s,A):L.setByteRange(s);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=s,L.tagList.push(["PROGRAM-DATE-TIME",s]),-1===I&&(I=d.length);break;case"PLAYLIST-TYPE":h.type&&zi(h,e,c),h.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?zi(h,e,c):d.length>0&&Ji(h,e,c),v=h.startSN=parseInt(s);break;case"SKIP":{h.skippedSegments&&zi(h,e,c);const t=new li(s,h),i=t.decimalInteger("SKIPPED-SEGMENTS");if(l(i)){h.skippedSegments+=i;for(let e=i;e--;)d.push(null);v+=i}const r=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==h.targetduration&&zi(h,e,c),h.targetduration=Math.max(parseInt(s),1);break;case"VERSION":null!==h.version&&zi(h,e,c),h.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||zi(h,e,c),h.live=!1;break;case"#":(s||a)&&L.tagList.push(a?[s,a]:[s]);break;case"DISCONTINUITY":T++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([e]);break;case"BITRATE":L.tagList.push([e,s]),S=1e3*parseInt(s),l(S)?L.bitrate=S:S=0;break;case"DATERANGE":{const e=new li(s,h),t=new di(e,h.dateRanges[e.ID],h.dateRangeTagCount);h.dateRangeTagCount++,t.isValid||h.skippedSegments?h.dateRanges[t.id]=t:x.warn(`Ignoring invalid DATERANGE tag: "${s}"`),L.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new li(s,h);"IMPORT"in e?ni(h,e,n):si(h,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?zi(h,e,c):d.length>0&&Ji(h,e,c),h.startCC=T=parseInt(s);break;case"KEY":{const e=Hi(s,t,h);if(e.isSupported()){if("NONE"===e.method){g=void 0;break}g||(g={}),g[e.keyFormat]&&(g=R({},g)),g[e.keyFormat]=e}else x.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":h.startTimeOffset=Yi(s);break;case"MAP":{const e=new li(s,h);if(L.duration){const t=new Z(r,o);Xi(t,e,i,g),p=t,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{const t=L.byteRangeEndOffset;if(t){const e=L.byteRangeStartOffset;D=`${t-e}@${e}`}else D=null;Xi(L,e,i,g),p=L,b=!0}p.cc=T;break}case"SERVER-CONTROL":m&&zi(h,e,c),m=new li(s),h.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),h.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{h.partTarget&&zi(h,e,c);const t=new li(s);h.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=h.partList;e||(e=h.partList=[]);const t=y>0?e[e.length-1]:void 0,i=y++,r=new li(s,h),n=new ee(r,L,o,i,t);e.push(n),L.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new li(s,h);h.preloadHint=e;break}case"RENDITION-REPORT":{const e=new li(s,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(e);break}default:x.warn(`line parsed but not handled: ${c}`)}}}A&&!A.relurl?(d.pop(),E-=A.duration,h.partList&&(h.fragmentHint=A)):h.partList&&(qi(L,A,u),L.cc=T,h.fragmentHint=L,g&&Qi(L,g,h)),h.targetduration||(h.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const k=d.length,_=d[0],P=d[k-1];if(E+=h.skippedSegments*h.targetduration,E>0&&k&&P){h.averagetargetduration=E/k;const e=P.sn;h.endSN="initSegment"!==e?e:0,h.live||(P.endList=!0),_&&void 0===h.startCC&&(h.startCC=_.cc),I>0&&(!function(e,t){let i=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(d,I),_&&u.unshift(_))}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(E+=h.fragmentHint.duration),h.totalduration=E,u.length&&h.dateRangeTagCount&&_&&Ki(u,h),h.endCC=T,h}}function Ki(e,t){const i=e.length,r=e[i-1],s=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let a=n.length;a--;){const o=t.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=r.ref;for(let r=i;r--;){const i=Vi(t,l,e,r,s);if(-1!==i){o.tagAnchor=t.fragments[i].ref;break}}}}function Vi(e,t,i,r,s){const n=i[r];if(n){const o=n.programDateTime;if(t>=o||0===r){var a;if(t<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||s)-n.start)){const s=i[r].sn-e.startSN,n=e.fragments;if(n.length>i.length){for(let a=(i[r+1]||n[n.length-1]).sn-e.startSN;a>s;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return s}}}return-1}function Hi(e,t,i){var r,s;const n=new li(e,i),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&x.error(`Invalid IV: ${n.IV}`);const u=o?$i.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Mi(a,u,d,c,l)}function Yi(e){const t=new li(e).decimalFloatingPoint("TIME-OFFSET");return l(t)?t:null}function Wi(e,t){let i=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const r=i.filter((t=>Ce(t,e)));r.length&&(t[`${e}Codec`]=r.map((e=>e.split("/")[0])).join(","),i=i.filter((e=>-1===r.indexOf(e))))})),t.unknownCodecs=i}function ji(e,t,i){const r=t[i];r&&(e[i]=r)}function qi(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Xi(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function Qi(e,t,i){e.levelkeys=t;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}function zi(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function Ji(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function Zi(e,t){const i=t.startPTS;if(l(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function er(e,t,i,r,s,n){r-i<=0&&(x.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);let a=i,o=r;const h=t.startPTS,d=t.endPTS;if(l(h)){const e=Math.abs(h-i);l(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(i,h),i=Math.min(i,h),s=Math.min(s,t.startDTS),o=Math.min(r,d),r=Math.max(r,d),n=Math.max(n,t.endDTS)}const u=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=n;const c=t.sn;if(!e||c<e.startSN||c>e.endSN)return 0;let f;const g=c-e.startSN,m=e.fragments;for(m[g]=t,f=g;f>0;f--)Zi(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Zi(m[f],m[f+1]);return e.fragmentHint&&Zi(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function tr(e,t){if(e===t)return;let i=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){i=t;break}}let s;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){const r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let h=s;h<=n;h++){const s=l[a+h];let n=o[h];if(r&&!n&&s&&(n=t.fragments[h]=s),s&&n){if(i(s,n,h,o),s.url&&s.url!==n.url)return void(t.playlistParsingError=ir(`media sequence mismatch ${n.sn}:`,e,t,s,n));if(s.cc!==n.cc)return void(t.playlistParsingError=ir(`discontinuity sequence mismatch (${s.cc}!=${n.cc})`,e,t,s,n))}}}(e,t,((r,n,a,o)=>{if(!t.startCC&&n.cc!==r.cc){var h,d;const i=r.cc-n.cc;for(let e=a;e<o.length;e++)o[e].cc+=i;t.startCC=null!=(h=null==(d=ar(e,t.startSN-1))?void 0:d.cc)?h:o[0].cc,t.endCC=o[o.length-1].cc}l(r.startPTS)&&l(r.endPTS)&&(n.setStart(n.startPTS=r.startPTS),n.startDTS=r.startDTS,n.maxStartPTS=r.maxStartPTS,n.endPTS=r.endPTS,n.endDTS=r.endDTS,n.minEndPTS=r.minEndPTS,n.setDuration(r.endPTS-r.startPTS),n.duration&&(s=n),t.PTSKnown=t.alignedSliding=!0),r.hasStreams&&(n.elementaryStreams=r.elementaryStreams),n.loader=r.loader,r.hasStats&&(n.stats=r.stats),r.initSegment&&(n.initSegment=r.initSegment,i=r.initSegment)}));const n=t.fragments,a=t.fragmentHint?n.concat(t.fragmentHint):n;if(i&&a.forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)})),t.skippedSegments)if(t.deltaUpdateFailed=n.some((e=>!e)),t.deltaUpdateFailed){x.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)n.shift();t.startSN=n[0].sn}else{t.endCC=n[n.length-1].cc,t.canSkipDateRanges&&(t.dateRanges=function(e,t){const{dateRanges:i,recentlyRemovedDateranges:r}=t,s=R({},e);r&&r.forEach((e=>{delete s[e]}));const n=Object.keys(s).length;n&&Object.keys(i).forEach((e=>{const t=s[e],r=new di(i[e].attr,t);r.isValid?(s[e]=r,t||(r.tagOrder+=n)):x.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${nt(i[e].attr)}"`)}));return s}(e.dateRanges,t));const i=e.fragments.filter((e=>e.rawProgramDateTime));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<a.length;e++)null===a[e].programDateTime&&qi(a[e],a[e-1],i);Ki(i,t)}!function(e,t,i){if(e&&t){let r=0;for(let s=0,n=e.length;s<=n;s++){const n=e[s],a=t[s+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):r--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?er(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):rr(e,t),n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function ir(e,t,i,r,s){return new Error(`${e} ${s.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function rr(e,t,i=!0){const r=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,n=r>=0;let a=0;if(n&&r<s.length)a=s[r].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}sr(t,a)}function sr(e,t){if(t){const i=e.fragments;for(let r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function nr(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const r=e.fragments,s=4;if(r.length&&i*s>t){const e=1e3*r[r.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function ar(e,t,i){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,r&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function or(e,t,i){return e?lr(e.partList,t,i):null}function lr(e,t,i){if(e)for(let r=e.length;r--;){const s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function hr(e){e.forEach(((e,t)=>{var i;null==(i=e.details)||i.fragments.forEach((e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function dr(e,t){for(let r=0,s=e.length;r<s;r++){var i;if((null==(i=e[r])?void 0:i.cc)===t)return e[r]}return null}function ur(e,t){if(e){const i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function cr(e,t){const i=t.fragments;for(let t=0,r=i.length;t<r;t++)ur(i[t],e);t.fragmentHint&&ur(t.fragmentHint,e),t.alignedSliding=!0}function fr(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),r=dr(t.fragments,i),s=dr(e.fragments,i);if(!r||!s)return;x.log(`Aligning playlist at start of dicontinuity sequence ${i}`);cr(r.start-s.start,e)}function gr(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,r=t.fragments;if(!i.length||!r.length)return;let s,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=dr(r,a),n=dr(i,a)),s&&n||(s=r[Math.floor(r.length/2)],n=dr(i,s.cc)||i[Math.floor(i.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;cr((l-o)/1e3-(n.start-s.start),e)}const mr=function(e){let t="";const i=e.length;for(let r=0;r<i;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t},pr={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class vr extends zt{constructor(e,t,i,r,s){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=pr.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:e,fragCurrent:t,media:i,mediaBuffer:r,state:s}=this,n=i?i.currentTime:0,a=ei.bufferInfo(r||i,n,e.maxBufferHole);if(this.log(`media seeking to ${l(n)?n.toFixed(3):n}, state: ${s}`),this.state===pr.ENDED)this.resetLoadingState();else if(t){const i=e.maxFragLookUpTolerance,r=t.start-i,s=t.start+t.duration+i;if(!a.len||s<a.start||r>a.end){const e=n>s;(n<r||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||a.len||(this.log(`setting startPosition to ${n} because of seek before start`),this.nextLoadPosition=this.startPosition=n),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new jt(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Yt(e.config)}registerListeners(){const{hls:e}=this;e.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(f.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===pr.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=pr.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;const s=e.nextStart;if(s&&s>r&&s<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const n=t.partList;if(null!=n&&n.length){const e=n[n.length-1];return ei.isBuffered(this.media,e.start+e.duration/2)}const a=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(a)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===pr.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=pr.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){this._doFragLoad(e,t,i,(e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const t=this.state,i=e.frag;this.fragContextChanged(i)?(t===pr.FRAG_LOADING||!this.fragCurrent&&t===pr.PARSING)&&(this.fragmentTracker.removeFragment(i),this.state=pr.IDLE):("payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(f.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((t=>{this.state!==pr.STOPPED&&this.state!==pr.ERROR&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===xt){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(s,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ot&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:i};this.hls.trigger(f.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:t}=this,{frag:i,payload:r}=e,s=i.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&ci(s.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,fi(s.method)).catch((e=>{throw t.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((r=>{const s=self.performance.now();return t.trigger(f.FRAG_DECRYPTED,{frag:i,payload:r,stats:{tstart:n,tdecrypt:s}}),e.payload=r,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((t=>{this.state!==pr.STOPPED&&this.state!==pr.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==pr.STOPPED&&(this.state=pr.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?mr(ei.getBuffered(i)):"(detached)"})`),J(e)){var r;if(e.type!==T){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=pr.IDLE)}const t=null==(r=this.levels)?void 0:r[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=pr.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:r,partsLoaded:s}=e,n=!s||0===s.length||s.some((e=>!e)),a=new Jt(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var s;this.fragCurrent=e;const n=null==t?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=pr.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(f.KEY_LOADED,e),this.state===pr.KEY_LOADING&&(this.state=pr.IDLE),e})),this.hls.trigger(f.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const o=this.fragPrevious;if(J(e)&&(!o||e.sn!==o.sn)){const i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&J(e)){const s=n.partList;if(s&&r){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(s,e,i);if(o>-1){const l=s[o];let h;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${s.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=pr.FRAG_LOADING,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(f.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}if(J(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${n?"["+n.startSN+"-"+n.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),l(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=pr.FRAG_LOADING;const h=this.config.progressive;let d;return d=h&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,h?r:void 0),a]).then((([e])=>(!h&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(f.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,i,r){return new Promise(((s,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const n=r.part;this.hls.trigger(f.FRAG_LOADED,r);const a=or(i.details,e.sn,t.index+1)||lr(l,e.sn,t.index+1);if(!a)return s({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===c.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(f.ERROR,t)}else this.hls.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==pr.PARSING)return void(this.fragCurrent||this.state===pr.STOPPED||this.state===pr.ERROR||(this.state=pr.IDLE));const{frag:i,part:r,level:s}=t,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,r,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var i;const s=e.partList[0];if(t>=s.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)){var r;if((this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:n}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=a.details,l=n>-1?or(o,s,n):null,h=l?l.fragment:ar(o,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,i,r,s){var n;if(!e||this.state!==pr.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=Se(a,o)),null==(n=l)||!n.length)return;const h={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(f.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ei.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const i=t.currentTime,r=ei.bufferInfo(t,i,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,r.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const r=this.getLoadPosition();if(!l(r))return null;const s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,s)}getFwdBufferInfoAtPos(e,t,i,r){const s=ei.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(s.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(s.nextStart,n.end)-t,r);return ei.bufferInfo(e,t,i)}}return s}getMaxBufferLength(e){const{config:t}=this;let i;return i=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(e,t=y){var i;const r=null==(i=this.fragmentTracker)?void 0:i.getAppendedFrag(e,t);return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const i=t.fragments,r=i.length;if(!r)return null;const{config:s}=this,n=i[0].start,a=s.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const h=s.initialLiveManifestSize;if(r<h)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t,i);const r=this.hls.startPosition,s=this.hls.liveSyncPosition,h=o?(-1!==r&&r>=n?r:s)||o.start:e;this.log(`Setting startPosition to ${h} to match start frag at live edge. mainStart: ${r} liveSyncPosition: ${s} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=h}}else e<=n&&(o=i[0]);if(!o){const i=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,i,t)}let h=this.filterReplacedPrimary(o,t);if(!h&&o){const e=o.sn-t.startSN;h=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Mt||i===Ot&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,s){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==e&&i.len+e.len>=s){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(yr(this.hls.config)){var e,t;if(null==(e=this.hls.interstitialsManager)||null==(t=e.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(yr(this.hls.config)&&e.type!==T){const i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){const i=r.event;if(i){if(i.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}const s=null==i?void 0:i.playerQueue;if(s)for(let t=s.length;t--;){const i=s[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,r>-1&&i<o.start)break;const l=o.loaded;l?r=-1:(s||o.independent||n)&&o.fragment===t&&(r=a),s=l}return r}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!l(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r<e.length;++r){const s=e[r];if(vt(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){const n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=yt(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){const{config:r}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,h=i.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let u;if(d&&o&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var c;u=mt(s,n,e,e<this.lastCurrentTime||e>t-l||null!=(c=this.media)&&c.paused||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const e=u.sn-i.startSN,t=this.fragmentTracker.getState(u);if((t===Mt||t===Ot&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!d||h[0].fragment.sn>u.sn||!i.live&&!d)){if(s&&u.level===s.level){const t=n[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==Mt?t:null}}}return u}alignPlaylists(e,t,i){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,n=!t,a=e.alignedSliding&&l(s);if(n||!a&&!s){!function(e,t){e&&(fr(t,e),!t.alignedSliding&&e&&gr(t,e),t.alignedSliding||!e||t.skippedSegments||rr(e,t,!1))}(i,e);const s=e.fragmentStart;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),s}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const r=this.timelineOffset;if(-1===i){const s=null!==this.startTimeOffset,n=s?this.startTimeOffset:e.startTimeOffset;null!==n&&l(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}getLoadPosition(){var e;const{media:t}=this;let i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&J(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===pr.FRAG_LOADING_WAITING_RETRY)||(this.state=pr.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=t.details===c.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const n=t.errorAction,{action:a,flags:o,retryCount:l=0,retryConfig:h}=n||{},d=!!n&&!!h,u=d&&a===Dt,f=d&&!n.resolved&&o===_t;if(!u&&f&&J(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),n.resolved=!0;else if((u||f)&&l<h.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=St(h,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${h.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=pr.FRAG_LOADING_WAITING_RETRY}else if(h&&n){if(this.resetFragmentErrors(e),!(l<h.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${l})`);s||a===bt||(n.resolved=!0)}else this.state=a===It?pr.WAITING_LEVEL:pr.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===pr.PARSING||this.state===pr.PARSED){const t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===E&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==pr.STOPPED&&(this.state=pr.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const r=ei.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===pr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==pr.STOPPED&&(this.state=pr.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){const s=i.details;if(!s)return void this.warn("level.details undefined");var n;if(!Object.keys(e.elementaryStreams).reduce(((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=r?0:er(s,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(f.LEVEL_PTS_UPDATED,{details:s,level:i,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(n=this.transmuxer)?void 0:n.error))){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=pr.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(f.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===y?"level":"track"}fragInfo(e,t=!0,i){var r,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)}-${(null!=(s=t&&!i?e.endPTS:(i||e).end)?s:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function yr(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class Er{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){const s=e[t];i.set(s,r),r+=s.length}return i}(e,t),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Tr,Sr={exports:{}};var Ar=(Tr||(Tr=1,function(module){var e=Object.prototype.hasOwnProperty,t="~";function i(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,i,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||e,a),l=t?t+i:i;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(t=!1)),a.prototype.eventNames=function(){var i,r,s=[];if(0===this._eventsCount)return s;for(r in i=this._events)e.call(i,r)&&s.push(t?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(i)):s},a.prototype.listeners=function(e){var i=t?t+e:e,r=this._events[i];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},a.prototype.listenerCount=function(e){var i=t?t+e:e,r=this._events[i];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,i,r,s,n,a){var o=t?t+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,r),!0;case 4:return d.fn.call(d.context,i,r,s),!0;case 5:return d.fn.call(d.context,i,r,s,n),!0;case 6:return d.fn.call(d.context,i,r,s,n,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,i);break;case 3:d[h].fn.call(d[h].context,i,r);break;case 4:d[h].fn.call(d[h].context,i,r,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,i,r,s){var a=t?t+e:e;if(!this._events[a])return this;if(!i)return n(this,a),this;var o=this._events[a];if(o.fn)o.fn!==i||s&&!o.once||r&&o.context!==r||n(this,a);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==i||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},a.prototype.removeAllListeners=function(e){var r;return e?(r=t?t+e:e,this._events[r]&&n(this,r)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,module.exports=a}(Sr)),Sr.exports),Lr=U(Ar);const Rr="1.6.2",Ir={};function br(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Dr(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function kr(e,t){let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i}function _r(e,t){const i=t;let r=0;for(;Dr(e,t);){r+=10;r+=kr(e,t+6),br(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)}function Pr(e,t){return 255===e[t]&&240==(246&e[t+1])}function Cr(e,t){return 1&e[t+1]?7:9}function wr(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function xr(e,t){return t+1<e.length&&Pr(e,t)}function Or(e,t){if(xr(e,t)){const i=Cr(e,t);if(t+i>=e.length)return!1;const r=wr(e,t);if(r<=i)return!1;const s=t+r;return s===e.length||xr(e,s)}return!1}function Mr(e,t,i,r,s){if(!e.samplerate){const n=function(e,t,i,r){const s=t[i+2],n=s>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(f.ERROR,f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(s>>6&3),o=t[i+3]>>6&3|(1&s)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d=n;5!==a&&29!==a||(d-=3);const g=[a<<3|(14&d)>>1,(1&d)<<7|o<<3];return x.log(`manifest codec:${r}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:g,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:r}}(t,i,r,s);if(!n)return;R(e,n)}}function Fr(e){return 9216e4/e}function Nr(e,t,i,r,s){const n=r+s*Fr(e.samplerate),a=function(e,t){const i=Cr(e,t);if(t+i<=e.length){const r=wr(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,h=Math.max(0,i+l-t.length);h?(o=new Uint8Array(l-s),o.set(t.subarray(i+s,t.length),0)):o=t.subarray(i+s,i+l);const d={unit:o,pts:n};return h||e.samples.push(d),{sample:d,length:l,missing:h}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Ur(e,t){return Dr(e,t)&&kr(e,t+6)+10<=e.length-t}function Br(e,t){if(e<0)return-Br(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){const t=Math.floor(e*i);return(t%2==0?t:t+1)/i}return Math.round(e*i)/i}function Gr(e,t=0,i=1/0){return function(e,t,i,r){const s=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);const a=(u=e,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/n,l=(a+t)/n,h=Math.floor(Math.max(0,Math.min(l,o))),d=Math.floor(Math.min(h+Math.max(i,0),o));var u;return new r(s,h,d-h)}(e,t,i,Uint8Array)}function $r(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=e.data.subarray(1).indexOf(0);if(-1===i)return;const r=F(Gr(e.data,1,i)),s=e.data[2+i],n=e.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=F(Gr(e.data,3+i,n));let o;return o="--\x3e"===r?F(Gr(e.data,4+i+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+n)),t.mimeType=r,t.pictureType=s,t.description=a,t.data=o,t}function Kr(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=F(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=F(e.data.subarray(t),!0);t+=i.length+1;const r=F(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=F(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?$r(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=F(e.data.subarray(t),!0);t+=i.length+1;const r=F(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=F(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function Vr(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=kr(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}const Hr=10,Yr=10;function Wr(e){let t=0;const i=[];for(;Dr(e,t);){const r=kr(e,t+6);e[t+5]>>6&1&&(t+=Hr),t+=Hr;const s=t+r;for(;t+Yr<s;){const r=Vr(e.subarray(t)),s=Kr(r);s&&i.push(s),t+=r.size+Hr}br(e,t)&&(t+=Hr)}return i}function jr(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function qr(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Xr(e){const t=Wr(e);for(let e=0;e<t.length;e++){const i=t[e];if(jr(i))return qr(i)}}let Qr=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function zr(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Jr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Se(this.cachedData,e),this.cachedData=null);let i,r=_r(e,0),s=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?Xr(r):void 0,h=e.length;for((null===this.basePTS||0===this.frameIndex&&l(o))&&(this.basePTS=Zr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Qr.audioId3,duration:Number.POSITIVE_INFINITY});s<h;){if(this.canParse(e,s)){const t=this.appendFrame(n,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,i=s):s=h}else Ur(e,s)?(r=_r(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Qr.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++;if(s===h&&i!==h){const t=e.slice(i);this.cachedData?this.cachedData=Se(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:zr(),id3Track:a,textTrack:zr()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:zr(),id3Track:this._id3Track,textTrack:zr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Zr=(e,t,i)=>{if(l(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};let es=null;const ts=[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],is=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],rs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ss=[0,1,1,4];function ns(e,t,i,r,s){if(i+24>t.length)return;const n=as(t,i);if(n&&i+n.frameLength<=t.length){const a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function as(e,t){const i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*ts[14*(3===i?3-r:3===r?3:4)+s-1],h=is[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,u=rs[i][r],c=ss[r],f=8*u*c,g=Math.floor(u*l/h+a)*c;if(null===es){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);es=e?parseInt(e[1]):0}return!!es&&es<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function os(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function ls(e,t){return t+1<e.length&&os(e,t)}function hs(e,t){if(t+1<e.length&&os(e,t)){const i=4,r=as(e,t);let s=i;null!=r&&r.frameLength&&(s=r.frameLength);const n=t+s;return n===e.length||ls(e,n)}return!1}const ds=(e,t)=>{let i=0,r=5;t+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=e[t];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],t+=1,r-=o}return i};class us extends Jr{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const r=cs(e,t,i,this.basePTS,this.frameIndex);if(-1!==r){return{sample:e.samples[e.samples.length-1],length:r,missing:0}}}static probe(e){if(!e)return!1;const t=_r(e,0);if(!t)return!1;const i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Xr(t)&&ds(e,i)<16}}function cs(e,t,i,r,s){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;const h=t[i+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const u=(t[i+6]<<8|t[i+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][h]+u,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=m,e.channelCount=c,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}const fs=/\/emsg[-/]ID3/i;function gs(e,t){return l(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class ms{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Yt(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Gt)}decryptAacSample(e,t,i){const r=e[t].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}))}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)i.set(e.subarray(t,t+16),r);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(i.subarray(r,r+16),t);return e}decryptAvcSample(e,t,i,r,s){const n=be(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}))}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();const s=e[t].units;for(;!(i>=s.length);i++){const n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}}}class ps{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,r=i.length;if(!r)return void t.dropped++;{const t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){const r=t.byteLength;let s=e.naluState||0;const n=s,a=[];let o,l,h,d=0,u=-1,c=0;for(-1===s&&(u=0,c=this.getNALuType(t,0),s=0,d=1);d<r;)if(o=t[d++],s)if(1!==s)if(o)if(1===o){if(l=d-s-1,u>=0){const e={data:t.subarray(u,l),type:c};a.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(n&&d<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=Se(i.data,t.subarray(0,l)),i.state=0))}d<r?(h=this.getNALuType(t,d),u=d,c=h,s=0):s=-1}else s=0;else s=3;else s=o?0:2;else s=o?0:1;if(u>=0&&s>=0){const e={data:t.subarray(u,r),type:c,state:s};a.push(e)}if(0===a.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=Se(i.data,t))}return e.naluState=s,a}}class vs{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&x.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class ys extends ps{parsePES(e,t,i,r){const s=this.parseNALu(e,i.data,r);let n,a=this.VideoSample,o=!1;i.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach((r=>{var s,l;switch(r.type){case 1:{let t=!1;n=!0;const s=r.data;if(o&&s.length>4){const e=this.readSliceType(s);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Ie(r.data,1,i.pts,t.samples);break;case 7:{var d,u;n=!0,o=!0;const t=r.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(d=e.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];const r=t.subarray(1,4);let s="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),s+=t}e.codec=s}break}case 8:n=!0,e.pps=[r.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new vs(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i,r=8,s=8;for(let n=0;n<e;n++)0!==s&&(i=t.readEG(),s=(r+i+256)%256),r=0===s?r:s}readSPS(e){const t=new vs(e);let i,r,s,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),d=t.readBits.bind(t),u=t.readUEG.bind(t),c=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=u();if(3===e&&f(1),m(),m(),f(1),c())for(r=3!==e?8:12,s=0;s<r;s++)c()&&p(s<6?16:64,t)}m();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),i=u(),s=0;s<i;s++)g();m(),f(1);const E=u(),T=u(),S=d(1);0===S&&f(1),f(1),c()&&(n=u(),a=u(),o=u(),l=u());let A=[1,1];if(c()&&c()){switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class Es extends ps{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,r){const s=this.parseNALu(e,i.data,r);let n,a=this.VideoSample,o=!1;i.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach((r=>{var s,l;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Ie(r.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=R(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],r.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const i in t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,r.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(r.data);for(const i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new vs(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new vs(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const r=t.readBits(2),s=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=[],y=[];for(let e=0;e<i;e++)v.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const E=t.readUEG();3==E&&t.skipBits(1);const T=t.readUEG(),S=t.readUEG(),A=t.readBoolean();let L=0,R=0,I=0,b=0;A&&(L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG(),b+=t.readUEG());const D=t.readUEG(),k=t.readUEG(),_=t.readUEG();for(let e=t.readBoolean()?0:i;e<=i;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++){if(t.readBoolean()){const i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const P=t.readUEG();let C=0;for(let e=0;e<P;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===P&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=C;e++){const e=t.readBoolean();let r=!1;e||(r=t.readBoolean()),(e||r)&&i++}C=i}else{const e=t.readUEG(),i=t.readUEG();C=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<_+4;e++)t.readBits(1);t.readBits(1)}}let w=0,x=1,O=1,M=!0,F=1,N=0;t.readBoolean(),t.readBoolean();let U=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],O=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(x=t.readBits(16),O=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readBoolean(),U&&(L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG(),b+=t.readUEG());if(t.readBoolean()){F=t.readBits(32),N=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),r=t.readBoolean();let s=!1;(e||r)&&(s=t.readBoolean(),s&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=i;n++){M=t.readBoolean();let i=!1;M||t.readBoolean()?t.readEG():i=t.readBoolean();const n=i?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),s&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),s&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),w=t.readUEG())}let B=T,G=S;if(A||U){let e=1,t=1;1===E?e=t=2:2==E&&(e=2),B=T-e*R-e*L,G=S-t*b-t*I}const $=r?["A","B","C"][r]:"",K=a<<24|o<<16|l<<8|h;let V=0;for(let e=0;e<32;e++)V=(V|(K>>e&1)<<31-e)>>>0;let H=V.toString(16);1===n&&"2"===H&&(H="6");return{codecString:`hvc1.${$}${n}.${H}.${s?"H":"L"}${p}.B0`,params:{general_tier_flag:s,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,u,c,f,g,m],general_level_idc:p,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:w,chroma_format_idc:E,frame_rate:{fixed:M,fps:N/F}},width:B,height:G,pixelRatio:[x,O]}}readPPS(e){const t=new vs(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Ts=188;class Ss{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(e,t){const i=Ss.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let i=Math.min(940,t-Ts)+1,r=0;for(;r<i;){let s=!1,n=-1,a=0;for(let o=r;o<t;o+=Ts){if(71!==e[o]||t-o!==Ts&&71!==e[o+Ts]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,e.length-Ts)+1)),s||(s=0===As(e,o)),s&&a>1&&(0===n&&a>2||o+Ts>i))return n}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:se[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ss.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=Ss.createTrack("audio",r),this._id3Track=Ss.createTrack("id3"),this._txtTrack=Ss.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){let s;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,u=a.pid,c=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Se(this.remainderData,e)).length,this.remainderData=null),y<Ts&&!r)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,Ss.syncOffset(e));y-=(y-E)%Ts,y<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let T=0;for(let t=E;t<y;t+=Ts)if(71===e[t]){const r=!!(64&e[t+1]),y=As(e,t);let T;if((48&e[t+3])>>4>1){if(T=t+5+e[t+4],T===t+Ts)continue}else T=t+4;switch(y){case h:if(r){if(d&&(s=Ds(d,this.logger))){if(null===this.videoParser)switch(n.segmentCodec){case"avc":this.videoParser=new ys;break;case"hevc":this.videoParser=new Es}null!==this.videoParser&&this.videoParser.parsePES(n,l,s,!1)}d={data:[],size:0}}d&&(d.data.push(e.subarray(T,t+Ts)),d.size+=t+Ts-T);break;case u:if(r){if(f&&(s=Ds(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(T,t+Ts)),f.size+=t+Ts-T);break;case c:r&&(g&&(s=Ds(g,this.logger))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(T,t+Ts)),g.size+=t+Ts-T);break;case 0:r&&(T+=e[T]+1),v=this._pmtId=Ls(e,T);break;case v:{r&&(T+=e[T]+1);const s=Rs(e,T,this.typeSupported,i,this.observer,this.logger);h=s.videoPid,h>0&&(n.pid=h,n.segmentCodec=s.segmentVideoCodec),u=s.audioPid,u>0&&(a.pid=u,a.segmentCodec=s.segmentAudioCodec),c=s.id3Pid,c>0&&(o.pid=c),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,t=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&Is(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:r,textTrack:s}=e,n=i.pesData,a=t.pesData,o=r.pesData;let l;if(n&&(l=Ds(n,this.logger))){if(null===this.videoParser)switch(i.segmentCodec){case"avc":this.videoParser=new ys;break;case"hevc":this.videoParser=new Es}null!==this.videoParser&&(this.videoParser.parsePES(i,s,l,!0),i.pesData=null)}else i.pesData=n;if(a&&(l=Ds(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Ds(o,this.logger))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,i){const r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new ms(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise((i=>{const{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const r=this.aacOverFlow;let s,n,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t)o=Se(r.sample.unit,o);else{const n=s-t;r.sample.unit.set(o.subarray(0,t),n),e.samples.push(r.sample),i=r.missing}}for(s=i,n=o.length;s<n-1&&!xr(o,s);s++);if(s!==i){let e;const t=s<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",Is(this.observer,new Error(e),t,this.logger),!t)return}if(Mr(e,this.observer,o,s,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Fr(e.samplerate);a=r.sample.pts+t}}let l,h=0;for(;s<n;){if(l=Nr(e,o,s,a,h),s+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;s<n-1&&!xr(o,s);s++);}}parseMPEGPES(e,t){const i=t.data,r=i.length;let s=0,n=0;const a=t.pts;if(void 0!==a)for(;n<r;)if(ls(i,n)){const t=ns(e,i,n,a,s);if(!t)break;n+=t.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const i=t.data,r=t.pts;if(void 0===r)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const s=i.length;let n,a=0,o=0;for(;o<s&&(n=cs(e,i,o,r,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=R({},t,{type:this._videoTrack?Qr.emsg:Qr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function As(e,t){return((31&e[t+1])<<8)+e[t+2]}function Ls(e,t){return(31&e[t+10])<<8|e[t+11]}function Rs(e,t,i,r,s,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=As(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){bs("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!r){bs("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){bs("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let r=t+5,s=l;for(;s>2;){if(106===e[r])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return Is(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function Is(e,t,i,r){r.warn(`parsing error: ${t.message}`),e.emit(f.ERROR,f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function bs(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Ds(e,t){let i,r,s,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Se(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(r=(i[4]<<8)+i[5],r&&r>e.size-6)return null;const h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=i[8];let d=s+9;if(e.size<=d)return null;e.size-=d;const u=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){i=l[e];let t=i.byteLength;if(d){if(d>t){d-=t;continue}i=i.subarray(d),t-=d,d=0}u.set(i,o),o+=t}return r&&(r-=s+3),{data:u,pts:n,dts:a,len:r}}return null}class ks{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const _s=Math.pow(2,32)-1;class Ps{static init(){let e;for(e in Ps.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:[]},Ps.types)Ps.types.hasOwnProperty(e)&&(Ps.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),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]);Ps.HDLR_TYPES={video:t,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Ps.STTS=Ps.STSC=Ps.STCO=s,Ps.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ps.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ps.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ps.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Ps.FTYP=Ps.box(Ps.types.ftyp,n,o,n,a),Ps.DINF=Ps.box(Ps.types.dinf,Ps.box(Ps.types.dref,r))}static box(e,...t){let i=8,r=t.length;const s=r;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r<s;r++)n.set(t[r],i),i+=t[r].byteLength;return n}static hdlr(e){return Ps.box(Ps.types.hdlr,Ps.HDLR_TYPES[e])}static mdat(e){return Ps.box(Ps.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(_s+1)),r=Math.floor(t%(_s+1));return Ps.box(Ps.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return Ps.box(Ps.types.mdia,Ps.mdhd(e.timescale||0,e.duration||0),Ps.hdlr(e.type),Ps.minf(e))}static mfhd(e){return Ps.box(Ps.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Ps.box(Ps.types.minf,Ps.box(Ps.types.smhd,Ps.SMHD),Ps.DINF,Ps.stbl(e)):Ps.box(Ps.types.minf,Ps.box(Ps.types.vmhd,Ps.VMHD),Ps.DINF,Ps.stbl(e))}static moof(e,t,i){return Ps.box(Ps.types.moof,Ps.mfhd(e),Ps.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Ps.trak(e[t]);return Ps.box.apply(null,[Ps.types.moov,Ps.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Ps.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Ps.trex(e[t]);return Ps.box.apply(null,[Ps.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(_s+1)),r=Math.floor(t%(_s+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Ps.box(Ps.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let r,s;for(r=0;r<t.length;r++)s=t[r].flags,i[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return Ps.box(Ps.types.sdtp,i)}static stbl(e){return Ps.box(Ps.types.stbl,Ps.stsd(e),Ps.box(Ps.types.stts,Ps.STTS),Ps.box(Ps.types.stsc,Ps.STSC),Ps.box(Ps.types.stsz,Ps.STSZ),Ps.box(Ps.types.stco,Ps.STCO))}static avc1(e){let t,i,r,s=[],n=[];for(t=0;t<e.sps.length;t++)i=e.sps[t],r=i.byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)i=e.pps[t],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));const a=Ps.box(Ps.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return Ps.box(Ps.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Ps.box(Ps.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ps.box(Ps.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return Ps.box(Ps.types.mp4a,Ps.audioStsd(e),Ps.box(Ps.types.esds,Ps.esds(e)))}static mp3(e){return Ps.box(Ps.types[".mp3"],Ps.audioStsd(e))}static ac3(e){return Ps.box(Ps.types["ac-3"],Ps.audioStsd(e),Ps.box(Ps.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return Ps.box(Ps.types.stsd,Ps.STSD,Ps.mp4a(e));if("ac3"===t&&e.config)return Ps.box(Ps.types.stsd,Ps.STSD,Ps.ac3(e));if("mp3"===t&&"mp3"===e.codec)return Ps.box(Ps.types.stsd,Ps.STSD,Ps.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return Ps.box(Ps.types.stsd,Ps.STSD,Ps.avc1(e));if("hevc"===t&&e.vps)return Ps.box(Ps.types.stsd,Ps.STSD,Ps.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,s=e.height||0,n=Math.floor(i/(_s+1)),a=Math.floor(i%(_s+1));return Ps.box(Ps.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const i=Ps.sdtp(e),r=e.id,s=Math.floor(t/(_s+1)),n=Math.floor(t%(_s+1));return Ps.box(Ps.types.traf,Ps.box(Ps.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Ps.box(Ps.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),Ps.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Ps.box(Ps.types.trak,Ps.tkhd(e),Ps.mdia(e))}static trex(e){const t=e.id;return Ps.box(Ps.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],r=i.length,s=12+16*r,n=new Uint8Array(s);let a,o,l,h,d,u;for(t+=8+s,n.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<r;a++)o=i[a],l=o.duration,h=o.size,d=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Ps.box(Ps.types.trun,n)}static initSegment(e){Ps.types||Ps.init();const t=Ps.moov(e);return Se(Ps.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let s=r.length;for(let e=0;e<i.length;e+=1){s+=3;for(let t=0;t<i[e].length;t+=1)s+=2+i[e][t].length}const n=new Uint8Array(s);n.set(r,0),s=r.length;const a=i.length-1;for(let e=0;e<i.length;e+=1){n.set(new Uint8Array([32+e|(e===a?128:0),0,i[e].length]),s),s+=3;for(let t=0;t<i[e].length;t+=1)n.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),s),s+=2,n.set(i[e][t],s),s+=i[e][t].length}const o=Ps.box(Ps.types.hvcC,n),l=e.width,h=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return Ps.box(Ps.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,Ps.box(Ps.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ps.box(Ps.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))}}Ps.types=void 0,Ps.HDLR_TYPES=void 0,Ps.STTS=void 0,Ps.STSC=void 0,Ps.STCO=void 0,Ps.STSZ=void 0,Ps.VMHD=void 0,Ps.SMHD=void 0,Ps.STSD=void 0,Ps.FTYP=void 0,Ps.DINF=void 0;const Cs=9e4;function ws(e,t,i=1,r=!1){const s=e*t*i;return r?Math.round(s):s}function xs(e,t=!1){return ws(e,1e3,1/Cs,t)}let Os,Ms=null,Fs=null;function Ns(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Us{constructor(e,t,i,r){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.ISGenerated=!1,null===Ms){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ms=e?parseInt(e[1]):0}if(null===Fs){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Fs=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,r=e.reduce(((e,r)=>{let s=r.pts,n=s-e;return n<-4294967296&&(t=!0,s=Bs(s,i),n=s-e),n>0?e:s}),i);return t&&this.logger.debug("PTS rollover detected"),r}remux(e,t,i,r,s,n,a,o){let l,h,d,u,c,f,g=s,m=s;const p=e.pid>-1,v=t.pid>-1,y=t.samples.length,T=e.samples.length>0,S=a&&y>0||y>1;if((!p||T)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var A,L,R,I;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(A=t.pixelRatio)?void 0:A[0])!==(null==(L=e.pixelRatio)?void 0:L[0])||(null==(R=t.pixelRatio)?void 0:R[1])!==(null==(I=e.pixelRatio)?void 0:I[1]))||!e&&S||null===this.nextAudioPts&&T)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,s,n));const i=this.isVideoContiguous;let r,a=-1;if(S&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.logger.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,r=m}else-1===a&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const i=this.getVideoStartPts(t.samples),r=(Bs(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(T){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||S||o===E?m:void 0),S){const r=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,m,i,r)}}else S&&(l=this.remuxVideo(t,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=Gs(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=$s(r,s,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:u,id3:c}}generateIS(e,t,i,r){const s=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,u,c=!l||r,f="audio/mp4";if(c&&(h=d=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Ps.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(u=e.inputTimeScale,l&&u===l.timescale?c=!1:h=d=s[0].pts-Math.round(u*i))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ps.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(u=t.inputTimeScale,l&&u===l.timescale)c=!1;else{const e=this.getVideoStartPts(n),t=Math.round(u*i);d=Math.min(d,Bs(n[0].dts,e)-t),h=Math.min(h,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:h,timescale:u},this._initDTS={baseTime:d,timescale:u}):h=u=void 0,{tracks:o,initPTS:h,timescale:u}}remuxVideo(e,t,i,r){const s=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS;let h,d,g=this.nextAvcDts,m=8,p=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=!1;if(!i||null===g){const e=t*s,r=n[0].pts-Bs(n[0].dts,n[0].pts);Ms&&null!==g&&Math.abs(e-r-g)<15e3?i=!0:g=e-r}const T=l.baseTime*s/l.timescale;for(let e=0;e<o;e++){const t=n[e];t.pts=Bs(t.pts-T,g),t.dts=Bs(t.dts-T,g),t.dts<n[e>0?e-1:e].dts&&(E=!0)}E&&n.sort((function(e,t){const i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),h=n[0].dts,d=n[n.length-1].dts;const S=d-h,A=S?Math.round(S/(o-1)):p||e.inputTimeScale/30;if(i){const i=h-g,r=i>A,s=i<-1;if((r||s)&&(r?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${xs(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${xs(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!s||g>=n[0].pts||Ms)){h=g;const e=n[0].pts-i;if(r)n[0].dts=h,n[0].pts=e;else{let t=!0;for(let r=0;r<n.length&&!(n[r].dts>e&&t);r++){const e=n[r].pts;if(n[r].dts-=i,n[r].pts-=i,r<n.length-1){const i=n[r+1].pts;t=i<=n[r].pts==i<=e}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${xs(e,!0)}/${xs(h,!0)}, delta: ${xs(i,!0)} ms`)}}h=Math.max(0,h);let L=0,I=0,b=h;for(let e=0;e<o;e++){const t=n[e],i=t.units,r=i.length;let s=0;for(let e=0;e<r;e++)s+=i[e].data.length;I+=s,L+=r,t.length=s,t.dts<b?(t.dts=b,b+=A/4|0||1):b=t.dts,v=Math.min(t.pts,v),y=Math.max(t.pts,y)}d=n[o-1].dts;const D=I+4*L+8;let k;try{k=new Uint8Array(D)}catch(e){return void this.observer.emit(f.ERROR,f.ERROR,{type:u.MUX_ERROR,details:c.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:D,reason:`fail allocating video mdat ${D}`})}const _=new DataView(k.buffer);_.setUint32(0,D),k.set(Ps.types.mdat,4);let P=!1,C=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],i=t.units;let l,h=0;for(let e=0,t=i.length;e<t;e++){const t=i[e],r=t.data,s=t.data.byteLength;_.setUint32(m,s),m+=4,k.set(r,m),m+=s,h+=4+s}if(e<o-1)p=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const i=this.config,a=e>0?t.dts-n[e-1].dts:A;if(l=e>0?t.pts-n[e-1].pts:A,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(i.maxBufferHole*s),n=(r?v+r*s:this.nextAudioPts)-t.pts;n>e?(p=n-a,p<0?p=a:P=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=a}else p=a}const d=Math.round(t.pts-t.dts);C=Math.min(C,p),x=Math.max(x,p),w=Math.min(w,l),O=Math.max(O,l),a.push(Ns(t.key,p,h,d))}if(a.length)if(Ms){if(Ms<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Fs&&O-w<x-C&&A/x<.025&&0===a[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=h;for(let t=0,i=a.length;t<i;t++){const r=e+a[t].duration,s=e+a[t].cts;if(t<i-1){const e=r+a[t+1].cts;a[t].duration=e-s}else a[t].duration=t?a[t-1].duration:A;a[t].cts=0,e=r}}p=P||!p?A:p,this.nextAvcDts=g=d+p,this.videoSampleDuration=p,this.isVideoContiguous=!0;const M={data1:Ps.moof(e.sequenceNumber++,h,R(e,{samples:a})),data2:k,startPTS:v/s,endPTS:(y+p)/s,startDTS:h/s,endDTS:g/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,M}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,r,s){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,g=[],m=void 0!==s;let p=e.samples,v=d?0:8,y=this.nextAudioPts||-1;const E=t*n,T=h.baseTime*n/h.timescale;if(this.isAudioContiguous=i=i||p.length&&y>0&&(r&&Math.abs(E-y)<9e3||Math.abs(Bs(p[0].pts-T,E)-y)<20*l),p.forEach((function(e){e.pts=Bs(e.pts-T,E)})),!i||y<0){if(p=p.filter((e=>e.pts>=0)),!p.length)return;y=0===s?0:r&&!m?Math.max(0,E):p[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,r=y;i<p.length;i++){const s=p[i],a=s.pts,o=a-r,h=Math.abs(1e3*o/n);if(o<=-t*l&&m)0===i&&(this.logger.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=y=r=a);else if(o>=t*l&&h<1e4&&m){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===i&&(this.nextAudioPts=y=r),this.logger.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){const t=Math.max(r,0);let n=ks.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);n||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=s.unit.subarray()),p.splice(i,0,{unit:n,pts:t}),r+=l,i++}}s.pts=r,r+=l}}let S,A=null,L=null,I=0,b=p.length;for(;b--;)I+=p[b].unit.byteLength;for(let t=0,r=p.length;t<r;t++){const r=p[t],s=r.unit;let n=r.pts;if(null!==L){g[t-1].duration=Math.round((n-L)/a)}else{if(i&&"aac"===e.segmentCodec&&(n=y),A=n,!(I>0))return;I+=v;try{S=new Uint8Array(I)}catch(e){return void this.observer.emit(f.ERROR,f.ERROR,{type:u.MUX_ERROR,details:c.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:I,reason:`fail allocating audio mdat ${I}`})}if(!d){new DataView(S.buffer).setUint32(0,I),S.set(Ps.types.mdat,4)}}S.set(s,v);const l=s.byteLength;v+=l,g.push(Ns(!0,o,l,0)),L=n}const D=g.length;if(!D)return;const k=g[g.length-1];this.nextAudioPts=y=L+a*k.duration;const _=d?new Uint8Array(0):Ps.moof(e.sequenceNumber++,A/a,R({},e,{samples:g}));e.samples=[];const P=A/n,C=y/n,w={data1:_,data2:S,startPTS:P,endPTS:C,startDTS:P,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,w}}function Bs(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function Gs(e,t,i,r){const s=e.samples.length;if(!s)return;const n=e.inputTimeScale;for(let a=0;a<s;a++){const s=e.samples[a];s.pts=Bs(s.pts-i.baseTime*n/i.timescale,t*n)/n,s.dts=Bs(s.dts-r.baseTime*n/r.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function $s(e,t,i){const r=e.samples.length;if(!r)return;const s=e.inputTimeScale;for(let n=0;n<r;n++){const r=e.samples[n];r.pts=Bs(r.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort(((e,t)=>e.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}function Ks(e,t){const i=null==e?void 0:e.codec;if(i&&i.length>4)return i;if(t===q){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Be(i,!1)}return x.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return x.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{Os=self.performance.now.bind(self.performance)}catch(e){Os=Date.now}const Vs=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){const s=this.videoTrack=zr("video",1),n=this.audioTrack=zr("audio",1),a=this.txtTrack=zr("text",1);if(this.id3Track=zr("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=fe(e);if(o.video){const{id:e,timescale:t,codec:i,supplemental:r}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=i,s.supplemental=r}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=se.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i<t;){const r=oe(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Se(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=ue(e,["moof"]);if(i.length<2)return t.remainder=e,t;const r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;const n=this.extractID3Track(r,t);return s.samples=Ae(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return i.samples=Ae(e,t),{videoTrack:t,audioTrack:zr(),id3Track:r,textTrack:zr()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const r=ue(e.samples,["emsg"]);r&&r.forEach((e=>{const r=function(e){const t=e[0];let i="",r="",s=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==ne(e.subarray(d,d+1));)i+=ne(e.subarray(d,d+1)),d+=1;for(i+=ne(e.subarray(d,d+1)),d+=1;"\0"!==ne(e.subarray(d,d+1));)r+=ne(e.subarray(d,d+1)),d+=1;r+=ne(e.subarray(d,d+1)),d+=1,s=oe(e,12),n=oe(e,16),o=oe(e,20),l=oe(e,24),d=28}else if(1===t){d+=4,s=oe(e,d),d+=4;const t=oe(e,d);d+=4;const n=oe(e,d);for(d+=4,a=2**32*t+n,h(a)||(a=Number.MAX_SAFE_INTEGER,x.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=oe(e,d),d+=4,l=oe(e,d),d+=4;"\0"!==ne(e.subarray(d,d+1));)i+=ne(e.subarray(d,d+1)),d+=1;for(i+=ne(e.subarray(d,d+1)),d+=1;"\0"!==ne(e.subarray(d,d+1));)r+=ne(e.subarray(d,d+1)),d+=1;r+=ne(e.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}(e);if(fs.test(r.schemeIdUri)){const e=gs(r,t);let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:Qr.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=gs(r,t);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:Qr.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class{constructor(e,t,i,r){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=r}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;const i=t.keyId;i&&t.isCommonEncryption&&ue(e,["moov","trak"]).forEach((e=>{const t=ue(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=ue(t,["enca"]);const s=r.length>0;s||(r=ue(t,["encv"])),r.forEach((e=>{ue(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=Ee(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(x.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${N.hexDump(e)} -> ${N.hexDump(i)}`),t.set(i,8))}}))}))}));return e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=fe(e);r.audio&&(t=Ks(r.audio,q)),r.video&&(i=Ks(r.video,X));const s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,r,s,n){var a,o;let{initPTS:h,lastEndTime:d}=this;const u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};l(d)||(d=this.lastEndTime=s||0);const c=t.samples;if(null==c||!c.length)return u;const f={initPTS:void 0,timescale:1};let g=this.initData;if(null!=(a=g)&&a.length||(this.generateInitSegment(c),g=this.initData),null==(o=g)||!o.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(e,t){let i=0,r=0,s=0;const n=ue(e,["moof","traf"]);for(let e=0;e<n.length;e++){const a=n[e],o=ue(a,["tfhd"])[0],l=t[oe(o,4)];if(!l)continue;const h=l.default,d=oe(o,0)|(null==h?void 0:h.flags);let u=null==h?void 0:h.duration;8&d&&(u=oe(o,2&d?12:8));const c=l.timescale||9e4,f=ue(a,["trun"]);for(let e=0;e<f.length;e++)i=Te(f[e]),!i&&u&&(i=u*oe(f[e],4)),l.type===X?r+=i/c:l.type===q&&(s+=i/c)}if(0===r&&0===s){let t=1/0,i=0,r=0;const s=ue(e,["sidx"]);for(let e=0;e<s.length;e++){const n=ce(s[e]);if(null!=n&&n.references){t=Math.min(t,n.earliestPresentationTime/n.timescale);const e=n.references.reduce(((e,t)=>e+t.info.duration||0),0);i=Math.max(i,e+n.earliestPresentationTime/n.timescale),r=i-t}}if(r&&l(r))return r}return r||s}(c,g),p=function(e,t){return ue(t,["moof","traf"]).reduce(((t,i)=>{const r=ue(i,["tfdt"])[0],s=r[0],n=ue(i,["tfhd"]).reduce(((t,i)=>{const n=oe(i,4),a=e[n];if(a){let e=oe(r,4);if(1===s){if(e===ie)return x.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=ie+1,e+=oe(r,8)}const i=e/(a.timescale||9e4);if(l(i)&&(null===t||i<t))return i}return t}),null);return null!==n&&l(n)&&(null===t||n<t)?n:t}),null)}(g,c),v=null===p?s:p;!n&&h||!function(e,t,i,r){if(null===e)return!0;const s=Math.max(r,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>s}(h,v,s,m)&&f.timescale===h.timescale||(f.initPTS=v-s,h&&1===h.timescale&&this.logger.warn(`Adjusting initPTS @${s} from ${h.baseTime/h.timescale} to ${f.initPTS}`),this.initPTS=h={baseTime:f.initPTS,timescale:1});const y=e?v-h.baseTime/h.timescale:d,E=y+m;!function(e,t,i){ue(t,["moof","traf"]).forEach((t=>{ue(t,["tfhd"]).forEach((r=>{const s=oe(r,4),n=e[s];if(!n)return;const a=n.timescale||9e4;ue(t,["tfdt"]).forEach((e=>{const t=e[0],r=i*a;if(r){let i=oe(e,4);if(0===t)i-=r,i=Math.max(i,0),de(e,4,i);else{i*=Math.pow(2,32),i+=oe(e,8),i-=r,i=Math.max(i,0);const t=Math.floor(i/(ie+1)),s=Math.floor(i%(ie+1));de(e,4,t),de(e,8,s)}}}))}))}))}(g,c,h.baseTime/h.timescale),m>0?this.lastEndTime=E:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!g.audio,S=!!g.video;let A="";T&&(A+="audio"),S&&(A+="video");const L={data1:c,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:A,hasAudio:T,hasVideo:S,nb:1,dropped:0};return u.audio="audio"===L.type?L:void 0,u.video="audio"!==L.type?L:void 0,u.initSegment=f,u.id3=Gs(i,s,h,h),r.samples.length&&(u.text=$s(r,s,h)),u}}},{demux:Ss,remux:Us},{demux:class extends Jr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=_r(e,0);let r=(null==i?void 0:i.length)||0;if(hs(e,r))return!1;for(let i=e.length;r<i;r++)if(Or(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Pr(e,t)&&wr(e,t)<=e.length-t}(e,t)}appendFrame(e,t,i){Mr(e,this.observer,t,i,e.manifestCodec);const r=Nr(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:Us},{demux:class extends Jr{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=_r(e,0);let i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Xr(t)&&ds(e,i)<=16)return!1;for(let t=e.length;i<t;i++)if(hs(e,i))return x.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return os(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,i){if(null!==this.basePTS)return ns(e,t,i,this.basePTS,this.frameIndex)}},remux:Us}];Vs.splice(2,0,{demux:us,remux:Us});class Hs{constructor(e,t,i,r,s,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){const s=i.transmuxing;s.executeStart=Os();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=r||a,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=o,A=function(e,t){let i=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(A&&ci(A.method)){const e=this.getDecrypter(),t=fi(A.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer,t).then((e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t})),this.decryptionPromise;{let r=e.softwareDecrypt(n,A.key.buffer,A.iv.buffer,t);if(i.part>-1){const t=e.flush();r=t?t.buffer:t}if(!r)return s.executeEnd=Os(),Ys(i);n=new Uint8Array(r)}}const L=this.needsProbing(h,d);if(L){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(f.ERROR,f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=Os(),Ys(i)}(h||d||p||L)&&this.resetInitSegment(S,v,y,T,t),(h||p||L)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const R=this.transmux(n,A,m,g,i);this.asyncResult=Ws(R);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,s.executeEnd=Os(),R}flush(e){const t=e.transmuxing;t.executeStart=Os();const{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then((()=>this.flush(e)));const n=[],{timeOffset:a}=r;if(i){const t=i.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Os();const i=[Ys(e)];return this.asyncResult?Promise.resolve(i):i}const h=o.flush(a);return Ws(h)?(this.asyncResult=!0,h.then((t=>(this.flushRemux(n,t,e),n)))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,i){const{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===y?"level":"track"} ${i.level}`);const h=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Os()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s),n}transmuxUnencrypted(e,t,i,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:r}=this;let s;for(let t=0,i=Vs.length;t<i;t++){var n;if(null!=(n=Vs[t].demux)&&n.probe(e,this.logger)){s=Vs[t];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=s.remux,h=s.demux;o&&o instanceof l||(this.remuxer=new l(i,t,r,this.logger)),a&&a instanceof h||(this.demuxer=new h(i,t,r,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Yt(this.config)),e}}const Ys=e=>({remuxResult:{},chunkMeta:e});function Ws(e){return"then"in e&&e.then instanceof Function}class js{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class qs{constructor(e,t,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}}let Xs=0;class Qs{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Xs++,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=e=>{const t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===f.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Lr,this.observer.on(f.FRAG_DECRYPTED,n),this.observer.on(f.ERROR,n);const a=Ke(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(i.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=Ir[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Ir[e]=r,r}(s.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=Ir[Rr];if(e)return e.clientCount++,e;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"}),i=self.URL.createObjectURL(t),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return Ir[Rr]=r,r}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:nt(s)})}catch(r){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new Hs(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new Hs(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Xs++;const t=this.hls.config,i=Ke(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:nt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=Ir[e||Rr];if(t&&1==t.clientCount--){const{worker:i,objectURL:r}=t;delete Ir[e||Rr],r&&self.URL.revokeObjectURL(r),i.terminate()}}(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 e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,r,s,n,a,o,l,h){var d,u;l.transmuxing.start=self.performance.now();const{instanceNo:c,transmuxer:f}=this,g=n?n.start:s.start,m=s.decryptdata,p=this.frag,v=!(p&&s.cc===p.cc),E=!(p&&l.level===p.level),T=p?l.sn-p.sn:-1,S=this.part?l.part-this.part.index:-1,A=0===T&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!E&&(1===T||0===T&&(1===S||A&&S<=0)),R=self.performance.now();(E||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=R),!n||!S&&L||(n.stats.parsing.start=R);const I=!(p&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=p.initSegment)?void 0:u.url)),b=new qs(v,L,o,E,g,I);if(!L||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===y?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${E}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const e=new js(i,r,t,a,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:b},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,b);Ws(t)?t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const t=i.flush(e);Ws(t)?t.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class zs extends D{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const r=null==t?void 0:t.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){const n=r[i];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){s=i;break}a===e.substring(0,a.length)&&(s=i)}if(-1!==s){const e=r[s],n=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let a=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=i&&et(i);return new tt(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){const{details:r,stats:s}=t,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;r.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){const e=Math.max(o||0,0);r.appliedTimelineOffset=e,r.fragments.forEach((t=>{t.start=t.playlistOffset+e}))}if(r.live||null!=i&&i.live){const o="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){tr(i,r);const e=r.playlistParsingError;if(e){this.warn(e);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void i.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=r.fragments[0])?void 0:l.type,networkDetails:n,stats:s})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,g=nr(r,1e3*(r.edge-d));if(r.requestScheduled+g<n?r.requestScheduled=n:r.requestScheduled+=g,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let m,p,v;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,s=r.lastPartSn,a=r.endSN,l=r.lastPartIndex,h=s===a;-1!==l?h?(p=a+1,v=e?0:l):(p=s,v=e?l+1:r.maxPartIndex):p=a+1;const d=r.age,u=d+r.ageHeader;let c=Math.min(u-r.partTarget,1.5*r.targetduration);if(c>0){if(u>3*r.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=i&&i.tuneInGoal&&u-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${c} with playlist age: ${r.age}`),c=0;else{const e=Math.floor(c/r.targetduration);if(p+=e,void 0!==v){v+=Math.round(c%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${c} skip sn ${e} to part ${v}`)}r.tuneInGoal=c}if(m=this.getDeliveryDirectives(r,t.deliveryDirectives,p,v),e||!h)return r.requestScheduled=n,void this.loadingPlaylist(o,m)}else(r.canBlockReload||r.canSkipUntil)&&(m=this.getDeliveryDirectives(r,t.deliveryDirectives,p,v));m&&void 0!==p&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(g-2*a,g/2)),this.scheduleLoading(o,m,r)}else this.clearTimer()}scheduleLoading(e,t,i){const r=i||e.details;if(!r)return void this.loadingPlaylist(e,t);const s=self.performance.now(),n=r.requestScheduled;if(s>=n)return void this.loadingPlaylist(e,t);const a=n-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(e,t)),a)}getDeliveryDirectives(e,t,i,r){let s=et(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=ze),new tt(i,r,s)}checkRetry(e){const t=e.details,i=Et(e),r=e.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===Dt||!r.resolved&&s===It);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=St(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}function Js(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Zs(e[i].attrs,t[i].attrs))return!1;return!0}function Zs(e,t,i){const r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i=>e[i]!==t[i]))}function en(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class tn{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(null===this.queues||null===this.tracks)return;const r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}appendBlocker(e){return new Promise((t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)}))}prependBlocker(e){return new Promise((t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e=>{var t;const i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;const s=null==(i=this.tracks[e])?void 0:i.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map((e=>e.label)).join(", "))||""}}const rn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,sn="HlsJsTrackRemovedError";class nn extends Error{constructor(e){super(e),this.name=sn}}function an(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function on(e){return"audio"===e?1:0}class ln{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(f.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(f.MANIFEST_PARSED,this.onManifestParsed,this),e.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(f.BUFFER_CODECS,this.onBufferCodecs,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(f.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(f.MANIFEST_PARSED,this.onManifestParsed,this),e.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(f.BUFFER_CODECS,this.onBufferCodecs,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&l(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter(((t,i)=>this.isLevelAllowed(t)&&i<=e));return this.clientRect=null,ln.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 e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;let r=e.length-1;const s=Math.max(t,i);for(let t=0;t<e.length;t+=1){const i=e[t];if((i.width>=s||i.height>=s)&&(n=i,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){r=t;break}}var n,a;return r}}const hn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},dn={HLS:"h"},un={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},cn={[un.OBJECT]:["br","d","ot","tb"],[un.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[un.SESSION]:["cid","pr","sf","sid","st","v"],[un.STATUS]:["bs","rtp"]};class fn{constructor(e,t){Array.isArray(e)&&(e=e.map((e=>e instanceof fn?e:new fn(e)))),this.value=e,this.params=t}}const gn="Dict";function mn(e,t,i,r){return new Error(`failed to ${e} "${s=t,Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s)}" as ${i}`,{cause:r});var s}function pn(e,t,i){return mn("serialize",e,t,i)}class vn{constructor(e){this.description=e}}const yn="Bare Item",En="Boolean";const Tn="Byte Sequence";function Sn(e){if(!1===ArrayBuffer.isView(e))throw pn(e,Tn);return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}const An="Integer";function Ln(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw pn(e,An);return e.toString()}const Rn="Decimal";function In(e){const t=Br(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw pn(e,Rn);const i=t.toString();return i.includes(".")?i:`${i}.0`}const bn="String",Dn=/[\x00-\x1f\x7f]+/;const kn="Token";function _n(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw pn(t,kn);return t}function Pn(e){switch(typeof e){case"number":if(!l(e))throw pn(e,yn);return Number.isInteger(e)?Ln(e):In(e);case"string":return function(e){if(Dn.test(e))throw pn(e,bn);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return _n(e);case"boolean":return function(e){if("boolean"!=typeof e)throw pn(e,En);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Ln(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Sn(e);if(e instanceof vn)return _n(e);default:throw pn(e,yn)}}const Cn="Key";function wn(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw pn(e,Cn);return e}function xn(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${wn(e)}`:`;${wn(e)}=${Pn(t)}`)).join("")}function On(e){return e instanceof fn?`${Pn(e.value)}${xn(e.params)}`:Pn(e)}function Mn(e,t={whitespace:!0}){if("object"!=typeof e)throw pn(e,gn);const i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((([e,t])=>{t instanceof fn==!1&&(t=new fn(t));let i=wn(e);var r;return!0===t.value?i+=xn(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(r=t).value.map(On).join(" ")})${xn(r.params)}`:i+=On(t)),i})).join(`,${r}`)}const Fn=e=>Math.round(e),Nn=e=>100*Fn(e/100),Un={br:Fn,d:Fn,bl:Nn,dl:Nn,mtp:Nn,nor:(e,t)=>((null==t?void 0:t.baseUrl)&&(e=function(e,t){const i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;const s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}(e,t.baseUrl)),encodeURIComponent(e)),rtp:Nn,tb:Fn};function Bn(e,t){const i={};if(null==e||"object"!=typeof e)return i;const r=Object.keys(e).sort(),s=R({},Un,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return r.forEach((r=>{if(null==n?void 0:n(r))return;let a=e[r];const o=s[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||function(e){return"number"==typeof e?l(e):null!=e&&""!==e&&!1!==e}(a)&&(function(e){return"ot"===e||"sf"===e||"st"===e}(r)&&"string"==typeof a&&(a=new vn(a)),i[r]=a)})),i}function Gn(e,t={}){return e?function(e,t){return Mn(e,t)}(Bn(e,t),R({whitespace:!1},t)):""}function $n(e,t,i){return R(e,function(e,t={}){const i={};if(!e)return i;const r=Object.entries(e),s=Object.entries(cn).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),n=r.reduce(((e,t)=>{var i,r;const[n,a]=t,o=(null===(i=s.find((e=>e[1].includes(n))))||void 0===i?void 0:i[0])||un.REQUEST;return null!==(r=e[o])&&void 0!==r||(e[o]={}),e[o][n]=a,e}),{});return Object.entries(n).reduce(((e,[i,r])=>(e[i]=Gn(r,t),e)),i)}(t,i))}const Kn="CMCD";const Vn=/CMCD=[^&#]+/;function Hn(e,t,i){const r=function(e,t={}){if(!e)return"";const i=Gn(e,t);return`${Kn}=${encodeURIComponent(i)}`}(t,i);if(!r)return e;if(Vn.test(e))return e.replace(Vn,r);const s=e.includes("?")?"&":"?";return`${e}${s}${r}`}function Yn(e,t,i,r){e&&Object.keys(t).forEach((s=>{const n=e.filter((e=>e.groupId===s)).map((e=>{const n=R({},e);return n.details=void 0,n.attrs=new li(n.attrs),n.url=n.attrs.URI=Wn(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=r,n}));e.push(...n)}))}function Wn(e,t,i,r){const{HOST:s,PARAMS:n,[i]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}class jn extends D{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=jn.CDMCleanupPromise?[jn.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{const{initDataType:t,initData:i}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Pi(this.config));const t=e.map(_i).filter((e=>!!e));this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then((s=>{const n=Li(s);let a,o;if("sinf"===t){if(n!==yi.FAIRPLAY)return void this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);const s=ne(new Uint8Array(i));try{const e=Ee(gi(JSON.parse(s).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24)),o=yi.FAIRPLAY}catch(e){return void this.warn(`${r} Failed to parse sinf: ${e}`)}}else{if(n!==yi.WIDEVINE&&n!==yi.PLAYREADY)return void this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);const s=function(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let r=0;for(;r+32<i;){const i=ke(new DataView(e,r));t.push(i),r+=i.size}}return t}(i),l=s.filter((e=>!!e.systemId&&ki(e.systemId)===n));l.length>1&&this.warn(`${r} Using first of ${l.length} pssh found for selected key-system ${n}`);const h=l[0];if(!h)return void(0===s.length||s.some((e=>!e.systemId))?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${s.map((e=>ki(e.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=ki(h.systemId),0===h.version&&h.data)if(o===yi.WIDEVINE){const e=h.data.length-22;a=new Uint8Array(h.data.subarray(e,e+16))}else o===yi.PLAYREADY&&(a=xi(h.data))}if(!o||!a)return;const l=N.hexDump(a),{keyIdToKeySessionPromise:h,mediaKeySessions:d}=this;let u=h[l];for(let e=0;e<d.length;e++){const r=d[e],s=r.decryptdata;if(!s.keyId)continue;const n=N.hexDump(s.keyId);if(l===n||-1!==s.uri.replace(/-/g,"").indexOf(l)){if(u=h[n],s.pssh)break;delete h[n],s.pssh=new Uint8Array(i),s.keyId=a,u=h[l]=u.then((()=>this.generateRequestWithPreferredKeySession(r,t,i,"encrypted-event-key-match"))),u.catch((e=>this.handleError(e)));break}}if(!u){if(o!==n)return void this.log(`Ignoring "${e.type}" event with ${o} init data for selected key-system ${n}`);u=h[l]=this.getKeySystemSelectionPromise([o]).then((({keySystem:e,mediaKeys:r})=>{var s;this.throwIfDestroyed();const n=new Mi("ISO-23001-7",l,null!=(s=_i(e))?s:"");return n.pssh=new Uint8Array(i),n.keyId=a,this.attemptSetMediaKeys(e,r).then((()=>{this.throwIfDestroyed();const s=this.createMediaKeySessionContext({decryptdata:n,keySystem:e,mediaKeys:r});return this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-no-match")}))})),u.catch((e=>this.handleError(e)))}}))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(f.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(f.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(f.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(f.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(f.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(f.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];return r?r.licenseUrl:e===yi.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(i),s=t.map((e=>e.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):i(t instanceof qn?t:new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Ci&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){const r=function(e,t,i,r){let s;switch(e){case yi.FAIRPLAY:s=["cenc","sinf"];break;case yi.WIDEVINE:case yi.PLAYREADY:s=["cenc"];break;case yi.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,t,i,r)}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let n=null==s?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${nt(r)}`),n=this.requestMediaKeySystemAccess(e,r);const t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((i=>i?this.setMediaKeysServerCertificate(t,e,i):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${N.hexDump(e.keyId||[])}`);const r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return N.hexDump(e.keyId)}updateKeySession(e,t){var i;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${N.hexDump((null==(i=e.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,i)=>{const r=Pi(this.config),s=e.map(Li).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const r=_i(e);r?t(r):i(new Error(`Unable to find format for key-system "${e}"`))})).catch(i)}))}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];if(!s){s=this.getKeySystemForKeyPromise(t).then((({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t})))))));(this.keyIdToKeySessionPromise[i]=s.then((e=>{const i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")}))).catch((e=>this.handleError(e)))}return s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof qn?this.hls.trigger(f.ERROR,e.data):this.hls.trigger(f.ERROR,{type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Li(e.keyFormat),i=t?[t]:Pi(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Pi(this.config)),0===e.length)throw new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${nt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===i.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,i,r){var s,n;const a=null==(s=this.config.drmSystems)||null==(n=s[e.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,t,i,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=r.initData?r.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);const h=new Lr,d=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch((e=>{h.eventNames().length?h.emit("error",e):this.handleError(e)})):"license-release"===r?e.keySystem===yi.FAIRPLAY&&(this.updateKeySession(e,mi("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},f=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const i=e.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",f);const g=new Promise(((e,t)=>{h.on("error",t),h.on("keyStatus",(i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return e.mediaKeysSession.generateRequest(t,i).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>g)).catch((t=>{throw h.removeAllListeners(),this.removeSession(e),t})).then((()=>(h.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,i)=>{if("string"==typeof i&&"object"==typeof t){const e=i;i=t,t=e}this.log(`key status change "${t}" for keyStatuses keyId: ${N.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${N.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise(((s,n)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,o)=>{n(new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:b({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{n(new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise(((r,s)=>{e.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${t}"`),r(e)})).catch((e=>{s(new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i<r;i++){var n,a;t=s[i];const r=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;r&&o&&e.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return mi(atob(l))}setupLicenseXHR(e,t,i,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)})).then((i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}r(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new qn({type:u.KEY_SYSTEM_ERROR,details:c.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:i})=>{e.keySystem==yi.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(e){var t;const i=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Mi.clearKeyUriToKeyIdMap();const r=i.length;jn.CDMCleanupPromise=Promise.all(i.map((e=>this.removeSession(e))).concat(null==e||null==(t=e.setMediaKeys(null))?void 0:t.catch((e=>{var t;this.log(`Could not clear media keys: ${e}`),null==(t=this.hls)||t.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})})))).then((()=>{r&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)})).catch((e=>{var t;this.log(`Could not close sessions and clear media keys: ${e}`),null==(t=this.hls)||t.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{drmSystemOptions:s}=this.config,n=function(e){var t;return"persistent-license"===e.sessionType||!(null==(t=e.sessionTypes)||!t.some((e=>"persistent-license"===e)))}(s)?new Promise(((e,i)=>{self.setTimeout((()=>i(new Error("MediaKeySession.remove() timeout"))),8e3),t.remove().then(e)})):Promise.resolve();return n.catch((e=>{var t;this.log(`Could not remove session: ${e}`),null==(t=this.hls)||t.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})})).then((()=>t.close())).catch((e=>{var t;this.log(`Could not close session: ${e}`),null==(t=this.hls)||t.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})}))}}}jn.CDMCleanupPromise=void 0;class qn extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Xn(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function Qn(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){x.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){x.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function zn(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function Jn(e,t,i,r){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,i){const r=[],s=function(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let r,s=0,n=i;for(;s<=n;)if(r=Math.floor((n+s)/2),t<e[r].startTime)n=r-1;else{if(!(t>e[r].startTime&&s<i))return r;s=r+1}return e[s].startTime-t<t-e[n].startTime?s:n}(e,t);if(s>-1)for(let n=s,a=e.length;n<a;n++){const s=e[n];if(s.startTime>=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(e.cues,t,i);for(let t=0;t<s.length;t++)r&&!r(s[t])||e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}function Zn(e){const t=[];for(let i=0;i<e.length;i++){const r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}function ea(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}const ta=.025;let ia=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function ra(e,t,i){return`${e.identifier}-${i+1}-${ea(t)}`}class sa{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;if(e<=0||isNaN(t))return!1;return this.assetList[e].startOffset>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return na(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-na(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=l(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return na(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<ta))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?ia.Range:ia.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function na(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<ta)?t.start:t.start+t.duration}function aa(e,t,i){const r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function oa(e){const t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class la{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{const e=this.interstitial.playoutLimit,t=this.currentTime;this.startOffset+t>=e&&this.hls.trigger(f.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=i,this.assetItem=r;let n=r.uri;try{n=aa(n,s.sessionId).href}catch(e){}s.loadSource(n);const a=()=>{this.hasDetails=!0};s.once(f.LEVEL_LOADED,a),s.once(f.AUDIO_TRACK_LOADED,a),s.once(f.SUBTITLE_TRACK_LOADED,a),s.on(f.MEDIA_ATTACHING,((e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&t.addEventListener("timeupdate",this.checkPlayout)}))}bufferedInPlaceToEnd(e){var t;if(!this.interstitial.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const i=this.timelineOffset,r=ei.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=this._bufferedEosTime-.02}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=ei.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;return e||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(e,t,i){this.hls.on(e,t)}once(e,t,i){this.hls.once(e,t)}off(e,t,i){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${oa(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${null!=(t=this.interstitial)&&t.appendInPlace?"append-in-place":""}`}}class ha extends D{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((e=>e.reset())),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce(((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i),0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let r=0;r<i.length;r++){let s=i[r];if(t&&"primary"!==t&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return r}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){const e=i[r].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){const t=this.items;if(t)for(let r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return-1}findAssetIndex(e,t){const i=e.assetList,r=i.length;if(r>1)for(let e=0;e<r;e++){const r=i[e];if(!r.error){const i=r.timelineStart;if(t===i||t>i&&t<i+(r.duration||0))return e}}return 0}get assetIdAtEnd(){var e,t;const i=null==(e=this.items)||null==(t=e[this.length-1])?void 0:t.event;if(i){const e=i.assetList,t=e[e.length-1];if(t)return t.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:r}=i,s=this.events,n=this.parseDateRanges(r,{url:i.url},t),a=Object.keys(r),o=s?s.filter((e=>!a.includes(e.identifier))):[];n.length&&n.sort(((e,t)=>{const i=e.cue.pre,r=e.cue.post,s=t.cue.pre,n=t.cue.post;if(i&&!s)return-1;if(s&&!i)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(i||s||r||n)){const i=e.startTime,r=t.startTime;if(i!==r)return i-r}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=n,o.forEach((e=>{this.removeEvent(e)})),this.updateSchedule(e,o)}updateSchedule(e,t=[]){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,s=this.parseSchedule(i,e);(t.length||(null==r?void 0:r.length)!==s.length||s.some(((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005)))&&(this.items=s,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const r=[],s=Object.keys(e);for(let n=0;n<s.length;n++){const a=s[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new sa(o,t),this.eventMap[a]=e,!1===i&&(e.appendInPlace=i)),r.push(e)}}return r}parseSchedule(e,t){const i=[],r=t.main.details,s=r.live?1/0:r.edge;let n=0;if((e=e.filter((e=>!(e.error||e.cue.once&&e.hasPlayed)))).length){this.resolveOffsets(e,t);let r=0,o=0;if(e.forEach(((t,a)=>{const l=t.cue.pre,h=t.cue.post,d=e[a-1]||null,u=t.appendInPlace,c=h?s:t.startOffset,f=t.duration,g=t.timelineOccupancy===ia.Range?f:0,m=t.resumptionOffset,p=(null==d?void 0:d.startTime)===c,v=c+t.cumulativeDuration;let y=u?v+f:c+m;if(l||!h&&c<=0){const e=o;o+=g,t.timelineStart=v;const r=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:r,end:n},integrated:{start:e,end:o}})}else{if(!(c<=s))return;{if(!p){const s=c-r;if(s>.033){const l=r,h=o;o+=s;const d=n;n+=s;const u={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+s,playout:{start:d,end:n},integrated:{start:h,end:o}};i.push(u)}else s>0&&d&&(d.cumulativeDuration+=s,i[i.length-1].end=c)}h&&(y=v),t.timelineStart=v;const s=o;o+=g;const l=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:l,end:n},integrated:{start:s,end:o}})}}const E=t.resumeTime;r=h||E>s?s:E})),r<s){var a;const e=r,t=o,l=s-r;o+=l;const h=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:r,end:e+l,playout:{start:h,end:n},integrated:{start:t,end:o}})}this.setDurations(s,n,o)}else{const e=0;i.push({previousEvent:null,nextEvent:null,start:e,end:s,playout:{start:e,end:s},integrated:{start:e,end:s}}),this.setDurations(s,s,s)}return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,r=i.live?1/0:i.edge;let s=0,n=-1;e.forEach(((a,o)=>{const h=a.cue.pre,d=a.cue.post,u=h?0:d?r:a.startTime;this.updateAssetDurations(a);if(n===u?a.cumulativeDuration=s:(s=0,n=u),!d&&a.snapOptions.in&&(a.resumeAnchor=mt(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=l(a.resumeOffset)?a.resumeOffset:a.duration;s+=c}))}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,r=e.startTime+e.resumptionOffset;if(Math.abs(i-r)>ta)return this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1;if(!t)return this.log(`"${e.identifier}" resumption ${i} can not be aligned with media (none selected)`),!1;return!Object.keys(t).some((r=>{const s=t[r].details,n=s.edge;if(i>=n)return this.log(`"${e.identifier}" resumption ${i} past ${r} playlist end ${n}`),!1;const a=mt(null,s.fragments,i);if(!a)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;const o="audio"===r?.175:0;return!(Math.abs(a.start-i)<ta+o||Math.abs(a.end-i)<ta+o)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)}))}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,r=!1,s=!1;e.assetList.forEach(((e,n)=>{const a=t+i;e.startOffset=i,e.timelineStart=a,r||(r=null===e.duration),s||(s=!!e.error);const o=e.error?0:e.duration||0;i+=o})),e.duration=r&&!s?Math.max(i,e.duration):i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function da(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class ua{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let r;try{r=aa(i,this.hls.sessionId,e.baseUrl)}catch(t){const r=this.assignAssetListError(e,c.ASSET_LIST_LOAD_ERROR,t,i);return void this.hls.trigger(f.ERROR,r)}t&&"data:"!==r.protocol&&r.searchParams.set("_HLS_start_offset",""+t);const s=this.hls.config,n=new(0,s.loader)(s),a={responseType:"json",url:r.href},o=s.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,i,r,s)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))e.assetListResponse=n,this.hls.trigger(f.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:s});else{const t=this.assignAssetListError(e,c.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),r.url,i,s);this.hls.trigger(f.ERROR,t)}},onError:(t,i,r,s)=>{const n=this.assignAssetListError(e,c.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,s,r);this.hls.trigger(f.ERROR,n)},onTimeout:(t,i,r)=>{const s=this.assignAssetListError(e,c.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,r);this.hls.trigger(f.ERROR,s)}};return n.load(a,l,h),this.hls.trigger(f.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,i,r,s,n){return e.error=i,{type:u.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:n,stats:s}}}function ca(e,t,i){fa(e,t,i),e.addEventListener(t,i)}function fa(e,t,i){e.removeEventListener(t,i)}function ga(e){null==e||e.play().catch((()=>{}))}class ma{constructor(e){this.buffered=void 0;const t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}const pa={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},va=e=>String.fromCharCode(pa[e]||e),ya=15,Ea=100,Ta={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Sa={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Aa={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},La={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ra=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ia{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;x.log(`${this.time} [${e}] ${i}`)}}}const ba=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Da{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class ka{constructor(){this.uchar=" ",this.penState=new Da}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class _a{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Da,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Ea;e++)this.chars.push(new ka);this.logger=e}equals(e){for(let t=0;t<Ea;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ea;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ea;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ea&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ea)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=va(e);this.pos>=Ea?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<Ea;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Ea;i++){const r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class Pa{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ya;t++)this.rows.push(new _a(e));this.logger=e}reset(){for(let e=0;e<ya;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<ya;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<ya;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ya;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+nt(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<ya;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const r=i.rows[e].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(i.rows[e+r])}}this.currRow=t;const i=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,r=Math.max(t-1,0);i.setCursor(e.indent),e.color=i.chars[r].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+nt(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",r=-1;for(let i=0;i<ya;i++){const s=this.rows[i].getTextString();s&&(r=i+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class Ca{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Pa(i),this.nonDisplayedMemory=new Pa(i),this.lastOutputScreen=new Pa(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+nt(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class wa{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Ia;this.channels=[null,new Ca(e,t,r),new Ca(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const i=127&t[e],r=127&t[e+1];let s=!1,n=null;if(0===i&&0===r)continue;this.logger.log(3,(()=>"["+ba([t[e],t[e+1]])+"] -> ("+ba([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if(Oa(i,r,a)){xa(null,null,a),this.logger.log(3,(()=>"Repeated command ("+ba([i,r])+") is dropped"));continue}xa(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else xa(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+ba([i,r])+" orig: "+ba([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+ba([e,t])+")")),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const r=e<=23?1:2;i=t>=64&&t<=95?1===r?Ta[e]:Aa[e]:1===r?Sa[e]:La[e];const s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(()=>"Special char '"+va(e)+"' in channel "+i)),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,(()=>"Char codes = "+ba(r).join(","))),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=Ra[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}xa(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function xa(e,t,i){i.a=e,i.b=t}function Oa(e,t,i){return i.a===e&&i.b===t}var Ma=function(){if(null!=vi&&vi.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function s(e,...t){let i=1;for(;i<arguments.length;i++){const t=arguments[i];for(const i in t)e[i]=t[i]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,u=t,c=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return m},set:function(t){const r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return y},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return T},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return A},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Fa{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Na(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class Ua{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Ba(e,t,i,r){const s=r?e.split(r):[e];for(const e in s){if("string"!=typeof s[e])continue;const r=s[e].split(i);if(2!==r.length)continue;t(r[0],r[1])}}const Ga=new Ma(0,0,""),$a="middle"===Ga.align?"middle":"center";function Ka(e,t,i){const r=e;function s(){const t=Na(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){const r=new Ua;Ba(e,(function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",$a,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",$a,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",$a,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===Ga.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",$a);let n=r.get("position","auto");"auto"===n&&50===Ga.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Va(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class Ha{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Fa,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Va(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;const r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=i();const r=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=i(),t.state){case"HEADER":/:/.test(e)?Ba(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new Ma(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Ka(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==e.indexOf("--\x3e");if(!e||i&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Ya=/\r\n|\n\r|\n|\r/g,Wa=function(e,t,i=0){return e.slice(i,i+t.length)===t};function ja(e,t,i){return ea(e.toString())+ea(t.toString())+ea(i)}function qa(e,t,i,r,s,n,a){const o=new Ha,h=F(new Uint8Array(e)).trim().replace(Ya,"\n").split("\n"),d=[],u=t?function(e,t=1){return ws(e,Cs,1/t)}(t.baseTime,t.timescale):0;let c,f="00:00.000",g=0,m=0,p=!0;o.oncue=function(e){const n=i[r];let a=i.ccOffset;const o=(g-u)/9e4;if(null!=n&&n.new&&(void 0!==m?a=i.ccOffset=n.start:function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,h=Bs(9e4*(e.startTime+a-m),9e4*s)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const f=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(f)),e.id||(e.id=ja(e.startTime,e.endTime,f)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(d)},h.forEach((e=>{if(p){if(Wa(e,"X-TIMESTAMP-MAP=")){p=!1,e.slice(16).split(",").forEach((e=>{Wa(e,"LOCAL:")?f=e.slice(6):Wa(e,"MPEGTS:")&&(g=parseInt(e.slice(7)))}));try{m=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(l(t)&&l(i)&&l(r)&&l(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*s,t}(f)/1e3}catch(e){c=e}return}""===e&&(p=!1)}o.parse(e+"\n")})),o.flush()}const Xa="stpp.ttml.im1t",Qa=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,za=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ja={left:"start",center:"center",right:"end",start:"start",end:"end"};function Za(e,t,i,r){const s=ue(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=s.map((e=>F(e))),a=function(e,t,i=1,r=!1){return ws(e,t,1/i,r)}(t.baseTime,1,t.timescale);try{n.forEach((e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((e,t)=>(e[t]=r.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==r.getAttribute("xml:space"),o=to(eo(r,"styling","style")),l=to(eo(r,"layout","region")),h=eo(r,"body","[begin]");return[].map.call(h,(e=>{const i=io(e,a);if(!i||!e.hasAttribute("begin"))return null;const r=no(e.getAttribute("begin"),n),s=no(e.getAttribute("dur"),n);let h=no(e.getAttribute("end"),n);if(null===r)throw so(e);if(null===h){if(null===s)throw so(e);h=r+s}const d=new Ma(r-t,h-t,i);d.id=ja(d.startTime,d.endTime,d.text);const u=function(e,t,i){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(s=i[a]);return n.reduce(((i,n)=>{const a=ro(t,r,n)||ro(e,r,n)||ro(s,r,n);return a&&(i[n]=a),i}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:c}=u;if(c){const e=Ja[c];e&&(d.lineAlign=e),d.align=c}return R(d,u),d})).filter((e=>null!==e))}(e,a))))}catch(e){r(e)}}function eo(e,t,i){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function to(e){return e.reduce(((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function io(e,t){return[].slice.call(e.childNodes).reduce(((e,i,r)=>{var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?io(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function ro(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function so(e){return new Error(`Could not parse ttml timestamp ${e}`)}function no(e,t){if(!e)return null;let i=Na(e);return null===i&&(Qa.test(e)?i=function(e,t){const i=Qa.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):za.test(e)&&(i=function(e,t){const i=za.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}class ao{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class oo{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(f.FRAG_LOADING,this.onFragLoading,this),e.on(f.FRAG_LOADED,this.onFragLoaded,this),e.on(f.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(f.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(f.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(f.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(f.FRAG_LOADING,this.onFragLoading,this),e.off(f.FRAG_LOADED,this.onFragLoaded,this),e.off(f.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(f.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(f.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(f.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new ao(this,"textTrack1"),t=new ao(this,"textTrack2"),i=new ao(this,"textTrack3"),r=new ao(this,"textTrack4");this.cea608Parser1=new wa(1,e,t),this.cea608Parser2=new wa(3,i,r)}addCues(e,t,i,r,s){let n=!1;for(let e=s.length;e--;){const r=s[e],d=(a=r[0],o=r[1],l=t,h=i,Math.min(o,h)-Math.max(a,l));if(d>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),n=!0,d/(i-t)>.5))return}var a,o,l,h;if(n||s.push([t,i]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{const s=this.Cues.newCue(null,t,i,r);this.hls.trigger(f.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){const{unparsedVttFrags:n}=this;i===y&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(f.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){const s=i.textTracks[r];if(ho(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:r}=this,{label:s,languageCode:n}=t[e],a=this.getExistingTrack(s,n);if(a)i[e]=a,zn(i[e]),Xn(i[e],r);else{const t=this.createTextTrack("captions",s,n);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(f.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){const r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:r}=this;Object.keys(r).forEach((e=>{zn(r[e]),delete r[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)zn(t[e])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],r=i.some((e=>e.textCodec===Xa));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Js(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?Zn(e.textTracks):null;if(this.tracks.forEach(((e,i)=>{let r;if(t){let i=null;for(let r=0;r<t.length;r++)if(t[r]&&ho(t[r],e)){i=t[r],t[r]=null;break}i&&(r=i)}if(r)zn(r);else{const t=lo(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)})),null!=t&&t.length){const e=t.filter((e=>null!==e)).map((e=>e.label));e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(f.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===y){var i,r;const{cea608Parser1:e,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:r}=t;if(i.type===T)if(r.byteLength){const e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===Xa?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Za(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),i.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(e);const o=this.hls;qa(null!=(t=i.initSegment)&&t.data?Se(i.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(e=>{this._appendCues(e,i.level),o.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?n.push(e):this._fallbackToIMSC1(i,r),o.logger.log(`Failed to parse VTT cue: ${t}`),s&&a>i.cc||o.trigger(f.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Za(t,this.initPTS[e.cc],(()=>{i.textCodec=Xa,this._parseIMSC1(e,t)}),(()=>{i.textCodec="wvtt"}))}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((e=>Qn(i,e)))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;i.trigger(f.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===T&&this.onFragLoaded(f.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:r}=t;if(i.type!==y||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<r.length;e++){const t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,i[0]),this.cea608Parser2.addData(r[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:s}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!s||"video"===s){const{captionsTracks:e}=this;Object.keys(e).forEach((r=>Jn(e[r],t,i)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((i=>Jn(e[i],t,r)))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let r=2;for(let s=0;s<i;s++){const i=e[r++],s=127&e[r++],n=127&e[r++];if(0===s&&0===n)continue;if(!!(4&i)){const e=3&i;0!==e&&1!==e||(t[e].push(s),t[e].push(n))}}return t}}function lo(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function ho(e,t){return!!e&&e.kind===lo(t)&&en(t,e)}const uo=/\s/,co={newCue(e,t,i,r){const s=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let c=0;c<r.rows.length;c++)if(n=r.rows[c],o=!0,l=0,h="",!n.isEmpty()){var u;for(let e=0;e<n.chars.length;e++)uo.test(n.chars[e].uchar)&&o?l++:(h+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;const r=Va(h.trim()),f=ja(t,i,r);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||(a=new d(t,i,r),a.id=f,a.line=c+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>Qn(e,t)))),s}};const fo=/(\d+)-(\d+)\/(\d+)/;class go{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||mo,this.controller=new self.AbortController,this.stats=new j}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(R({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=o&&l(o)?o:h,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))}),t.timeout);(Ws(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((i=>{var s;this.response=this.loader=i;const a=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))}),h-(a-r.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new po(t||"fetch, bad network response",e,i)}r.loading.first=a,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=fo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(l(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||r.total;const o=null==(s=this.callbacks)?void 0:s.onProgress;return o&&l(t.highWaterMark)?this.loadProgressively(i,r,e,t.highWaterMark,o):n?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((i=>{var s,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const h=i[a];h&&(r.loaded=r.total=h);const d={url:o.url,data:i,code:o.status},u=null==(s=this.callbacks)?void 0:s.onProgress;u&&!l(t.highWaterMark)&&u(r,e,i,o),null==(n=this.callbacks)||n.onSuccess(d,r,e,o)})).catch((t=>{var i;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,n=t?t.message:null;null==(i=this.callbacks)||i.onError({code:s,text:n},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){const n=new Er,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(t,i,n.flush().buffer,e)):s(t,i,l.buffer,e),o()})).catch((()=>Promise.reject()));return o()}}function mo(e,t){return new self.Request(e.url,t)}class po extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const vo=/^age:\s*[\d.]+\s*$/im;class yo{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new j,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{var s;null==(s=this.callbacks)||s.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&l(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,l="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){const s=null!=l?l:t.response;if(null!=s){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===t.responseType?s.byteLength:s.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,e,s,t);const h={url:t.responseURL,data:s,code:r};return void(null==(a=this.callbacks)||a.onSuccess(h,i,e,t))}}const h=s.loadPolicy.errorRetry;var o;if(Lt(h,i.retry,!1,{url:e.url,data:void 0,code:r}))this.retry(h);else x.error(`${r} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:r,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Lt(e,this.stats.retry,!0))this.retry(e);else{var t;x.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=St(e,i.retry),i.retry++,x.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.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(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&vo.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Eo=b(b({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:yo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends D{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:i,partCurrent:r,hls:s}=this,{autoLevelEnabled:n,media:a}=s;if(!i||!a)return;const o=performance.now(),h=r?r.stats:i.stats,d=r?r.duration:i.duration,u=o-h.loading.start,c=s.minAutoLevel,g=i.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const p=m>-1&&m!==g,v=!!e||p;if(!v&&(a.paused||!a.playbackRate||!a.readyState))return;const y=s.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(a.playbackRate);if(u<=Math.max(E,d/(2*T)*1e3))return;const S=y?y.len/T:0,A=h.loading.first?h.loading.first-h.loading.start:-1,L=h.loaded&&A>-1,R=this.getBwEstimate(),I=s.levels,b=I[g],D=Math.max(h.loaded,Math.round(d*(i.bitrate||b.averageBitrate)/8));let k=L?u-A:u;k<1&&L&&(k=Math.min(u,8*h.loaded/R));const _=L?1e3*h.loaded/k:0,P=E/1e3,C=_?(D-h.loaded)/_:8*D/R+P;if(C<=S)return;const w=_?8*_:R,x=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),O=this.hls.config.abrBandWidthUpFactor;let M,F=Number.POSITIVE_INFINITY;for(M=g-1;M>c;M--){const e=I[M].maxBitrate,t=!I[M].details||x;if(F=this.getTimeToLoadFrag(P,w,d*e,t),F<Math.min(S,d+P))break}if(F>=C)return;if(F>10*d)return;L?this.bwEstimator.sample(u-Math.min(E,A),h.loaded):this.bwEstimator.sampleTTFB(u);const N=I[M].maxBitrate;this.getBwEstimate()*O>N&&this.resetEstimator(N);const U=this.findBestLevel(N,c,M,0,S,1,1);U>-1&&(M=U),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|A} ms\n Current BW estimate: ${l(R)?0|R:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|N} bps`),s.nextLoadLevel=s.nextAutoLevel=M,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===M&&M>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,M>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,M,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};p||C>2*F?B():this.timer=self.setInterval(B,1e3*F),s.trigger(f.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new A(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.FRAG_LOADING,this.onFragLoading,this),e.on(f.FRAG_LOADED,this.onFragLoaded,this),e.on(f.FRAG_BUFFERED,this.onFragBuffered,this),e.on(f.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(f.LEVEL_LOADED,this.onLevelLoaded,this),e.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(f.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.FRAG_LOADING,this.onFragLoading,this),e.off(f.FRAG_LOADED,this.onFragLoaded,this),e.off(f.FRAG_BUFFERED,this.onFragBuffered,this),e.off(f.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(f.LEVEL_LOADED,this.onLevelLoaded,this),e.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(f.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(f.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case c.BUFFER_ADD_CODEC_ERROR:case c.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case c.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(e,t,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:r}=t.stats,s=r.end-r.first;l(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const r=i?i.stats:t.stats;if(t.type===y&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,s=this.hls.levels[t.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(f.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted)return;if(this.ignoreFragment(i))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==y||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,r,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,r,l,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1}}const c=this.findBestLevel(o,n,r,l,u,h,d);if(this.rebufferNotice!==c&&(this.rebufferNotice=c,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`)),c>-1)return c;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,s,n,a){var o;const h=r+s,d=this.lastLoadedFragLevel,u=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===g.length)return 0;const y=g[u],E=!(null==(o=this.hls.latestLevelDetails)||!o.live),T=-1===p||-1===d;let S,A="SDR",L=(null==y?void 0:y.frameRate)||0;const{audioPreference:R,videoPreference:I}=v,b=this.audioTracksByGroup||(this.audioTracksByGroup=ot(m));let D=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce(((e,i,r)=>{if(!i.codecSet)return e;const s=i.audioGroups;let n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,s&&s.forEach((e=>{if(!e)return;const i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((e=>{n.channels[e]=(n.channels[e]||0)+i.channels[e]})))})),e}),{})}(g,b,t,i)),s=function(e,t,i,r,s){const n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,h=null==s?void 0:s.videoCodec,d=a&&2===parseInt(a);let u=!1,c=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=st(t,s);for(let t=n.length;t--;){const i=e[n[t]];u||(u=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter((e=>i.videoRanges[e]>0)).length>0&&(c=!0)}f=l(f)?f:0,g=l(g)?g:0;const S=Math.max(1080,f),A=Math.max(30,g);m=l(m)?m:i,i=Math.max(m,i),c||(t=void 0);const L=n.length>1;return{codecSet:n.reduce(((t,r)=>{const s=e[r];if(r===t)return t;if(y=c?T.filter((e=>s.videoRanges[e]>0)):[],L){if(s.minBitrate>i)return at(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return at(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return at(r,`audio codec preference "${o}" not found`),t;if(a&&!d){if(!s.channels[a])return at(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||d)&&u&&0===s.channels[2])return at(r,"no renditions with stereo sound found"),t;if(s.minHeight>S)return at(r,`min resolution of ${s.minHeight} > maximum of ${S}`),t;if(s.minFramerate>A)return at(r,`min framerate of ${s.minFramerate} > maximum of ${A}`),t;if(!y.some((e=>s.videoRanges[e]>0)))return at(r,`no variants with VIDEO-RANGE of ${nt(y)} found`),t;if(h&&r.indexOf(h.substring(0,4))%5!=0)return at(r,`video codec preference "${h}" not found`),t;if(s.maxScore<v)return at(r,`max score of ${s.maxScore} < selected max of ${v}`),t}return t&&(Fe(r)>=Fe(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,v=s.maxScore,r)}),void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(r,A,e,R,I),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:h,minIndex:d,preferHDR:u}=s;D=d,S=n,A=u?a[a.length-1]:a[0],L=o,e=Math.max(e,h),this.log(`picked start tier ${nt(s)}`)}else S=null==y?void 0:y.codecSet,A=null==y?void 0:y.videoRange;const k=f?f.duration:c?c.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=i;o>=t;o--){var C;const t=g[o],c=o>u;if(!t)continue;if(v.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&(je(t,b,A,L,e,R)||Le(t.videoCodec))?(t.supportedPromise=qe(t,b,i),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,r=i.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${nt(e)}`):e.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${nt(e)}`),r>-1&&i.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):t.supportedResult=He}if((S&&t.codecSet!==S||A&&t.videoRange!==A||c&&L>t.frameRate||!c&&L>0&&L<t.frameRate||t.supportedResult&&(null==(C=t.supportedResult.decodingInfoResults)||!C[0].smooth))&&(!T||o!==D)){P.push(o);continue}const m=t.details,y=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||k;let I;I=c?a*e:n*e;const w=k&&r>=2*k&&0===s?t.averageBitrate:t.maxBitrate,x=this.getTimeToLoadFrag(_,I,w*y,void 0===m);if(I>=w&&(o===d||0===t.loadError&&0===t.fragmentError)&&(x<=_||!l(x)||E&&!this.bitrateTestDelay||x<h)){const e=this.forcedAutoLevel;return o===p||-1!==e&&e===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[P[0]].codecs}" ${g[P[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(I)})-bitrate=${Math.round(I-w)} ttfb:${_.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${T} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends D{constructor(e,t){var i;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(f.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=O(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.MANIFEST_PARSED,this.onManifestParsed,this),e.on(f.BUFFER_RESET,this.onBufferReset,this),e.on(f.BUFFER_APPENDING,this.onBufferAppending,this),e.on(f.BUFFER_CODECS,this.onBufferCodecs,this),e.on(f.BUFFER_EOS,this.onBufferEos,this),e.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(f.FRAG_PARSED,this.onFragParsed,this),e.on(f.FRAG_CHANGED,this.onFragChanged,this),e.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.MANIFEST_PARSED,this.onManifestParsed,this),e.off(f.BUFFER_RESET,this.onBufferReset,this),e.off(f.BUFFER_APPENDING,this.onBufferAppending,this),e.off(f.BUFFER_CODECS,this.onBufferCodecs,this),e.off(f.BUFFER_EOS,this.onBufferEos,this),e.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(f.FRAG_PARSED,this.onFragParsed,this),e.off(f.FRAG_CHANGED,this.onFragChanged,this),e.off(f.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?R(i,r.tracks):this.sourceBuffers.forEach((e=>{const[t]=e;t&&(i[t]=R({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null})),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media,r=O(this.appendSource);if(this.transferData=this.overrides=void 0,i&&r){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const s=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(s),e)this._objectUrl=i.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");const t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&s instanceof t,an(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,r=t.tracks,s=r?Object.keys(r):null,n=s?s.length:0,a=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(r&&s&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${nt(i,((e,t)=>"initSegment"===e?void 0:t))};\ntransfer tracks: ${nt(r,((e,t)=>"initSegment"===e?void 0:t))}}`),!M(r,i)){t.mediaSource=null,t.tracks=void 0;const s=e.currentTime,n=this.details,a=Math.max(s,(null==n?void 0:n.fragments[0].start)||0);return a-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${s}`),this.onMediaDetaching(f.MEDIA_DETACHING,{}),this.onMediaAttaching(f.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,s.forEach((e=>{const t=e,i=r[t];if(i){const e=i.buffer;if(e){const r=this.fragmentTracker,s=i.id;if(r.hasFragments(s)||r.hasParts(s)){const i=ei.getBuffered(e);r.detectEvictedFragments(t,i,s,null,!0)}const n=on(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,i)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:r,mediaSource:s,_objectUrl:n}=this;if(s){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((([e])=>{e&&this.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===s.readyState;try{const t=s.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),s.removeSourceBuffer(t[i]);e&&s.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(r.removeAttribute("src"),this.appendSource&&an(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(f.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach((([e])=>{e&&this.resetBuffer(e)})),this.initTracks()}resetBuffer(e){var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[on(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new tn(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),n=!s&&this.sourceBufferCount&&this.media&&r.some((e=>!i[e]));s||n?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach((e=>{var r,s,n;const a=t[e],{id:o,codec:l,levelCodec:h,container:d,metadata:u,supplemental:c}=a;let f=i[e];const g=null==(r=this.transferData)||null==(s=r.tracks)?void 0:s[e],m=null!=g&&g.buffer?g:f,p=(null==m?void 0:m.pendingCodec)||(null==m?void 0:m.codec),v=null==m?void 0:m.levelCodec;f||(f=i[e]={buffer:void 0,listeners:[],codec:l,supplemental:c,container:d,levelCodec:h,metadata:u,id:o});const y=Ge(p,v),E=null==y?void 0:y.replace(rn,"$1");let T=Ge(l,h);const S=null==(n=T)?void 0:n.replace(rn,"$1");T&&y&&E!==S&&("audio"===e.slice(0,5)&&(T=Be(T,this.appendSource)),this.log(`switching codec ${p} to ${T}`),T!==(f.pendingCodec||f.codec)&&(f.pendingCodec=T),f.container=d,this.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e}),{})}appendChangeType(e,t,i){const r=`${t};codecs=${i}`,s={label:`change-type=${r}`,execute:()=>{const s=this.tracks[e];if(s){const n=s.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),n.changeType(r),s.codec=i,s.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,r=i+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,y))?void 0:t.gap))return;const s={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>r||null!=t&&t.buffer&&ei.isBuffered(t.buffer,r)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(r,y))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:r,type:s,parent:n,frag:a,part:o,chunkMeta:l}=t,h=l.buffering[s],d=a.sn,g=self.performance.now();h.start=g;const m=a.stats.buffering,p=o?o.stats.buffering:null;0===m.start&&(m.start=g),p&&0===p.start&&(p.start=g);const v=i.audio;let y=!1;"audio"===s&&"audio/mpeg"===(null==v?void 0:v.container)&&(y=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const E=this.tracks.video,T=null==E?void 0:E.buffer;if(T&&"initSegment"!==d){const e=o||a,t=this.blockedAudioAppend;if("audio"!==s||"main"===n||this.blockedAudioAppend){if("video"===s){const i=e.end;if(t){const e=t.frag.start;(i>e||i<this.lastVideoAppendEnd||ei.isBuffered(T,e))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const t=e.start+.05*e.duration,i=T.buffered,r=this.currentOp("video");i.length||r?!r&&!ei.isBuffered(T,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const S=(o||a).start,A={label:`append-${s}`,execute:()=>{if(h.executeStart=self.performance.now(),y){const e=this.tracks[s];if(e){const t=e.buffer;if(t){const e=S-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${S} (delta: ${e}) sn: ${d})`),t.timestampOffset=S)}}}this.appendExecutor(r,s)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();h.executeEnd=h.end=e,0===m.first&&(m.first=e),p&&0===p.first&&(p.first=e);const t={};this.sourceBuffers.forEach((([e,i])=>{e&&(t[e]=ei.getBuffered(i))})),this.appendErrors[s]=0,"audio"===s||"video"===s?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(f.BUFFER_APPENDED,{type:s,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const i={type:u.MEDIA_ERROR,parent:a.type,details:c.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},r=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)i.details=c.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!r)i.errorAction=Ct(!0);else if(e.name===sn&&0===this.sourceBufferCount)i.errorAction=Ct(!0);else{const e=++this.appendErrors[s];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${r||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||r)&&(i.fatal=!0)}this.hls.trigger(f.ERROR,i)}};this.append(A,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(f.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){const{type:i,startOffset:r,endOffset:s}=t;i?this.append(this.getFlushOp(i,r,s),i):this.sourceBuffers.forEach((([e])=>{e&&this.append(this.getFlushOp(e,r,s),e)}))}onFragParsed(e,t){const{frag:i,part:r}=t,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[Q]?s.push("audiovideo"):(n[q]&&s.push("audio"),n[X]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:i.stats;this.hls.trigger(f.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})}),s).catch((e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t,i;return e&&(!(null!=(t=this.tracks[e])&&t.ended)||(null==(i=this.tracks[e])?void 0:i.ending))}))}onBufferEos(e,t){var i;this.sourceBuffers.forEach((([e])=>{if(e){const i=this.tracks[e];t.type&&t.type!==e||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}}));const r=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)}))&&(r?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(f.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(f.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach((([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen((()=>this.updateMediaSource(e)))}onError(e,t){if(t.details===c.BUFFER_APPEND_ERROR&&t.frag){var i;const e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;l(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.sourceBufferCount)return;const r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(l(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(s/n)*n-e;this.flushBackBuffer(s,n,t)}if(l(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const e=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),t=Math.max(e,n),i=Math.floor(s/n)*n+t;this.flushFrontBuffer(s,n,i)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach((([e,t])=>{if(t){const s=ei.getBuffered(t);if(s.length>0&&i>s.start(0)){var r;this.hls.trigger(f.BACK_BUFFER_REACHED,{bufferEnd:i});const t=this.tracks[e];if(null!=(r=this.details)&&r.live)this.hls.trigger(f.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(f.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}}))}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach((([t,r])=>{if(r){const s=ei.getBuffered(r),n=s.length;if(n<2)return;const a=s.start(n-1),o=s.end(n-1);if(i>a||e>=a&&e<=o)return;this.hls.trigger(f.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}}))}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,r)}}return{duration:1/0}}const s=null==(e=this.overrides)?void 0:e.duration;if(s)return l(s)?{duration:s}:null;const n=this.media.duration;return r>(l(i.duration)?i.duration:0)&&r>n||!l(n)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){const r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==e&&(l(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${nt(i)}`),this.tracksReady){var r;const e=null==(r=this.transferData)?void 0:r.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach((([t,i])=>{if(t){const r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}})),this.hls.trigger(f.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([e])=>{this.executeNext(e)}))}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const n=s,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),s=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${s})${this.currentOp(n)?" Queued":""} ${nt(a)}`);try{const e=i.addSourceBuffer(s),r=on(n),o=[n,e];t[r]=o,a.buffer=e}catch(e){var r;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(r=this.operationQueue)||r.removeBlockers(),delete this.tracks[n],void this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:s,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let r=e.codec;i&&("video"===t||"audiovideo"===t)&&we(i,"video")&&(r=function(e,t){const i=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)Ce(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(r,i));const s=Ge(r,e.levelCodec);return s?"audio"===t.slice(0,5)?Be(s,this.appendSource):s:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(f.BUFFER_FLUSHED,{type:e})}))}get mediaSrc(){var e,t;const i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const s=this.currentOp(e);s&&s.onError(r)}removeExecutor(e,t,i){const{media:r,mediaSource:s}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!r||!s||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=l(r.duration)?r.duration:1/0,h=l(s.duration)?s.duration:1/0,d=Math.max(0,t),u=Math.min(i,o,h);u>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${u}] from the ${e} SourceBuffer`),a.remove(d,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new nn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some((([e,t])=>e&&t.updating))}isQueued(){return this.sourceBuffers.some((([e])=>e&&!!this.currentOp(e)))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,r=t.map((e=>this.appendBlocker(e)));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then((t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(e){e.forEach((e=>{var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)}))}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((e,t)=>e+(this.isPending(this.tracks[t])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((e,[t])=>e+(t?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([e])=>e)).filter((e=>!!e))}addBufferListener(e,t,i){const r=this.tracks[e];if(!r)return;const s=r.buffer;if(!s)return;const n=i.bind(this,e);r.listeners.push({event:t,listener:n}),s.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach((e=>{i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},capLevelController:ln,errorController:class extends D{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(f.ERROR,this.onError,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(f.ERROR,this.onError,this),e.off(f.ERROR,this.onErrorOut,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===y?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const r=this.hls,s=t.context;switch(t.details){case c.FRAG_LOAD_ERROR:case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_ERROR:case c.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case c.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=Ct());case c.FRAG_GAP:case c.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=It);case c.LEVEL_EMPTY_ERROR:case c.LEVEL_PARSING_ERROR:{var n,a;const e=t.parent===y?t.level:r.loadLevel;t.details===c.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(a=n.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case c.LEVEL_LOAD_ERROR:case c.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level)));case c.AUDIO_TRACK_LOAD_ERROR:case c.AUDIO_TRACK_LOAD_TIMEOUT:case c.SUBTITLE_LOAD_ERROR:case c.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const e=r.loadLevelObj;if(e&&(s.type===p&&e.hasAudioGroup(s.groupId)||s.type===v&&e.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=It,void(t.errorAction.flags=_t)}return;case c.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=r.loadLevelObj,i=null==e?void 0:e.attrs["HDCP-LEVEL"];i?t.errorAction={action:It,flags:Pt,hdcpLevel:i}:this.keySystemError(t)}return;case c.BUFFER_ADD_CODEC_ERROR:case c.REMUX_ALLOC_ERROR:case c.BUFFER_APPEND_ERROR:var o;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(o=t.level)?o:r.loadLevel);return;case c.INTERNAL_EXCEPTION:case c.BUFFER_APPENDING_ERROR:case c.BUFFER_FULL_ERROR:case c.LEVEL_SWITCH_ERROR:case c.BUFFER_STALLED_ERROR:case c.BUFFER_SEEK_OVER_HOLE:case c.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Ct())}t.type===u.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=Tt(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Lt(i,r,Et(e),e.response))return{action:Dt,flags:kt,retryConfig:i,retryCount:r};const s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=t.config,a=Tt(e.details.startsWith("key")?n:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){e.details!==c.FRAG_GAP&&r.fragmentError++;if(Lt(a,o,Et(e),e.response))return{action:Dt,flags:kt,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const r=this.hls.levels[t];if(r){var s,n;const t=e.details;r.loadError++,t===c.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:u,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=null==(s=e.frag)?void 0:s.type,m=(g===E&&t===c.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===c.BUFFER_ADD_CODEC_ERROR||t===c.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>r.audioCodec!==e)),S="video"===e.sourceBufferName&&(t===c.BUFFER_ADD_CODEC_ERROR||t===c.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t)),{type:A,groupId:L}=null!=(n=e.context)?n:{};for(let i=h.length;i--;){const s=(i+d)%h.length;if(s!==d&&s>=u&&s<=f&&0===h[s].loadError){var a,o;const i=h[s];if(t===c.FRAG_GAP&&g===y&&e.frag){const t=h[s].details;if(t){const i=mt(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(A===p&&i.hasAudioGroup(L)||A===v&&i.hasSubtitleGroup(L))continue;if(g===E&&null!=(a=r.audioGroups)&&a.some((e=>i.hasAudioGroup(e)))||g===T&&null!=(o=r.subtitleGroups)&&o.some((e=>i.hasSubtitleGroup(e)))||m&&r.audioCodec===i.audioCodec||!m&&r.audioCodec!==i.audioCodec||S&&r.codecSet===i.codecSet)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:It,flags:kt,nextAutoLevel:l}}return{action:It,flags:_t}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case Rt:break;case It:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===c.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:r,hdcpLevel:s,nextAutoLevel:n}=i;switch(r){case kt:this.switchLevel(e,n);break;case Pt:s&&(t.maxHdcpLevel=Xe[Xe.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===c.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=Ve(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===t&&this.hls.removeLevel(r)}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(f.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(f.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,s=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(f.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(f.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},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:Ci,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:co,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends vr{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",T),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(f.LEVEL_LOADED,this.onLevelLoaded,this),e.on(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(f.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(f.LEVEL_LOADED,this.onLevelLoaded,this),e.off(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(f.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=pr.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:r}=t;if(J(i)&&(this.fragPrevious=i),this.state=pr.IDLE,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=i.start;for(let e=0;e<s.length;e++)if(a>=s[e].start&&a<=s[e].end){n=s[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:r}=t;if(0===i&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let i=0;i<t.length;)if(t[i].end<=e)t.shift();else{if(!(t[i].start<e))break;t[i].start=e,i++}})),this.fragmentTracker.removeFragmentsInRange(i,e,T)}}onError(e,t){const i=t.frag;(null==i?void 0:i.type)===T&&(t.details===c.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==pr.STOPPED&&(this.state=pr.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Js(this.levels,t)?this.levels=t.map((e=>new it(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new it(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,T),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==pr.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:r,levels:s}=this,{details:n,id:a}=t;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[a];if(a>=s.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,sr(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(gr(n,e),l=n.fragmentStart):t&&(l=t.start,sr(n,l))}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(f.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===pr.IDLE)){mt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&ci(r.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,fi(r.method)).catch((e=>{throw s.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const r=performance.now();s.trigger(f.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=pr.IDLE}))}}doTick(){if(this.media){if(this.state===pr.IDLE){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;const{config:r}=this,s=this.getLoadPosition(),n=ei.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const h=l.fragments,d=h.length,u=l.edge;let c=null;const f=this.fragPrevious;if(a<u){const e=r.maxFragLookUpTolerance,t=a>u-e?0:e;c=mt(f,h,Math.max(h[0].start,a),t),!c&&f&&f.start<h[0].start&&(c=h[0])}else c=h[d-1];if(c=this.filterReplacedPrimary(c,i.details),!c)return;const g=h[c.sn-l.startSN-1];if(g&&g.cc===c.cc&&this.fragmentTracker.getState(g)===wt&&(c=g),this.fragmentTracker.getState(c)===wt){const e=this.mapToInitFragWhenRequired(c);e&&this.loadFragment(e,i,a)}}}else this.state=pr.IDLE}loadFragment(e,t,i){J(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new ma(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends zs{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=Zn(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.MANIFEST_PARSED,this.onManifestParsed,this),e.on(f.LEVEL_LOADING,this.onLevelLoading,this),e.on(f.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.MANIFEST_PARSED,this.onManifestParsed,this),e.off(f.LEVEL_LOADING,this.onLevelLoading,this),e.off(f.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(f.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(f.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;Zn(i.textTracks).forEach((e=>{zn(e)}))}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;const i=ht(t,e);if(i>-1)s=e[i];else{const e=ht(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(f.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const s=t[r];if((!i||s.default)&&(i||e)&&(!e||dt(s,e)))return r}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Zs(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Zs(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){if(en(t[i],e))return i}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==v||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&dt(e,i))return i;const r=ht(e,this.tracksInGroup);if(r>-1){const e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}if(i)return null;{const i=ht(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${s}`),this.hls.trigger(f.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Zn(e.textTracks),i=this.currentTrack;let r;if(i&&(r=t.filter((e=>en(i,e)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==r&&(e.mode="disabled")})),r){const e=this.subtitleDisplay?"showing":"hidden";r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!l(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(f.SUBTITLE_TRACK_SWITCH,{id:e});const s=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:h,url:d}=r;this.hls.trigger(f.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:h,url:d});const u=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(u)}},timelineController:oo,audioStreamController:class extends vr{constructor(e,t,i){super(e,t,i,"audio-stream-controller",E),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(f.LEVEL_LOADED,this.onLevelLoaded,this),e.on(f.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(f.BUFFER_RESET,this.onBufferReset,this),e.on(f.BUFFER_CREATED,this.onBufferCreated,this),e.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(f.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(f.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(f.FRAG_LOADING,this.onFragLoading,this),e.on(f.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(f.LEVEL_LOADED,this.onLevelLoaded,this),e.off(f.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(f.BUFFER_RESET,this.onBufferReset,this),e.off(f.BUFFER_CREATED,this.onBufferCreated,this),e.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(f.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(f.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(f.FRAG_LOADING,this.onFragLoading,this),e.off(f.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){if(i===y){const e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${r}/${s}`),this.mainAnchor=t,this.state===pr.WAITING_INIT_PTS){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==e)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,i.abortRequests(),this.resetLoadingState()):this.state===pr.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),i=e.cc;return function(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){const r=i.start,s=i.end;let n=e.fragments;if(!i.relurl){const{fragmentHint:t}=e;t&&(n=n.concat(t))}return gt(n,(e=>e.cc<t||e.end<=r?1:e.cc>t||e.start>=s?-1:0))}return null}(t,i,e)||t&&yt(t.fragments,i)||e}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=pr.STOPPED);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=pr.IDLE):this.state=pr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case pr.IDLE:this.doTickIdle();break;case pr.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=pr.WAITING_INIT_PTS}break}case pr.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=pr.IDLE}break}case pr.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:r,complete:s}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=pr.FRAG_LOADING;const e={frag:t,part:i,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&(this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${n.cc}`),this.nextLoadPosition=this.findSyncFrag(n).start,this.clearWaitingFragment())}else this.state=pr.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==pr.STOPPED&&(this.state=pr.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:r,trackId:s}=this,n=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[s])return;const a=i[s],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=pr.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,q,E));const h=this.getFwdBufferInfo(l,E);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(f.BUFFER_EOS,{type:"audio"}),void(this.state=pr.ENDED);const d=h.len,u=t.maxBufferLength,c=o.fragments,g=c[0].start,m=this.getLoadPosition(),p=this.flushing?m:h.end;if(this.switchingTrack&&r){const e=m;o.PTSKnown&&e<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=g+.05)}if(d>=u&&!this.switchingTrack&&p<c[c.length-1].start)return;let v=this.getNextFragment(p,o);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,o,h,y,u)),!v)return void(this.bufferFlushed=!0);let T=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&J(v)&&!v.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===Mt&&(this.mainFragLoading=T=null),T&&J(T))){if(v.start>T.end){const e=this.fragmentTracker.getFragAtPos(p,y);e&&e.end>T.end&&(T=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new it(e)))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==pr.STOPPED&&(this.setInterval(100),this.state=pr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(f.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:r}=this,{details:s,id:n,groupId:a,track:o}=t;if(!r)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||s.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==pr.STOPPED&&(this.state=pr.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const h=r[n];let d=0;if(s.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;var u;if(h.details)d=this.alignPlaylists(s,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);s.alignedSliding||(fr(s,l),s.alignedSliding||gr(s,l),d=s.fragmentStart)}h.details=s,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(f.AUDIO_TRACK_UPDATED,{details:s,id:n,groupId:t.groupId}),this.state!==pr.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=pr.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:r,payload:s}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Qs(this.hls,E,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){const e=!1,t=r?r.index:-1,n=-1!==t,a=new Jt(i.level,i.sn,i.stats.chunkCount,s.byteLength,t,n);u.push(s,f,d,"",i,r,h.totalduration,e,a,c)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new Er,complete:!1};e.push(new Uint8Array(s)),this.state!==pr.STOPPED&&(this.state=pr.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===y&&J(t.frag)&&(this.mainFragLoading=t,this.state===pr.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i.type===E)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(J(i)){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(f.AUDIO_TRACK_SWITCHED,b({},e)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==y||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var i;if(t.fatal)this.state=pr.ERROR;else switch(t.details){case c.FRAG_GAP:case c.FRAG_PARSING_ERROR:case c.FRAG_DECRYPT_ERROR:case c.FRAG_LOAD_ERROR:case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_ERROR:case c.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(E,t);break;case c.AUDIO_TRACK_LOAD_ERROR:case c.AUDIO_TRACK_LOAD_TIMEOUT:case c.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==pr.WAITING_TRACK||(null==(i=t.context)?void 0:i.type)!==p||(this.state=pr.IDLE);break;case c.BUFFER_ADD_CODEC_ERROR:case c.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.resetLoadingState();break;case c.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case c.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==X&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==X){this.flushing=!1,this.bufferFlushed=!0,this.state===pr.ENDED&&(this.state=pr.IDLE);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,E),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:u,text:c,id3:g,initSegment:m}=s;if(!this.fragContextChanged(o)&&d){if(this.state=pr.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,m.tracks,e,n),r.trigger(f.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:m.tracks})}if(u){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=u;l&&(l.elementaryStreams[q]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(q,e,t,i,r),this.bufferFragmentData(u,o,l,n)}if(null!=g&&null!=(t=g.samples)&&t.length){const e=R({id:i,frag:o,details:d},g);r.trigger(f.FRAG_PARSING_METADATA,e)}if(c){const e=R({id:i,frag:o,details:d},c);r.trigger(f.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,r){if(this.state!==pr.PARSING)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const s=t.audio;s.id=E;const n=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(f.BUFFER_CODECS,t);const a=s.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(f.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);var s;if(this.switchingTrack||r===wt||r===Ot)if(J(e))if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=pr.WAITING_INIT_PTS;const i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&gr(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:r,characteristics:s,audioCodec:n,channels:a}=this.bufferedTrack;dt({name:t,lang:i,assocLang:r,characteristics:s,audioCodec:n,channels:a},e,ut)||(ft(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(f.AUDIO_TRACK_SWITCHED,b({},e))}},audioTrackController:class extends zs{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.MANIFEST_PARSED,this.onManifestParsed,this),e.on(f.LEVEL_LOADING,this.onLevelLoading,this),e.on(f.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(f.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.MANIFEST_PARSED,this.onManifestParsed,this),e.off(f.LEVEL_LOADING,this.onLevelLoading,this),e.off(f.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(f.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(f.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!s&&t){const i=ht(t,e,ut);if(i>-1)s=e[i];else{const e=ht(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(f.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==p||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&dt(e,r,ut))return r;const s=ht(e,this.tracksInGroup,ut);if(s>-1){const e=this.tracksInGroup[s];return this.setAudioTrack(s),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);const s=function(e,t,i,r,s){const n=t[r],a=t.reduce(((e,t,i)=>{const r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=ct(t,r,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return ht(e,n,s)>-1}));return d>-1?d:ct(t,r,(t=>{const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return ht(e,n,s)>-1}))}(e,t.levels,i,r,ut);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){const t=ht(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(f.AUDIO_TRACK_SWITCHING,b({},r)),s)return;const n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||dt(e,r,ut)))return i}if(e){const{name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(dt({name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o},t[e],ut))return e}for(let i=0;i<t.length;i++){const r=t[i];if(Zs(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Zs(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&ft(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${s}`),this.hls.trigger(f.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null,track:e})}},emeController:jn,cmcdController:class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:hn.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:i}=e,r=this.hls.levels[t.level],s=this.getObjectType(t),n={d:1e3*(i||t).duration,ot:s};s!==hn.VIDEO&&s!==hn.AUDIO&&s!=hn.MUXED||(n.br=r.bitrate/1e3,n.tb=this.getTopBandwidth(s)/1e3,n.bl=this.getBufferLength(s));const a=i?this.getNextPart(i):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(f.MEDIA_DETACHED,this.onMediaDetached,this),e.on(f.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(f.MEDIA_DETACHED,this.onMediaDetached,this),e.off(f.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:dn.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){R(t,this.createData());const i=t.ot===hn.INIT||t.ot===hn.VIDEO||t.ot===hn.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce(((e,i)=>(r.includes(i)&&(e[i]=t[i]),e)),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),$n(e.headers,t,s)):e.url=Hn(e.url,t,s)}getNextFrag(e){var t;const i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){const t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t,i;const{index:r,fragment:s}=e,n=null==(t=this.hls.levels[s.level])||null==(i=t.details)?void 0:i.partList;if(n){const{sn:e}=s;for(let t=n.length-1;t>=0;t--){const i=n[t];if(i.index===r&&i.fragment.sn===e)return n[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?hn.TIMED_TEXT:"initSegment"===e.sn?hn.INIT:"audio"===t?hn.AUDIO:"main"===t?this.hls.audioTracks.length?hn.VIDEO:hn.MUXED:void 0}getTopBandwidth(e){let t,i=0;const r=this.hls;if(e===hn.AUDIO)t=r.audioTracks;else{const e=r.maxAutoLevel,i=e>-1?e+1:r.levels.length;t=r.levels.slice(0,i)}for(const e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){const t=this.media,i=e===hn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*ei.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}},contentSteeringController:class extends D{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(f.MANIFEST_PARSED,this.onManifestParsed,this),e.on(f.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(f.MANIFEST_PARSED,this.onManifestParsed,this),e.off(f.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((null==i?void 0:i.action)===It&&i.flags===_t){const e=this.levels;let r=this._pathwayPriority,s=this.pathwayId;if(t.context){const{groupId:i,pathwayId:r,type:n}=t.context;i&&e?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${nt(r)} penalized: ${nt(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this._pathwayPriority=e;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((e=>{r-i[e]>3e5&&delete i[e]}));for(let r=0;r<e.length;r++){const s=e[r];if(s in i)continue;if(s===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,hr(t),this.hls.trigger(f.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(t===p&&r[i].hasAudioGroup(e)||t===v&&r[i].hasSubtitleGroup(e))return r[i].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},r={};e.forEach((e=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new li(e.attrs);t["PATHWAY-ID"]=s;const n=t.AUDIO&&`${t.AUDIO}_clone_${s}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(r[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Wn(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new it({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${s}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${s}`);return h}));t.push(...o),Yn(this.audioTracks,i,a,s),Yn(this.subtitleTracks,r,a,s)}))}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;let r;this.loader&&this.loader.destroy(),this.loader=new i(t);try{r=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==r.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+e)}const s={responseType:"json",url:r.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,i,s)=>{this.log(`Loaded steering manifest: "${r}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(f.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}},interstitialsController:class extends D{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const i=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const r=this.playingItem;if(!r)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule()}if(this.checkBuffer(),i&&e<r.start||e>=r.end){var s;const e=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(r)&&null!=(s=this.media)&&s.paused&&(this.shouldPlay=!1),!i){const t=this.findItemIndex(r);if(e>t){const i=this.schedule.findJumpRestrictedIndex(t+1,e);if(i>t)return void this.setSchedulePosition(i)}}return void this.setSchedulePosition(e)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(r)){const t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;(i&&e<a||e>=a+o)&&this.setScheduleToAssetAtTime(e,n)},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const i=this.playingAsset;if(!i)return;e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{const i=this.schedule,r=this.playingItem,s=i.events||[],n=i.items||[],a=i.durations,o=e.map((e=>e.identifier)),l=!(!s.length&&!o.length);if(l&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s}\nSchedule: ${n.map((e=>da(e)))}`),o.length&&this.log(`Removed events ${o}`),this.playerQueue.forEach((e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(r){Math.abs(i)>ta&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}})),r){const e=this.updateItem(r,this.timelinePos);this.itemsMatch(r,e)&&(this.playingItem=e,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const h=this.bufferingItem;if(h){const e=this.updateItem(h,this.bufferedPos);this.itemsMatch(h,e)?this.bufferingItem=e:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))}if(e.forEach((e=>{e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,null)}))})),l||t){if(this.hls.trigger(f.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(r)&&o.includes(r.event.identifier))return this.warn(`Interstitial "${r.event.identifier}" removed while playing`),void this.primaryFallback(r.event);this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new ua(e),this.schedule=new ha(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(f.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(f.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(f.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(f.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(f.BUFFER_APPENDED,this.onBufferAppended,this),e.on(f.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(f.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(f.MEDIA_ENDED,this.onMediaEnded,this),e.on(f.ERROR,this.onError,this),e.on(f.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(f.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(f.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(f.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(f.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(f.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(f.BUFFER_CODECS,this.onBufferCodecs,this),e.off(f.BUFFER_APPENDED,this.onBufferAppended,this),e.off(f.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(f.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(f.MEDIA_ENDED,this.onMediaEnded,this),e.off(f.ERROR,this.onError,this),e.off(f.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){fa(e,"play",this.onPlay),fa(e,"pause",this.onPause),fa(e,"seeking",this.onSeeking),fa(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;ca(i,"seeking",this.onSeeking),ca(i,"timeupdate",this.onTimeupdate),ca(i,"play",this.onPlay),ca(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();const e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=t=>t?e.getAssetPlayer(t.identifier):t,r=(t,r,s,a,o)=>{if(t){let l=t[r].start;const h=t.event;if(h){if("playout"===r||h.timelineOccupancy!==ia.Point){const e=i(s);(null==e?void 0:e.interstitial)===h&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?n():e[a])-t.start}return l}return 0},s=(t,i)=>{if(0!==t&&"primary"!==i&&e.schedule.length){var r;const s=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[s];if(n){return t+(n[i].start-n.start)}}return t},n=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=t=>{var i;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:e.schedule.durations[t]},o=(t,s)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip)return;e.log(`seek to ${t} "${s}"`);const l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,s),d=null==(a=e.schedule.items)?void 0:a[h],u=e.getBufferingPlayer(),c=null==u?void 0:u.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(f||g)){const n=i(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const i="primary"===s?a.currentTime:r(l,s,e.playingAsset,"timelinePos","currentTime"),o=t-i,h=(f?i:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let i=t;if("primary"!==s){const e=t-d[s].start;i=d.start+e}const r=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!r&&!d.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(h>n){const t=e.schedule.findJumpRestrictedIndex(n+1,h);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(r)e.timelinePos=i,e.checkBuffer();else{var m;const e=null==d||null==(m=d.event)?void 0:m.assetList;if(e){const i=t-(d[s]||d).start;for(let t=e.length;t--;){const r=e[t];if(r.duration&&i>=r.startOffset&&i<r.startOffset+r.duration){a=t;break}}}}e.setSchedulePosition(h,a)}}else{const t=e.media||(f?null==u?void 0:u.media:null);t&&(t.currentTime=i)}}},l=()=>{const i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;const r=t();return e.isInterstitial(r)?r:null},h={get currentTime(){const t=l(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){const i=l(),r=e.effectivePlayingItem;r&&r===i&&o(t+r.playout.start,"playout")},get duration(){const e=l();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const i=null==(t=l())?void 0:t.event.assetList;return i?i.map((t=>e.getAssetPlayer(t.identifier))):[]},get playingIndex(){var t;const i=null==(t=l())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var t,i;return(null==(t=e.schedule)||null==(i=t.events)?void 0:i.slice(0))||[]},get schedule(){var t,i;return(null==(t=e.schedule)||null==(i=t.items)?void 0:i.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){o(e,"primary")},get duration(){return a("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){o(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){var t;return s((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){const r=e.findItemIndex(t);if(i.appendInPlace){const e=t.playout.start+t.event.duration;o(e+.001,"playout")}else e.advanceAfterAssetEnded(i,r,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t,i;if(null===this.mediaSelection)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let s=this.media;!s&&null!=(e=this.bufferingItem)&&null!=(t=e.event)&&t.appendInPlace&&(s=this.primaryMedia);const n=null==(i=s)?void 0:i.currentTime;return void 0!==n&&l(n)?n:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${nt(i)}`),this.detachedData=i}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var i,r;if(e.media===t)return;let s=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let h;if(n.media)o&&(s=n.transferMedia(),this.detachedData=s),h="Primary";else if(l){const e=this.getBufferingPlayer();e?(s=e.transferMedia(),h=`${e}`):h="detached MediaSource"}else h="detached media";if(!s)if(l)s=this.detachedData,this.log(`using detachedData: MediaSource ${nt(s)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach((e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}})),this.hls.detachMedia(),this.detachedData={media:t}}const d=s&&"mediaSource"in s&&"closed"!==(null==(r=s.mediaSource)?void 0:r.readyState),u=d&&s?s:t;if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${h}`),u===s){const t=a&&e.assetId===this.schedule.assetIdAtEnd;u.overrides={duration:this.schedule.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.timelinePos=i,t.length&&t[0].cue.pre){const i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const t=this.timelinePos=i>0?i:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){const t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAfterAssetEnded(e,t,i){const r=i+1;if(e.isAssetPastPlayoutLimit(r)||e.assetList[r].error){const i=this.schedule.items;if(i){const r=t+1;if(r>=i.length)return void this.setSchedulePosition(-1);const s=e.resumeTime;this.timelinePos<s&&(this.timelinePos=s,this.checkBuffer()),this.setSchedulePosition(r)}}else this.setSchedulePosition(t,r)}setScheduleToAssetAtTime(e,t){const i=this.schedule,r=t.parentIdentifier,s=i.getEvent(r);if(s){const t=i.findEventIndex(r),n=i.findAssetIndex(s,e);this.setSchedulePosition(t,n)}}setSchedulePosition(e,t){const i=this.schedule.items;if(!i||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const r=e>=0?i[e]:null,s=this.playingItem,n=this.playingLastItem;if(this.isInterstitial(s)){var a;const l=s.event,h=this.playingAsset,d=null==h?void 0:h.identifier,u=d?this.getAssetPlayer(d):null;if(u&&d&&(!this.eventItemsMatch(s,r)||void 0!==t&&d!==(null==(a=l.assetList)?void 0:a[t].identifier))){var o;const t=l.findAssetIndex(h);this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${l.assetList.length} ${oa(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(f.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:t,event:l,schedule:i.slice(0),scheduleIndex:e,player:u}),this.retreiveMediaSource(d,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(s,r)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${da(s)}`),l.hasPlayed=!0,this.hls.trigger(f.INTERSTITIAL_ENDED,{event:l,schedule:i.slice(0),scheduleIndex:e}),l.cue.once)){this.updateSchedule();const e=this.schedule.items;if(r&&e){const i=this.schedule.findItemIndex(r);this.advanceSchedule(i,e,t,s,n)}return}}this.advanceSchedule(e,i,t,s,n)}advanceSchedule(e,t,i,r,s){const n=e>=0?t[e]:null,a=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach((t=>{const i=t.interstitial,r=this.schedule.findEventIndex(i.identifier);(r<e||r>e+1)&&this.clearInterstitial(i,n)})),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);const s=n.event;void 0===i&&(i=this.schedule.findAssetIndex(s,this.timelinePos));const o=this.waitingItem;this.assetsBuffered(n,a)||this.setBufferingItem(n);let l=this.preloadAssets(s,i);if(this.eventItemsMatch(n,o||r)||(this.waitingItem=n,this.log(`INTERSTITIAL_STARTED ${da(n)} ${s.appendInPlace?"append in place":""}`),this.hls.trigger(f.INTERSTITIAL_STARTED,{event:s,schedule:t.slice(0),scheduleIndex:e})),!s.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${s}`);if(s.assetListLoader&&(s.assetListLoader.destroy(),s.assetListLoader=void 0),!a)return void this.log(`Waiting for attachMedia to start Interstitial ${s}`);this.waitingItem=this.endedItem=null,this.playingItem=n;const h=s.assetList[i];if(!h){const r=t[e+1],n=this.media;return r&&n&&!this.isInterstitial(r)&&n.currentTime<r.start&&(n.currentTime=this.timelinePos=r.start),void this.advanceAfterAssetEnded(s,e,i||0)}if(l||(l=this.getAssetPlayer(h.identifier)),null===l||l.destroyed){const e=s.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${s}`),l=this.createAssetPlayer(s,h,i)}if(!this.eventItemsMatch(n,this.bufferingItem)&&s.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(l,i,t,e,a),this.shouldPlay&&ga(l.media)}else null!==n?(this.resumePrimary(n,e,r),this.shouldPlay&&ga(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e,t;return null==(e=this.mediaSelection)||null==(t=e.main)?void 0:t.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,i){var r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${da(e)}`),null==(r=this.detachedData)||!r.mediaSource){let i=this.timelinePos;(i<e.start||i>=e.end)&&(i=this.getPrimaryResumption(e,t),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;const s=this.schedule.items;s&&(this.log(`resumed ${da(e)}`),this.hls.trigger(f.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(i<e.fragmentStart||i>e.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return ei.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const r=this.primaryMedia;if(!r)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(f.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(f.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level)return;const i=this.hls.levels[t.level],r=b(b({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r)return void(this.altSelection=b(b({},this.altSelection),{},{audio:i}));const s=b(b({},r),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r)return void(this.altSelection=b(b({},this.altSelection),{},{subtitles:i}));const s=b(b({},r),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(e,t){const i=lt(t);this.playerQueue.forEach((e=>e.hls.setAudioOption(t)||e.hls.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=lt(t);this.playerQueue.forEach((e=>e.hls.setSubtitleOption(t)||-1!==t.id&&e.hls.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const r=t[e];if(r.cue.post){var i;const e=this.schedule.findEventIndex(r.identifier),t=null==(i=this.schedule.items)?void 0:i[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){const i=this.schedule.items;if(e&&i){return i[this.findItemIndex(e,t)]||null}return null}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e?this.schedule.findItemIndex(e,t):-1}updateSchedule(){const e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])}checkBuffer(e){const t=this.schedule.items;if(!t)return;const i=ei.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,t,e)}updateBufferedPos(e,t,i){const r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e)return;if(1===t.length&&this.itemsMatch(t[0],s))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h;const i=this.findItemIndex(s),r=Math.min(i+1,t.length-1),n=t[r];if((-1===o&&s&&e>=s.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=r),r-a>1&&!1===(null==s||null==(h=s.event)?void 0:h.appendInPlace))return;if(this.bufferedPos=e,o>i&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,s)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some((e=>{const i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))}))}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:r,events:s}=i;if(!r||!s)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const i=a?a.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${da(e)}`+(t?` (${i.toFixed(2)} remaining)`:"")),n?e.event.assetList.forEach((e=>{const t=this.getAssetPlayer(e.identifier);t&&t.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((e=>e.pauseBuffering())))}this.hls.trigger(f.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){const e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){const r=i.assetList[t],s=this.primaryMedia;r&&s&&this.bufferAssetPlayer(e,s)}}}preloadAssets(e,t){const i=e.assetUrl,r=e.assetList.length,s=0===r&&!e.assetListLoader,n=e.cue.once;if(s){const s=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(s+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-s;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(e,0,0,s,e.duration,i);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&r){for(let i=t;i<r;i++){const t=e.assetList[i],r=this.getAssetPlayerQueueIndex(t.identifier);-1!==r&&!this.playerQueue[r].destroyed||t.error||this.createAssetPlayer(e,t,i)}return this.getAssetPlayer(e.assetList[t].identifier)}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach((t=>{this.hls.trigger(f.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null}createAsset(e,t,i,r,s,n){const a={parentIdentifier:e.identifier,identifier:ra(e,n,t),duration:s,startOffset:i,timelineStart:r,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){this.log(`create HLSAssetPlayer for ${oa(t)}`);const r=this.hls,s=r.userConfig;let n=s.videoPreference;const a=r.loadLevelObj||r.levels[r.currentLevel];(n||a)&&(n=R({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=r.audioTracks[r.audioTrack],l=r.subtitleTracks[r.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const i=t.duration;i&&e<i&&(h=e)}}const d=t.identifier,g=b(b({},s),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||s.audioPreference,subtitlePreference:l||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(g.timelineOffset=t.timelineStart));const m=g.cmcd;null!=m&&m.sessionId&&m.contentId&&(g.cmcd=R({},m,{contentId:ea(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const p=new la(this.HlsPlayerClass,g,e,t);this.playerQueue.push(p),e.assetList[i]=t;const v=r=>{if(r.live){const t=new Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:u.OTHER_ERROR,details:c.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};return void this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),i,t.message)}const s=r.edge-r.fragmentStart,n=t.duration;(null===n||s>n)&&(this.log(`Interstitial asset "${d}" duration change ${n} > ${s}`),t.duration=s,this.updateSchedule())};p.on(f.LEVEL_UPDATED,((e,{details:t})=>v(t))),p.on(f.LEVEL_PTS_UPDATED,((e,{details:t})=>v(t)));const y=(e,t)=>{const i=this.getAssetPlayer(d);if(i&&t.tracks){i.off(f.BUFFER_CODECS,y),i.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};p.on(f.BUFFER_CODECS,y);const E=()=>{var i;const r=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${r}`),!r)return;const s=this.schedule.findEventIndex(e.identifier),n=e.findAssetIndex(t),a=n+1,o=null==(i=this.schedule.items)?void 0:i[s];if(this.isInterstitial(o))if(-1===n||e.isAssetPastPlayoutLimit(a)||e.assetList[a].error){var l;const e=null==(l=this.schedule.items)?void 0:l[s+1];e&&this.bufferedToItem(e)}else this.bufferedToItem(o,a)};p.on(f.BUFFERED_TO_END,E);const T=t=>()=>{if(!this.getAssetPlayer(d))return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return p.once(f.MEDIA_ENDED,T(i)),p.once(f.PLAYOUT_LIMIT_REACHED,T(1/0)),p.on(f.ERROR,((t,r)=>{const s=this.getAssetPlayer(d);if(r.details!==c.BUFFER_STALLED_ERROR)this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${r.error} ${e}`);else if(null!=s&&s.media){const t=s.currentTime,i=s.duration-t;t&&e.appendInPlace&&i/s.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${d} ${e} at ${s.media.currentTime}`),E()):(this.warn(`Stalled at ${t} of ${t+i} in asset ${d} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}})),p.on(f.DESTROYING,(()=>{if(!this.getAssetPlayer(d))return;const t=new Error(`Asset player destroyed unexpectedly ${d}`),r={fatal:!0,type:u.OTHER_ERROR,details:c.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),i,t.message)})),this.hls.trigger(f.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:p}),p}clearInterstitial(e,t){e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,t)})),e.reset()}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(-1!==i){this.log(`clearAssetPlayer "${e}" toSegment: ${t?da(t):t}`);const r=this.playerQueue[i];this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,r,s){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),this.hls.trigger(f.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var i,r;const{interstitial:s,assetItem:n,assetId:a}=e,o=this.schedule.findEventIndex(s.identifier),l=null==(i=this.schedule.items)?void 0:i[o];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=n;const h=this.getBufferingPlayer();if(h===e)return;const d=s.appendInPlace;if(d&&!1===(null==h?void 0:h.interstitial.appendInPlace))return;const f=(null==h?void 0:h.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks)return;if(f&&!M(f,e.tracks)){const t=new Error(`Asset "${a}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(f)}')`),i={fatal:!0,type:u.OTHER_ERROR,details:c.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},r=s.findAssetIndex(n);return void this.handleAssetItemError(i,s,o,r,t.message)}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,i,r,s){if(e.details===c.BUFFER_STALLED_ERROR)return;const n=t.assetList[r]||null;let a=null;if(n){const e=this.getAssetPlayerQueueIndex(n.identifier);a=this.playerQueue[e]||null}const o=this.schedule.items,l=R({},e,{fatal:!1,errorAction:Ct(!0),asset:n,assetListIndex:r,event:t,schedule:o,scheduleIndex:i,player:a});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(f.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const h=new Error(s);n&&(this.playingAsset!==n&&this.clearAssetPlayer(n.identifier,null),n.error=h),t.assetList.some((e=>!e.error))?t.appendInPlace&&(t.error=h):t.error=h,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${i?da(i):"<none>"} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let r=this.timelinePos;-1===r&&(r=this.hls.startPosition);const s=this.updateItem(i,r);if(this.itemsMatch(i,s))this.clearInterstitial(e,null);else{const e=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(e)}}else this.checkStart()}onAssetListLoaded(e,t){var i;const r=t.event,s=r.identifier,n=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(s))return;const a=r.timelineStart,o=r.duration;let l=0;n.forEach(((e,t)=>{const i=parseFloat(e.DURATION);this.createAsset(r,t,l,a+l,i,e.URI),l+=i})),r.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${o}) ${r}`);const h=this.waitingItem,d=(null==h?void 0:h.event.identifier)===s;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(d){var c;const e=this.schedule.findEventIndex(s),t=null==(c=this.schedule.items)?void 0:c[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${r}`),void this.primaryFallback(r)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===s&&u.appendInPlace){const e=r.assetList[0],t=this.getAssetPlayer(e.identifier),i=this.primaryMedia;e&&t&&i&&this.bufferAssetPlayer(t,i)}}onError(e,t){switch(t.details){case c.ASSET_LIST_PARSING_ERROR:case c.ASSET_LIST_LOAD_ERROR:case c.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&this.primaryFallback(e);break}case c.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}}}});function To(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(To):Object.keys(e).reduce(((t,i)=>(t[i]=To(e[i]),t)),{}):e}function So(e,t){const i=e.loader;if(i!==go&&i!==yo)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=go,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Ao extends zt{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(f.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const i=this.media=t.media;ca(i,"playing",this.onMediaPlaying),ca(i,"waiting",this.onMediaWaiting),ca(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(fa(i,"playing",this.onMediaPlaying),fa(i,"waiting",this.onMediaWaiting),fa(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,r;const s=null==(i=this.hls)?void 0:i.config;if(!s)return;const{media:n,stalled:a}=this;if(!n)return;const{seeking:o}=n,l=this.seeking&&!o,h=!this.seeking&&o,d=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,e!==t)return t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(h||l)return void(l&&this.stallResolved(e));if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(f.MEDIA_ENDED,{stalled:!1})));if(!ei.getBuffered(n).length)return void(this.nudgeRetry=0);const u=ei.bufferInfo(n,e,0),c=u.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const t=Lo(this.hls.inFlightFragments,e),i=u.len>2,r=!c||t||c-e>2&&!g.getPartialFragment(e);if(i||r)return;this.moved=!1}const m=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&g){if(!(u.len>0)&&!c)return;const t=Math.max(c,u.start||0)-e,i=!(null==m||!m.live)?2*m.targetduration:2,r=g.getPartialFragment(e);if(t>0&&(t<=i||r))return void(n.paused||this._trySkipBufferHole(r))}const p=s.detectStallWithCurrentTimeMs,v=self.performance.now(),y=this.waiting;if(null===a)return void(this.stalled=y>0&&v-y<p?y:v);const E=v-a;if(!o&&(E>=p||y)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==m||!m.live)&&Math.abs(e-((null==m?void 0:m.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(f.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}const S=ei.bufferInfo(n,e,s.maxBufferHole);this._tryFixBufferStall(S,E)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(f.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){const i=ei.bufferedInfo(ei.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const i=ei.timeRangesToArray(r),s=ei.bufferedInfo(i,t,0).bufferedIndex;if(s>-1&&s<i.length-1){const t=ei.bufferedInfo(i,e,0).bufferedIndex,r=i[s].end,n=i[s+1].start;if((-1===t||t>s)&&n-r<1&&e-r<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${n} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;const s=this.fragmentTracker.getPartialFragment(e)||void 0,a=ei.bufferInfo(this.media,e,0);this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:s,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t){var i,r;const{fragmentTracker:s,media:n}=this,a=null==(i=this.hls)?void 0:i.config;if(!n||!s||!a)return;const o=n.currentTime,l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=s.getPartialFragment(o);if(h||null!=l&&l.live&&o<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=e.buffered;(d&&d.length>1&&e.len>a.maxBufferHole||e.nextStart&&e.nextStart-o<a.maxBufferHole)&&(t>1e3*a.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_reportStall(e){const{hls:t,media:i,stallReported:r,stalled:s}=this;if(!r&&null!==s&&i&&t){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${nt(e)})`);this.warn(r.message),t.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:r}=this,s=null==(t=this.hls)?void 0:t.config;if(!r||!i||!s)return 0;const n=r.currentTime,a=ei.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=s.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,d=o-n;if(d>0&&(t||h)){if(d>s.maxBufferHole){let t=!1;if(0===n){const e=i.getAppendedFrag(0,y);e&&o<e.end&&(t=!0)}if(!t){const t=e||i.getAppendedFrag(n,y);if(t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Lo(this.hls.inFlightFragments,o))return 0;let e=!1,r=t.end;for(;r<o;){const t=i.getPartialFragment(r);if(!t){e=!0;break}r+=t.duration}if(e)return 0}}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,r.currentTime=t,null==e||!e.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`);this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:r}=this,s=null==t?void 0:t.config;if(!i||!s)return 0;const n=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){const a=n+(r+1)*s.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,t.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${s.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Lo(e,t){const i=Ro(e.main);if(i&&i.start<=t)return i;const r=Ro(e.audio);return r&&r.start<=t?r:null}function Ro(e){if(!e)return null;switch(e.state){case pr.IDLE:case pr.STOPPED:case pr.ENDED:case pr.ERROR:return null}return e.frag}function Io(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function bo(e,t,i,r,s){let n=new e(t,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new e(t,i,nt(s?b({type:s},r):r))}return n}const Do=(()=>{const e=Io();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ko{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(f.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e.on(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(f.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(f.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(f.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(f.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(f.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&zn(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if("metadata"===i.kind&&"id3"===i.label)return Xn(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:r}}}=this;if(!i&&!r)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Io();if(n)for(let e=0;e<s.length;e++){const t=s[e].type;if(t===Qr.emsg&&!i||!r)continue;const a=Wr(s[e].data);if(a){const i=s[e].pts;let r=i+s[e].duration;r>Do&&(r=Do);r-i<=0&&(r=i+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!jr(s)){this.updateId3CueEnds(i,t);const e=bo(n,i,r,s,t);e&&this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var i;const r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){const s=r[i];s.type===t&&s.startTime<e&&s.endTime===Do&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let e;e="audio"===r?e=>e.type===Qr.audioId3&&o:"video"===r?e=>e.type===Qr.emsg&&a:e=>e.type===Qr.audioId3&&o||e.type===Qr.emsg&&a,Jn(s,t,i,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:i}=this,{dateRanges:r}=e,s=Object.keys(r);let n=this.dateRangeCuesAppended;var a;if(i&&t)if(null!=(a=i.cues)&&a.length){const e=Object.keys(n).filter((e=>!s.includes(e)));for(let t=e.length;t--;){const r=e[t],s=n[r].cues;delete n[r],Object.keys(s).forEach((e=>{try{const t=s[e];t.removeEventListener("enter",this.onEventCueEnter),i.removeCue(t)}catch(e){}}))}}else n=this.dateRangeCuesAppended={};const o=e.fragments[e.fragments.length-1];if(0===s.length||!l(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=Io();for(let e=0;e<s.length;e++){const t=s[e],i=r[t],a=i.startTime,o=n[t],l=(null==o?void 0:o.cues)||{};let c=(null==o?void 0:o.durationKnown)||!1,f=Do;const{duration:g,endDate:m}=i;if(m&&null!==g)f=a+g,c=!0;else if(i.endOnNext&&!c){const e=s.reduce(((e,t)=>{if(t!==i.id){const s=r[t];if(s.class===i.class&&s.startDate>i.startDate&&(!e||i.startDate<e.startDate))return s}return e}),null);e&&(f=e.startTime,c=!0)}const p=Object.keys(i.attr);for(let e=0;e<p.length;e++){const r=p[e];if("ID"===(u=r)||"CLASS"===u||"CUE"===u||"START-DATE"===u||"DURATION"===u||"END-DATE"===u||"END-ON-NEXT"===u)continue;const s=l[r];if(s)c&&!o.durationKnown?s.endTime=f:Math.abs(s.startTime-a)>.01&&(s.startTime=a,s.endTime=f);else if(h){let e=i.attr[r];hi(r)&&(d=e,e=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const s=bo(h,a,f,{key:r,data:e},Qr.dateRange);s&&(s.id=t,this.id3Track.addCue(s),l[r]=s,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==r&&"X-ASSET-URL"!==r||s.addEventListener("enter",this.onEventCueEnter)))}}n[t]={cues:l,dateRange:i,durationKnown:c}}var d,u}}class _o{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,r=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,r)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);const h=r;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const i=this.levelDetails;if(null===i)return null;const r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(f.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(f.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(f.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(f.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===c.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(r=this.targetLatency)?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class Po extends zs{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(f.LEVEL_LOADED,this.onLevelLoaded,this),e.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(f.FRAG_BUFFERED,this.onFragBuffered,this),e.on(f.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(f.LEVEL_LOADED,this.onLevelLoaded,this),e.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(f.FRAG_BUFFERED,this.onFragBuffered,this),e.off(f.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(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,r=[],s={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t;const h=e.attrs;let{audioCodec:d,videoCodec:u}=e;d&&(e.audioCodec=d=Be(d,i)||void 0),0===(null==(t=u)?void 0:t.indexOf("avc1"))&&(u=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");if(i.length>2){let r=i.shift()+".";r+=parseInt(i.shift()).toString(16),r+=("000"+parseInt(i.shift()).toString(16)).slice(-4),t[e]=r}}return t.join(",")}(u));const{width:c,height:f,unknownCodecs:g}=e;let m=g?g.length:0;if(g)for(let t=m;t--;){const i=g[t];this.isAudioSupported(i)?(e.audioCodec=d=d?`${d},${i}`:i,m--,Pe.audio[d.substring(0,4)]=2):this.isVideoSupported(i)&&(e.videoCodec=u=u?`${u},${i}`:i,m--,Pe.video[u.substring(0,4)]=2)}if(a||(a=!(!c||!f)),o||(o=!!u),l||(l=!!d),m||d&&!this.isAudioSupported(d)||u&&!this.isVideoSupported(u))return void this.log(`Some or all CODECS not supported "${h.CODECS}"`);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=h,A=`${`${E||"."}-`}${e.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(s[A])if(s[A].uri===e.url||e.attrs["PATHWAY-ID"])s[A].addGroupId("audio",h.AUDIO),s[A].addGroupId("text",h.SUBTITLES);else{const t=n[A]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=this.createLevel(e);s[A]=i,r.push(i)}else{const t=this.createLevel(e);s[A]=t,n[A]=1,r.push(t)}})),this.filterAndSortMediaOptions(r,t,a,o,l)}createLevel(e){const t=new it(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=Ye(e,[])}return t}isAudioSupported(e){return we(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return we(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,r,s){let n=[],a=[],o=e;if((i||r)&&s&&(o=o.filter((({videoCodec:e,videoRange:t,width:i,height:r})=>{return(!!e||!(!i||!r))&&(!!(s=t)&&Qe.indexOf(s)>-1);var s}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${nt(t.levels.map((e=>e.attrs.CODECS)).filter(((e,t,i)=>i.indexOf(e)===t)))}`,this.warn(i),e+=` (${i})`);const r=new Error(e);this.hls.trigger(f.ERROR,{type:u.MEDIA_ERROR,details:c.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}));t.audioTracks&&(n=t.audioTracks.filter((e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),Co(n)),t.subtitles&&(a=t.subtitles,Co(a));const l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Qe.indexOf(e.videoRange)-Qe.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=Me(e.videoCodec),r=Me(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=Fe(e.codecSet),r=Fe(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){h=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===h){var d;this._firstLevel=e;const t=h.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${t}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const g=s&&!r,m=this.hls.config,p=!(!m.audioStreamController||!m.audioTrackController),v={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:p&&!g&&n.some((e=>!!e.url))};this.hls.trigger(f.MANIFEST_PARSED,v)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&r&&s===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${s?" with Pathway "+s:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(f.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==r?void 0:r.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter((e=>-1!==t.indexOf(e)));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===m&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===y){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:r,details:s}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${i}`),this.hls.trigger(f.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const i=this._levels.filter(((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));hr(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(f.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(f.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Co(e){const t={};e.forEach((e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function wo(){return self.SourceBuffer||self.WebKitSourceBuffer}function xo(){if(!O())return!1;const e=wo();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Oo extends vr{constructor(e,t,i){super(e,t,i,"stream-controller",y),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!l(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const i=this.getFwdBufferInfoAtPos(e,t,y,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(f.MANIFEST_PARSED,this.onManifestParsed,this),e.on(f.LEVEL_LOADING,this.onLevelLoading,this),e.on(f.LEVEL_LOADED,this.onLevelLoaded,this),e.on(f.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(f.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(f.BUFFER_CREATED,this.onBufferCreated,this),e.on(f.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(f.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(f.MANIFEST_PARSED,this.onManifestParsed,this),e.off(f.LEVEL_LOADED,this.onLevelLoaded,this),e.off(f.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(f.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(f.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(f.BUFFER_CREATED,this.onBufferCreated,this),e.off(f.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(f.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=pr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=pr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case pr.WAITING_LEVEL:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=pr.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=pr.IDLE;break}break}case pr.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,i=null==e?void 0:e[t];this.resetStartWhenNotLoaded(i||null),this.state=pr.IDLE}}}this.state===pr.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==i||!i[s])return;const n=i[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(f.BUFFER_EOS,e),void(this.state=pr.ENDED)}if(!this.buffering)return;e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=n.details;if(!l||this.state===pr.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=pr.WAITING_LEVEL,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let c=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&c&&J(c)&&this.fragmentTracker.getState(c)!==Mt){var g;const e=(null!=(g=this.backtrackFragment)?g:c).sn-l.startSN,t=l.fragments[e-1];t&&c.cc===t.cc&&(c=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){const e=this.audioOnly&&!this.altAudio?q:X,t=(e===X?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,y)}c=this.getNextFragmentLoopLoading(c,l,a,y,d)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,n,u))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);r===wt||r===Ot?J(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,y)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case pr.KEY_LOADING:case pr.FRAG_LOADING:case pr.FRAG_LOADING_WAITING_RETRY:case pr.PARSING:case pr.PARSED:this.state=pr.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;ca(i,"playing",this.onMediaPlaying),ca(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(fa(i,"playing",this.onMediaPlaying),fa(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(f.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),r=r||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!function(){var e;const t=wo();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==pr.IDLE)return;const r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=pr.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:r,startFragRequested:s}=this,n=t.level,a=t.details,o=a.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==pr.FRAG_LOADING&&this.state!==pr.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,d),this.hls.trigger(f.LEVEL_UPDATED,{details:a,level:n}),this.state===pr.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=pr.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const r=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&i.readyState<4||s<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),i.currentTime=r))}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:r,payload:s}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=i.initSegment)?void 0:t.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Qs(this.hls,y,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Jt(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];c.push(s,d,u,l,i,r,o.totalduration,h,m,p)}onAudioTrackSwitching(e,t){const i=this.hls,r=2===this.altAudio;if(ft(t.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 e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r)return this.fragmentTracker.removeAllFragments(),i.once(f.BUFFER_FLUSHED,(()=>{var e;null==(e=this.hls)||e.trigger(f.AUDIO_TRACK_SWITCHED,t)})),void i.trigger(f.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(f.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=ft(t.url,this.hls);if(i){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,s,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(s=e,r=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:r}=t,s=i.type===y;if(s){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===pr.PARSED&&(this.state=pr.IDLE));const e=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),J(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}const n=this.media;n&&(!this._hasEnoughToStart&&ei.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal)this.state=pr.ERROR;else switch(t.details){case c.FRAG_GAP:case c.FRAG_PARSING_ERROR:case c.FRAG_DECRYPT_ERROR:case c.FRAG_LOAD_ERROR:case c.FRAG_LOAD_TIMEOUT:case c.KEY_LOAD_ERROR:case c.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(y,t);break;case c.LEVEL_LOAD_ERROR:case c.LEVEL_LOAD_TIMEOUT:case c.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==pr.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==m||(this.state=pr.IDLE);break;case c.BUFFER_ADD_CODEC_ERROR:case c.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case c.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case c.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=pr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==q||!this.altAudio){const e=(t===X?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,y),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log(`could not seek to ${i}, already seeking at ${t}`);const r=this.timelineOffset;r&&i&&(i+=r);const s=this.getLevelDetails(),n=ei.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((e=>{const{hls:i}=this,r=null==e?void 0:e.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=pr.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const s=r.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(f.FRAG_LOADED,e),r.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const i=this.playlistType,{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:h,level:d}=a,{video:u,text:c,id3:g,initSegment:m}=s,{details:p}=d,v=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=pr.PARSING,m){if(null!=m&&m.tracks){const e=o.initSegment||o;this._bufferInitSegment(d,m.tracks,e,n),r.trigger(f.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:m.tracks})}const e=m.initPTS,t=m.timescale;l(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(f.INIT_PTS_FOUND,{frag:o,id:i,initPTS:e,timescale:t}))}if(u&&p){v&&"audiovideo"===u.type&&this.logMuxedErr(o);const e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,i=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:r,startDTS:s,endDTS:a}=u;if(h)h.elementaryStreams[u.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:a};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&n<l-this.config.maxBufferHole&&!i)return void this.backtrack(o);i&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,r,o.start,a,!0)}else t&&e-(p.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,e,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,h,n,t||i)}else{if(!t&&!i)return void this.backtrack(o);o.gap=!0}}if(v){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=v;h&&(h.elementaryStreams[q]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(q,e,t,i,r),this.bufferFragmentData(v,o,h,n)}if(p&&null!=g&&null!=(t=g.samples)&&t.length){const e={id:i,frag:o,details:p,samples:g.samples};r.trigger(f.FRAG_PARSING_METADATA,e)}if(p&&c){const e={id:i,frag:o,details:p,samples:c.samples};r.trigger(f.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${J(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,r){if(this.state!==pr.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:s,video:n,audiovideo:a}=t;if(s){let i=Ge(s.codec,e.audioCodec);"mp4a"===i&&(i="mp4a.40.5");const r=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===r.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==r.indexOf("android")&&"audio/mpeg"!==s.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),e.audioCodec&&e.audioCodec!==i&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${i}"`),s.levelCodec=i,s.id=y,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${i||""}/${e.audioCodec||""}/${s.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=y;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(f.BUFFER_CODECS,t),!this.hls)return;o.forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(f.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,y)}get maxBufferLength(){const{levels:e,level:t}=this,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=pr.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(ei.isBuffered(e,i)?t=this.getAppendedFrag(i):ei.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(f.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(f.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return l(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(l(t)){const e=this.getLevelDetails(),i=this.currentFrag||(e?mt(null,e.fragments,t):null);if(i){const e=i.programDateTime;if(null!==e){const r=e+1e3*(t-i.start);return new Date(r)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Mo{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=c.KEY_LOAD_ERROR,i,r,s){return new Qt({type:u.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let e=0;e<t.length;e++){const s=t[e];if(r<=s.cc&&("initSegment"===i||"initSegment"===s.sn||i<s.sn)){this.emeController.selectKeySystemFormat(s).then((e=>{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,c.KEY_LOAD_ERROR,i))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,c.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,c.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,i)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=new(0,i.loader)(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,c.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,c.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,b({url:a.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,c.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,c.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,h)}))}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}function Fo(e){const{type:t}=e;switch(t){case p:return E;case v:return T;default:return y}}function No(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class Uo{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(f.MANIFEST_LOADING,this.onManifestLoading,this),e.on(f.LEVEL_LOADING,this.onLevelLoading,this),e.on(f.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(f.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(f.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(f.MANIFEST_LOADING,this.onManifestLoading,this),e.off(f.LEVEL_LOADING,this.onLevelLoading,this),e.off(f.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(f.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(f.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:g,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:m,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:p,url:s,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:v,url:s,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const i=this.loaders[m];if(i){const e=i.context;e&&!t.levels.some((t=>t===e.levelOrTrack))&&(i.abort(),delete this.loaders[m])}}load(e){var t;const i=this.hls.config;let r,s=this.getInternalLoader(e);if(s){const t=this.hls.logger,i=s.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(r=e.type===g?i.manifestLoadPolicy.default:R({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),l(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===m&&null!==e.level?t=this.hls.levels[e.level].details:e.type===p&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===v&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);r=R({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,r)=>{const s=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),$i.isMediaPlaylist(n)||i.type!==g?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)):this.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};s.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,r){const s=this.hls,n=e.data,a=No(e,i),o=$i.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,i,o.playlistParsingError,r,t);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:g}=o;this.variableList=g;const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=$i.parseMasterPlaylistMedia(n,a,o);if(m.length){m.some((e=>!e.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new li({}),bitrate:0,url:""}))}s.trigger(f.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:v,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,r,s){const n=this.hls,{id:a,level:o,type:h}=i,d=No(e,i),u=l(o)?o:l(a)?a:0,c=Fo(i),m=$i.parseLevelPlaylist(e.data,d,u,c,0,this.variableList);if(h===g){const e={attrs:new li({}),bitrate:0,details:m,name:"",url:d};m.requestScheduled=t.loading.start+nr(m,0),n.trigger(f.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.MANIFEST_PARSING_ERROR,fatal:t.type===g,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===m?n+=`: ${e.level} id: ${e.id}`:e.type!==p&&e.type!==v||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=c.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case g:o=i?c.MANIFEST_LOAD_TIMEOUT:c.MANIFEST_LOAD_ERROR,l=!0;break;case m:o=i?c.LEVEL_LOAD_TIMEOUT:c.LEVEL_LOAD_ERROR,l=!1;break;case p:o=i?c.AUDIO_TRACK_LOAD_TIMEOUT:c.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case v:o=i?c.SUBTITLE_TRACK_LOAD_TIMEOUT:c.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const d={type:u.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){const i=(null==t?void 0:t.url)||e.url;d.response=b({url:i,data:void 0},r)}this.hls.trigger(f.ERROR,d)}handlePlaylistLoaded(e,t,i,r,s,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:E}=r,T=No(t,r),S=Fo(r),A="number"==typeof r.level&&S===y?l:void 0;if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.LEVEL_EMPTY_ERROR,fatal:!1,url:T,error:n,reason:n.message,response:t,context:r,level:A,parent:S,networkDetails:s,stats:i})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const L=e.playlistParsingError;if(L){if(this.hls.logger.warn(L),!a.config.ignorePlaylistParsingErrors)return void a.trigger(f.ERROR,{type:u.NETWORK_ERROR,details:c.LEVEL_PARSING_ERROR,fatal:!1,url:T,error:L,reason:L.message,response:t,context:r,level:A,parent:S,networkDetails:s,stats:i});e.playlistParsingError=null}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case g:case m:a.trigger(f.LEVEL_LOADED,{details:e,levelInfo:r.levelOrTrack||a.levels[0],level:A||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:E,withoutMultiVariant:o===g});break;case p:a.trigger(f.AUDIO_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:E});break;case v:a.trigger(f.SUBTITLE_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:E})}}}class Bo{static get version(){return Rr}static isMSESupported(){return xo()}static isSupported(){return function(){if(!xo())return!1;const e=O();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(Oe(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(Oe(t,"audio")))))}()}static getMediaSource(){return O()}static get Events(){return f}static get MetadataSchema(){return Qr}static get ErrorTypes(){return u}static get ErrorDetails(){return c}static get DefaultConfig(){return Bo.defaultConfig?Bo.defaultConfig:Eo}static set DefaultConfig(e){Bo.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Lr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,i){const r=P();if("object"==typeof console&&!0===e||"object"==typeof e){const s=["debug","log","info","warn","error"];s.forEach((t=>{r[t]=C(t,e,i)}));try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.2`)}catch(e){return P()}s.forEach((t=>{w[t]=C(t,e)}))}else R(w,r);return r}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){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(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=To(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];s.forEach((i=>{const s=`${e}Loading${i}`,l=t[s];if(void 0!==l&&a){o.push(s);const e=r[n].default;switch(t[n]={default:e},i){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${nt(t[n])}`)})),b(b({},r),t)}(Bo.DefaultConfig,e,t);this.userConfig=e,i.progressive&&So(i,t);const{abrController:r,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),h=this.abrController=new r(this),d=new Ft(this),u=i.interstitialsController,c=u?this.interstitialsController=new u(this,Bo):null,g=this.bufferController=new s(this,d),m=this.capLevelController=new n(this),p=new o(this),v=new Uo(this),y=i.contentSteeringController,E=y?new y(this):null,T=this.levelController=new Po(this,E),S=new ko(this),A=new Mo(this.config),L=this.streamController=new Oo(this,d,A),I=this.gapController=new Ao(this,d);m.setStreamController(L),p.setStreamController(L);const D=[v,T,L];c&&D.splice(1,0,c),E&&D.splice(1,0,E),this.networkControllers=D;const k=[h,g,I,m,p,S,d];this.audioTrackController=this.createController(i.audioTrackController,D);const _=i.audioStreamController;_&&D.push(this.audioStreamController=new _(this,d,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const x=i.subtitleStreamController;x&&D.push(this.subtititleStreamController=new x(this,d,A)),this.createController(i.timelineController,k),A.emeController=this.emeController=this.createController(i.emeController,k),this.cmcdController=this.createController(i.cmcdController,k),this.latencyController=this.createController(_o,k),this.coreComponents=k,D.push(l);const O=l.onErrorOut;"function"==typeof O&&this.on(f.ERROR,O,l),this.on(f.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===f.ERROR;this.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(f.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 e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(f.ERROR,{type:u.OTHER_ERROR,details:c.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(f.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(f.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(f.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,r=this._url=W.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(f.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((e=>{e.resumeBuffering&&e.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((e=>{e.pauseBuffering&&e.pauseBuffering()})))}get inFlightFragments(){const e={[y]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[E]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[T]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)}))}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Xe.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(r=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=i)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return qe(e,ot(t),navigator.mediaCapabilities)}}Bo.defaultConfig=void 0;var Go=i(74072),$o=i.n(Go),Ko=function(e,t,i,r,s,n){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?r.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(e){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(e||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},Vo=function(e,t,i){for(var r=arguments.length>2,s=0;s<t.length;s++)i=r?t[s].call(e,i):t[s].call(e);return r?i:void 0},Ho=function(e,t,i){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:i?"".concat(i," ",t):t})},Yo=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},Wo=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};let jo=(()=>{var e,t;let i,l,h=[a.JW],d=[],u=n.F;l=class extends u{get hlsInstance(){return this.hls}constructor(i,r){super(i,r),e.set(this,null),t.set(this,!1),this.dvrSegmentDuration=0,this.dvrWindowRight=0,this.dvrWindowLeft=0,this.dvrTime=-1,this.dvrRightToLiveOffset=0,this.dvrToDateSync=null,this.recoverDecodingErrorDate=-1,this.recoverSwapAudioCodecDate=-1,this.networkRecoveryHandler=null,this.hls=null,this.lastTickerUpdate=-1,this._dvrModeEnabled=!1,this._dvrWindow=0,this._dvrIsLive=!1,this.dvrTime=-1,this.dvrRightToLiveOffset=0,this.dvrToDateSync=null}get isPlayingSpatialAudio(){var e,t,i;return(null!==(t=null===(e=this.audioTrack)||void 0===e?void 0:e.channelCount)&&void 0!==t?t:0)>5||!0===(null===(i=this.audioTrack)||void 0===i?void 0:i.isAtmos)}applyVideoScale(e){this.mediaElement.style.objectFit="COVER"===e?"cover":"contain"}onError(e){var t;"error"===e.type&&e.currentTarget instanceof HTMLMediaElement&&(null===(t=e.currentTarget.error)||void 0===t?void 0:t.code)===MediaError.MEDIA_ERR_DECODE?this.handleHLSMediaError():this.handleError(e)}onSeekEnd(e){super.onSeekEnd(e),this.updateDVRValues()}onDurationChange(e){super.onDurationChange(e),this.dvrWindowRight=this.mediaElement.duration-this.dvrRightToLiveOffset,this.dvrWindowLeft=this.dvrWindowRight-this._dvrWindow}addSource(i){this.resetNetworkErrorHandler(),Yo(this,t,!1,"f");const s=$o().isSupported()&&i.url.indexOf("m3u8")>0;if(this.hls&&(this.hls.destroy(),this.hls=null),s){Yo(this,e,i,"f");const s={debug:!1,enableWorker:!0,liveSyncDurationCount:2,capLevelToPlayerSize:!0,startFragPrefetch:!0,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,manifestLoadingMaxRetry:2,manifestLoadingRetryDelay:500,manifestLoadingMaxRetryTimeout:64e3,levelLoadingMaxRetry:3,levelLoadingRetryDelay:500,levelLoadingMaxRetryTimeout:2e3},n=(0,o.$N)(this.pc.getPluginData("plugin-hls"),this.mc.getPluginData("plugin-hls")),a=(0,o.$N)(s,n);this._pendingSeek>0&&(a.startPosition=this._pendingSeek),a.timelineController=class extends oo{constructor(e){super(e),this.lastTracksLength=0,e.on(f.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdatedModifier,this)}get superTextTracks(){return this.textTracks}onSubtitleTracksUpdatedModifier(e,t){if(this.lastTracksLength!==this.superTextTracks.length){this.lastTracksLength=this.superTextTracks.length;const e=t.subtitleTracks;this.superTextTracks.length>1&&e.length&&e.forEach(((e,t)=>{e.forced&&(this.superTextTracks[t].isForced=!0)}))}}},this.log("HLS.js config:",a),this.hls=new($o())(a),this.hls.subtitleDisplay=!1,this.recoverDecodingErrorDate=-1,this.recoverSwapAudioCodecDate=-1,this.hls.attachMedia(this.mediaElement),this.hls.on($o().Events.MEDIA_ATTACHED,(()=>{var e;this.player.pixelController&&this.player.pixelController.loadStream(i.url),null===(e=this.hls)||void 0===e||e.loadSource(i.url),this.isPlaying()&&this.mediaElement.play()}));let l=!1;this.hls.on($o().Events.ERROR,((e,t)=>{var r,s,n,a,o,h,d,u,f,g,m,p,v;if(t.fatal)switch(t.type){case $o().ErrorTypes.NETWORK_ERROR:if(this.warn("fatal network error encountered",t.details,t.reason,t.networkDetails,null===(r=navigator.connection)||void 0===r?void 0:r.downlink),"object"==typeof navigator.connection&&(null!==(s=navigator.connection.downlink)&&void 0!==s?s:1)<=0)return this.warn("navigator says offline - add change handler"),this.networkRecoveryHandler=()=>{var e;this.log("network change, try to recover"),l=!0,null===(e=this.hls)||void 0===e||e.startLoad()},void navigator.connection.addEventListener("change",this.networkRecoveryHandler);if(null==this.hls||l){this.error("irrecoverable"),null===(n=this.hls)||void 0===n||n.destroy();const e=t.networkDetails;this.handleError(`${t.details} ${null!==(a=t.reason)&&void 0!==a?a:""} - Status: ${null!==(o=e.status)&&void 0!==o?o:-1} ${null!==(h=e.statusText)&&void 0!==h?h:""} - Response: ${null!==(d=e.response)&&void 0!==d?d:"null"}`)}else l=!0,[c.MANIFEST_LOAD_ERROR,c.MANIFEST_LOAD_TIMEOUT,c.MANIFEST_PARSING_ERROR,c.MANIFEST_INCOMPATIBLE_CODECS_ERROR].includes(t.details)||(null!==(g=null===(f=null===(u=this.hls)||void 0===u?void 0:u.levels)||void 0===f?void 0:f.length)&&void 0!==g?g:0)<1?(this.warn("manifest not loaded, try complete re-set"),null===(m=this.hls)||void 0===m||m.loadSource(i.url),this.mediaElement.play()):(this.log("try to recover"),null===(p=this.hls)||void 0===p||p.startLoad());break;case $o().ErrorTypes.MEDIA_ERROR:case $o().ErrorTypes.MUX_ERROR:this.warn("fatal media error encountered, try to recover"),this.handleHLSMediaError();break;default:this.error("fatal error",e,t),null===(v=this.hls)||void 0===v||v.destroy(),this.handleError()}})),this.hls.on($o().Events.LEVEL_LOADED,((e,i)=>{var s,n;this._dvrModeEnabled=this.mc.isDvrEnabled&&i.details.live,this.mc.isLive&&!i.details.live&&this.log("config mismatch: MC is live, stream is not!"),this.dvrSegmentDuration=i.details.targetduration,this.dvrRightToLiveOffset=(null!==(n=null===(s=this.hls)||void 0===s?void 0:s.config.liveSyncDurationCount)&&void 0!==n?n:0)*this.dvrSegmentDuration+1,this._dvrWindow=i.details.totalduration-this.dvrRightToLiveOffset,(this.dvrTime<0||isNaN(this.dvrTime))&&(this.dvrTime=this.getDuration()),this.updateDVRValues(),Wo(this,t,"f")||(this.player.loop.dispatchEvent(r.a.EVENT_STREAM_LOADED,{}),Yo(this,t,!0,"f"))})),this.hls.on($o().Events.FRAG_LOADED,((e,t)=>{const i=t.frag;if("main"===i.type)if(!i.programDateTime||isNaN(this.dvrWindowLeft)){if(i.sn&&"initSegment"!==i.sn&&i.duration&&!isNaN(this.dvrWindowLeft)){let e=i.duration;const t=i.tagList||[];for(const i of t)if("INF"===i[0]){e=Number(i[1]);break}const r=i.sn*e*1e3,s=new Date(r),n=new Date;if(s.getFullYear()!==n.getFullYear())return;const a=i.start-this.dvrWindowLeft;this.dvrToDateSync={rel:a,real:r,at:Date.now()}}}else{const e=i.start-this.dvrWindowLeft;this.dvrToDateSync={rel:e,real:i.programDateTime,at:Date.now()}}})),this.hls.on($o().Events.AUDIO_TRACKS_UPDATED,((e,t)=>{var i,r,s,n,a,l;this.audioTracks=[];const h=null!==(r=null===(i=this.hls)||void 0===i?void 0:i.audioTrack)&&void 0!==r?r:-1;for(const e of t.audioTracks){const t=h<0?e.default:h===this.audioTracks.length,i=(0,o.i5)(e.attrs,"CHANNELS")?parseInt(String(e.attrs.CHANNELS),10):void 0,r=(0,o.i5)(e.attrs,"CHARACTERISTICS")?String(e.attrs.CHARACTERISTICS).includes("public.accessibility.describes-video"):/audio\s*des[ck]ription/i.test(e.name),d={id:String(e.id),default:e.default,label:e.name,language:null!==(s=e.lang)&&void 0!==s?s:"und",isSpeechOptimized:/klare\s*sprache/i.test(e.name),isSimpleLanguage:/einfache\s*sprache/i.test(e.name),isAtmos:/dolby\s*atmos/i.test(e.name)||/ea?c3-joc/i.test(null!==(n=e.audioCodec)&&void 0!==n?n:"")||/immersive/i.test(null!==(a=e.channels)&&void 0!==a?a:"")||/joc/i.test(null!==(l=e.channels)&&void 0!==l?l:""),enabled:t,channelCount:i,isAudioDescription:r};this.audioTracks.push(d),e.default&&(this.audioTrack=d)}this.onAudioTracksChanged()})),this.hls.on($o().Events.AUDIO_TRACK_SWITCHED,((e,t)=>{const i=String(t.id);for(const e of this.audioTracks)i===e.id&&(this.audioTrack=e);this.player.loop.dispatchEvent(r.a.CURRENT_AUDIO_TRACK_CHANGED,{audioTrack:this.audioTrack})}))}else Yo(this,e,null,"f"),this.handleError()}handleHLSMediaError(){var e,t,i,r;const s=Date.now();-1===this.recoverDecodingErrorDate||s-this.recoverDecodingErrorDate>3e3?(this.recoverDecodingErrorDate=s,this.log(`try to recover media Error @ ${this.getCurrentTime()}`),null===(e=this.hls)||void 0===e||e.recoverMediaError()):-1===this.recoverSwapAudioCodecDate||s-this.recoverSwapAudioCodecDate>3e3?(this.recoverSwapAudioCodecDate=Date.now(),this.log(`try to swap Audio Codec and recover media Error @ ${this.getCurrentTime()}`),null===(t=this.hls)||void 0===t||t.swapAudioCodec(),null===(i=this.hls)||void 0===i||i.recoverMediaError()):(this.log("cannot recover, last media error recovery failed ..."),null===(r=this.hls)||void 0===r||r.destroy(),this.handleError())}resetNetworkErrorHandler(){var e;this.networkRecoveryHandler&&(null===(e=navigator.connection)||void 0===e||e.removeEventListener("change",this.networkRecoveryHandler))}canSeek(){return!0}getDvrToDateSync(){return this.dvrToDateSync}setCurrentTime(e,t,i,r){void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=!1);let s=-1;this.dvrToDateSync&&e>=this.dvrRelToUnix(0)&&(s=e,e=this.dvrUnixToRel(e));let n=Math.min(e,this.getDuration()-.1);if(this.setSeekEventTimestamps(this.getCurrentTime(),e),this._dvrModeEnabled){const t=e/this.getDuration();n=this.dvrWindowLeft+(this.dvrWindowRight-this.dvrWindowLeft)*t,this.dvrTime=e}this.setCurrentTimeRaw(n,s,t,i,r),this.player.model.time=e}getCurrentTime(){return this._dvrModeEnabled?this.dvrTime:super.getCurrentTime()}getDuration(){return this._dvrModeEnabled?this._dvrWindow:super.getDuration()}seekToLive(){var e,t;this.setCurrentTime(null!==(t=null===(e=this.hls)||void 0===e?void 0:e.liveSyncPosition)&&void 0!==t?t:this.getDuration())}updateTicker(){if(this._dvrModeEnabled){const e=performance.now();-1!==this.lastTickerUpdate&&(this.model.playstate===s.R.PLAYSTATE_PAUSED||this.model.playstate===s.R.PLAYSTATE_PLAYING&&this.playbackStalled?this.dvrTime=Math.max(0,this.dvrTime-(e-this.lastTickerUpdate)/1e3):this.model.playstate===s.R.PLAYSTATE_PLAYING&&(this.dvrTime+=(this.model.playbackRate-1)*((e-this.lastTickerUpdate)/1e3),this.dvrTime>=this.getDuration()&&(this.dvrTime=this.getDuration()))),this.lastTickerUpdate=e}super.updateTicker()}stopTicker(){this.lastTickerUpdate=-1,super.stopTicker()}updateDVRValues(){this.onDVRCallback(this._dvrModeEnabled,this._dvrWindow,this.dvrTime>=this.getDuration())}play(){this.model.playstate===s.R.PLAYSTATE_PAUSED&&this.mc.isLive&&!this.mc.isDvrEnabled&&this.seekToLive(),super.play()}getAudioTracks(){return null===this.hls?[]:this.audioTracks}setAudioTrack(e){if(this.audioTrack=e,null===this.hls)return;const t=parseInt(e.id,10);this.hls.audioTrack!==t&&(this.hls.audioTrack=t)}setAudioTrackById(e){if(null===this.hls)return;const t=parseInt(e,10);this.hls.audioTrack!==t&&(this.hls.audioTrack=t)}getAudioTrack(){return this.audioTrack}setWebVTTSubtitlesEnabled(e){this.hls&&this.hls.subtitleDisplay!==e&&(this.hls.subtitleDisplay=e)}dispose(){this.resetNetworkErrorHandler(),this.hls&&(this.hls.destroy(),this.hls=null),super.dispose()}debugString(){var t,i,r,s;return this.hls?`AutoLevel: ${String(this.hls.autoLevelEnabled)} | Quality ${(null!==(t=this.hls.currentLevel)&&void 0!==t?t:-2)+1} of ${null!==(r=null===(i=this.hls.levels)||void 0===i?void 0:i.length)&&void 0!==r?r:-1}${!0===(null===(s=Wo(this,e,"f"))||void 0===s?void 0:s.isAdaptiveQualitySelectable)?" (sub-selectable)":""}`:"no instance"}debugQualityLevel(){var e,t,i,r,s;return[null!==(t=null===(e=this.hls)||void 0===e?void 0:e.currentLevel)&&void 0!==t?t:-1,null!==(s=null===(r=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===r?void 0:r.length)&&void 0!==s?s:1]}get subQualities(){var e,t,i,r,s;const n=[{level:-1,label:"Auto",width:-1,height:-1}],a=null!==(r=null===(i=null===(e=this.hls)||void 0===e?void 0:e.levels[null===(t=this.hls)||void 0===t?void 0:t.currentLevel])||void 0===i?void 0:i.codecSet)&&void 0!==r?r:null;return null===(s=this.hls)||void 0===s||s.levels.forEach(((e,t)=>{var i,r,s;if(a&&e.codecSet!==a)return;const l=null!==(r=null===(i=e.videoCodec)||void 0===i?void 0:i.startsWith("hvc1.2"))&&void 0!==r&&r;n.push({level:t,label:null!==(s=e.name)&&void 0!==s?s:(0,o.a7)(e.width,e.height,l),width:e.width,height:e.height,debug:`${e.codecSet}@${Number.isFinite(e.bitrate)?e.bitrate/1e3+"k":e.bitrate}`}),n[0].width=Math.max(n[0].width,e.width),n[0].height=Math.max(n[0].height,e.height)})),n}selectSubQuality(e){null!==this.hls&&(this.hls.currentLevel=e<0||e>this.hls.levels.length?-1:e)}get currentSubQuality(){return null==this.hls||this.hls.autoLevelEnabled?-1:this.hls.currentLevel}getClassTypeString(){return"HLSCtrl"}};return e=new WeakMap,t=new WeakMap,Ho(l,"HLSCtrl"),(()=>{var e;const t="function"==typeof Symbol&&Symbol.metadata?Object.create(null!==(e=u[Symbol.metadata])&&void 0!==e?e:null):void 0;Ko(null,i={value:l},h,{kind:"class",name:l.name,metadata:t},null,d),l=i.value,t&&Object.defineProperty(l,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t}),Vo(l,d)})(),l})();const qo={Generator:i(45055).X,Controller:jo}},74072:module=>{!function e(t){module.exports=function(){"use strict";function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function r(e,t,i){if(c())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var s=new(e.bind.apply(e,r));return i&&m(s,i.prototype),s}function s(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,v(r.key),r)}}function n(e,t,i){return t&&s(e.prototype,t),i&&s(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function a(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=y(e))||t){i&&(e=i);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(e,t,i){return(t=v(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},l.apply(null,arguments)}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}function d(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,m(e,t)}function u(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}function c(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(c=function(){return!!e})()}function f(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function g(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?f(Object(i),!0).forEach((function(t){o(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):f(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}function p(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function v(e){var t=p(e,"string");return"symbol"==typeof t?t:t+""}function y(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}function E(e){var t="function"==typeof Map?new Map:void 0;return E=function(e){if(null===e||!u(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return r(e,arguments,h(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),m(i,e)},E(e)}function T(){try{return crypto.randomUUID()}catch(r){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(i+16*Math.random())%16|0;return i=Math.floor(i/16),("x"==e?t:3&t|8).toString(16)}))}}}function S(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var A,L={exports:{}};function R(){return A||(A=1,function(module){var e=Object.prototype.hasOwnProperty,t="~";function i(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,i,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||e,a),l=t?t+i:i;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(t=!1)),a.prototype.eventNames=function(){var i,r,s=[];if(0===this._eventsCount)return s;for(r in i=this._events)e.call(i,r)&&s.push(t?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(i)):s},a.prototype.listeners=function(e){var i=t?t+e:e,r=this._events[i];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},a.prototype.listenerCount=function(e){var i=t?t+e:e,r=this._events[i];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,i,r,s,n,a){var o=t?t+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,r),!0;case 4:return d.fn.call(d.context,i,r,s),!0;case 5:return d.fn.call(d.context,i,r,s,n),!0;case 6:return d.fn.call(d.context,i,r,s,n,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,i);break;case 3:d[h].fn.call(d[h].context,i,r);break;case 4:d[h].fn.call(d[h].context,i,r,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,i,r,s){var a=t?t+e:e;if(!this._events[a])return this;if(!i)return n(this,a),this;var o=this._events[a];if(o.fn)o.fn!==i||s&&!o.once||r&&o.context!==r||n(this,a);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==i||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},a.prototype.removeAllListeners=function(e){var r;return e?(r=t?t+e:e,this._events[r]&&n(this,r)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,module.exports=a}(L)),L.exports}var I,b=S(R()),D={exports:{}};function k(){return I||(I=1,function(module,e){var t,i,r,s,n;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var s=n.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=n.normalizePath(s.path),n.buildURLFromParts(s)}var a=n.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):t;var o=n.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(u)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=r.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(s,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},module.exports=n}(D)),D.exports}var _=k(),P=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},C=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=w},w=Number.MAX_SAFE_INTEGER||9007199254740991,x=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),O=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),M=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({}),F={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},N={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},U=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(i=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}var t=e.prototype;return t.sample=function(e,t){var i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),B=function(){function e(e,t,i,r){void 0===r&&(r=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new U(e),this.fast_=new U(t),this.defaultTTFB_=r,this.ttfb_=new U(e)}var t=e.prototype;return t.update=function(e,t){var i=this.slow_,r=this.fast_,s=this.ttfb_;i.halfLife!==e&&(this.slow_=new U(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new U(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new U(e,s.getEstimate(),s.getTotalWeight()))},t.sample=function(e,t){var i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)},t.sampleTTFB=function(e){var t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},n(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),G=function(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="["+e+"]:";this.trace=$,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)},$=function(){},K={trace:$,debug:$,log:$,warn:$,info:$,error:$};function V(){return l({},K)}function H(e,t){var i=self.console[e];return i?i.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):$}function Y(e,t,i){return t[e]?t[e].bind(t):H(e,i)}var W=V();function j(e,t,i){var r=V();if("object"==typeof console&&!0===e||"object"==typeof e){var s=["debug","log","info","warn","error"];s.forEach((function(t){r[t]=Y(t,e,i)}));try{r.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.2')}catch(e){return V()}s.forEach((function(t){W[t]=Y(t,e)}))}else l(W,r);return r}var q=W;function X(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Q(e){return"undefined"!=typeof self&&e===self.ManagedMediaSource}function z(e,t){var i=Object.keys(e),r=Object.keys(t),s=i.length,n=r.length;return!s||!n||s===n&&!i.some((function(e){return-1===r.indexOf(e)}))}function J(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(e);if(t){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.replace(/\0/g,"")}for(var s,n,a,o=e.length,l="",h=0;h<o;){if(0===(s=e[h++])&&t)return l;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(s);break;case 12:case 13:n=e[h++],l+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[h++],a=e[h++],l+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return l}var Z={hexDump:function(e){for(var t="",i=0;i<e.length;i++){var r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t}},ee=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}},te={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},ie=function(){function e(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,oe(this,"stats")}var t=e.prototype;return t.setByteRange=function(e,t){var i,r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[te.AUDIO]=null,e[te.VIDEO]=null,e[te.AUDIOVIDEO]=null},n(e,[{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){var e;return null===this._streams&&(this._streams=((e={})[te.AUDIO]=null,e[te.VIDEO]=null,e[te.AUDIOVIDEO]=null,e)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new ee),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=_.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function re(e){return"initSegment"!==e.sn}var se=function(e){function t(t,i){var r;return(r=e.call(this,i)||this)._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=t,r}d(t,e);var i=t.prototype;return i.addStart=function(e){this.setStart(this.start+e)},i.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},i.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},i.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},i.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},i.setElementaryStreamInfo=function(e,t,i,r,s,n){void 0===n&&(n=!1);var a=this.elementaryStreams,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}},n(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange){var t=this.byteRange[0],i=this.byteRange[1];if(P(t)&&P(i))return i-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{var t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=P(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&this.levelkeys[t[0]].encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){P(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return re(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(ie),ne=function(e){function t(t,i,r,s,n){var a;(a=e.call(this,r)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.duration=t.decimalFloatingPoint("DURATION"),a.gap=t.bool("GAP"),a.independent=t.bool("INDEPENDENT"),a.relurl=t.enumeratedString("URI"),a.fragment=i,a.index=s;var o=t.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,n),n&&(a.fragOffset=n.fragOffset+n.duration),a}return d(t,e),n(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}])}(ie);function ae(e,t){var i=Object.getPrototypeOf(e);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r||ae(i,t)}}function oe(e,t){var i=ae(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}var le=Math.pow(2,32)-1,he=[].push,de={video:1,audio:2,id3:3,text:4};function ue(e){return String.fromCharCode.apply(null,e)}function ce(e,t){var i=e[t]<<8|e[t+1];return i<0?65536+i:i}function fe(e,t){var i=me(e,t);return i<0?4294967296+i:i}function ge(e,t){var i=fe(e,t);return i*=Math.pow(2,32),i+=fe(e,t+4)}function me(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function pe(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function ve(e){for(var t=e.byteLength,i=0;i<t;){var r=fe(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}function ye(e,t){var i=[];if(!t.length)return i;for(var r=e.byteLength,s=0;s<r;){var n=fe(e,s),a=n>1?s+n:r;if(ue(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{var o=ye(e.subarray(s+8,a),t.slice(1));o.length&&he.apply(i,o)}s=a}return i}function Ee(e){var t=[],i=e[0],r=8,s=fe(e,r);r+=4;var n=0,a=0;0===i?(n=fe(e,r),a=fe(e,r+4),r+=8):(n=ge(e,r),a=ge(e,r+8),r+=16),r+=2;var o=e.length+a,l=ce(e,r);r+=2;for(var h=0;h<l;h++){var d=r,u=fe(e,d);d+=4;var c=2147483647&u;if(1==(2147483648&u)>>>31)return q.warn("SIDX has hierarchical references (not supported)"),null;var f=fe(e,d);d+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,r=d+=4}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function Te(e){for(var t=[],i=ye(e,["moov","trak"]),r=0;r<i.length;r++){var s=i[r],n=ye(s,["tkhd"])[0];if(n){var a=n[0],o=fe(n,0===a?12:20),l=ye(s,["mdia","mdhd"])[0];if(l){var h=fe(l,0===(a=l[0])?12:20),d=ye(s,["mdia","hdlr"])[0];if(d){var u=ue(d.subarray(8,12)),c={soun:te.AUDIO,vide:te.VIDEO}[u],f=Se(ye(s,["mdia","minf","stbl","stsd"])[0]);c?(t[o]={timescale:h,type:c,stsd:f},t[c]=g({timescale:h,id:o},f)):t[o]={timescale:h,type:u,stsd:f}}}}}return ye(e,["moov","mvex","trex"]).forEach((function(e){var i=fe(e,4),r=t[i];r&&(r.default={duration:fe(e,12),flags:fe(e,20)})})),t}function Se(e){var t,i=e.subarray(8),r=i.subarray(86),s=ue(i.subarray(4,8)),n=s,a="enca"===s||"encv"===s;if(a){var o=ye(i,[s])[0];ye(o.subarray("enca"===s?28:78),["sinf"]).forEach((function(e){var t=ye(e,["schm"])[0];if(t){var i=ue(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=ye(e,["frma"])[0];r&&(n=ue(r))}}}))}var l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":var h=ye(r,["avcC"])[0];h&&h.length>3&&(n+="."+Re(h[1])+Re(h[2])+Re(h[3]),t=Ae("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var d=ye(i,[s])[0],u=ye(d.subarray(28),["esds"])[0];if(u&&u.length>7){var c=4;if(3!==u[c++])break;c=Le(u,c),c+=2;var f=u[c++];if(128&f&&(c+=2),64&f&&(c+=u[c++]),4!==u[c++])break;c=Le(u,c);var g=u[c++];if(64!==g)break;if(n+="."+Re(g),c+=12,5!==u[c++])break;c=Le(u,c);var m=u[c++],p=(248&m)>>3;31===p&&(p+=1+((7&m)<<3)+((224&u[c])>>5)),n+="."+p}break;case"hvc1":case"hev1":var v=ye(r,["hvcC"])[0];if(v&&v.length>12){var y=v[1],E=["","A","B","C"][y>>6],T=31&y,S=fe(v,2),A=(32&y)>>5?"H":"L",L=v[12],R=v.subarray(6,12);n+="."+E+T,n+="."+S.toString(16).toUpperCase(),n+="."+A+L;for(var I="",b=R.length;b--;){var D=R[b];(D||I)&&(I="."+D.toString(16).toUpperCase()+I)}n+=I}t=Ae("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Ae(n,r)||n;break;case"vp09":var k=ye(r,["vpcC"])[0];if(k&&k.length>6){var _=k[4],P=k[5],C=k[6]>>4&15;n+="."+Ie(_)+"."+Ie(P)+"."+Ie(C)}break;case"av01":var w=ye(r,["av1C"])[0];if(w&&w.length>2){var x=w[1]>>>5,O=31&w[1],M=w[2]>>>7?"H":"M",F=(64&w[2])>>6,N=(32&w[2])>>5,U=2===x&&F?N?12:10:F?10:8,B=(16&w[2])>>4,G=(8&w[2])>>3,$=(4&w[2])>>2,K=3&w[2],V=1,H=1,Y=1,W=0;n+="."+x+"."+Ie(O)+M+"."+Ie(U)+"."+B+"."+G+$+K+"."+Ie(V)+"."+Ie(H)+"."+Ie(Y)+"."+W,t=Ae("dav1",r)}}return{codec:n,encrypted:a,supplemental:t}}function Ae(e,t){var i=ye(t,["dvvC"]),r=i.length?i[0]:ye(t,["dvcC"])[0];if(r){var s=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return e+"."+Ie(s)+"."+Ie(n)}}function Le(e,t){for(var i=t+5;128&e[t++]&&t<i;);return t}function Re(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ie(e){return(e<10?"0":"")+e}function be(e,t){if(!e||!t)return e;var i=t.keyId;return i&&t.isCommonEncryption&&ye(e,["moov","trak"]).forEach((function(e){var t=ye(e,["mdia","minf","stbl","stsd"])[0].subarray(8),r=ye(t,["enca"]),s=r.length>0;s||(r=ye(t,["encv"])),r.forEach((function(e){ye(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=De(e);if(t){var r=t.subarray(8,24);r.some((function(e){return 0!==e}))||(q.log("[eme] Patching keyId in 'enc"+(s?"a":"v")+">sinf>>tenc' box: "+Z.hexDump(r)+" -> "+Z.hexDump(i)),t.set(i,8))}}))}))})),e}function De(e){var t=ye(e,["schm"])[0];if(t){var i=ue(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return ye(e,["schi","tenc"])[0]}return null}function ke(e,t){return ye(t,["moof","traf"]).reduce((function(t,i){var r=ye(i,["tfdt"])[0],s=r[0],n=ye(i,["tfhd"]).reduce((function(t,i){var n=fe(i,4),a=e[n];if(a){var o=fe(r,4);if(1===s){if(o===le)return q.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;o*=le+1,o+=fe(r,8)}var l=o/(a.timescale||9e4);if(P(l)&&(null===t||l<t))return l}return t}),null);return null!==n&&P(n)&&(null===t||n<t)?n:t}),null)}function _e(e,t){for(var i=0,r=0,s=0,n=ye(e,["moof","traf"]),a=0;a<n.length;a++){var o=n[a],l=ye(o,["tfhd"])[0],h=t[fe(l,4)];if(h){var d=h.default,u=fe(l,0)|(null==d?void 0:d.flags),c=null==d?void 0:d.duration;8&u&&(c=fe(l,2&u?12:8));for(var f=h.timescale||9e4,g=ye(o,["trun"]),m=0;m<g.length;m++)!(i=Pe(g[m]))&&c&&(i=c*fe(g[m],4)),h.type===te.VIDEO?r+=i/f:h.type===te.AUDIO&&(s+=i/f)}}if(0===r&&0===s){for(var p=1/0,v=0,y=0,E=ye(e,["sidx"]),T=0;T<E.length;T++){var S=Ee(E[T]);if(null!=S&&S.references){p=Math.min(p,S.earliestPresentationTime/S.timescale);var A=S.references.reduce((function(e,t){return e+t.info.duration||0}),0);y=(v=Math.max(v,A+S.earliestPresentationTime/S.timescale))-p}}if(y&&P(y))return y}return r||s}function Pe(e){var t=fe(e,0),i=8;1&t&&(i+=4),4&t&&(i+=4);for(var r=0,s=fe(e,4),n=0;n<s;n++)256&t&&(r+=fe(e,i),i+=4),512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4);return r}function Ce(e,t,i){ye(t,["moof","traf"]).forEach((function(t){ye(t,["tfhd"]).forEach((function(r){var s=fe(r,4),n=e[s];if(n){var a=n.timescale||9e4;ye(t,["tfdt"]).forEach((function(e){var t=e[0],r=i*a;if(r){var s=fe(e,4);if(0===t)s-=r,pe(e,4,s=Math.max(s,0));else{s*=Math.pow(2,32),s+=fe(e,8),s-=r,s=Math.max(s,0);var n=Math.floor(s/(le+1)),o=Math.floor(s%(le+1));pe(e,4,n),pe(e,8,o)}}}))}}))}))}function we(e){var t={valid:null,remainder:null},i=ye(e,["moof"]);if(i.length<2)return t.remainder=e,t;var r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}function xe(e,t){var i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Oe(e,t){var i=[],r=t.samples,s=t.timescale,n=t.id,a=!1;return ye(r,["moof"]).map((function(o){var l=o.byteOffset-8;ye(o,["traf"]).map((function(o){var h=ye(o,["tfdt"]).map((function(e){var t=e[0],i=fe(e,4);return 1===t&&(i*=Math.pow(2,32),i+=fe(e,8)),i/s}))[0];return void 0!==h&&(e=h),ye(o,["tfhd"]).map((function(h){var d=fe(h,4),u=16777215&fe(h,0),c=0,f=!!(16&u),g=0,m=!!(32&u),p=8;d===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=fe(h,p),p+=4),f&&(g=fe(h,p),p+=4),m&&(p+=4),"video"===t.type&&(a=Me(t.codec)),ye(o,["trun"]).map((function(n){var o=n[0],h=16777215&fe(n,0),d=!!(1&h),u=0,f=!!(4&h),m=!!(256&h),p=0,v=!!(512&h),y=0,E=!!(1024&h),T=!!(2048&h),S=0,A=fe(n,4),L=8;d&&(u=fe(n,L),L+=4),f&&(L+=4);for(var R=u+l,I=0;I<A;I++){if(m?(p=fe(n,L),L+=4):p=c,v?(y=fe(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?fe(n,L):me(n,L),L+=4),t.type===te.VIDEO)for(var b=0;b<y;){var D=fe(r,R);Fe(a,r[R+=4])&&Ne(r.subarray(R,R+D),a?2:1,e+S/s,i),R+=D,b+=D+4}e+=p/s}})))}))}))})),i}function Me(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Fe(e,t){if(e){var i=t>>1&63;return 39===i||40===i}return 6==(31&t)}function Ne(e,t,i,r){var s=Ue(e),n=0;n+=t;for(var a=0,o=0,l=0;n<s.length;){a=0;do{if(n>=s.length)break;a+=l=s[n++]}while(255===l);o=0;do{if(n>=s.length)break;o+=l=s[n++]}while(255===l);var h=s.length-n,d=n;if(o<h)n+=o;else if(o>h){q.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===s[d++]){var u=ce(s,d);if(d+=2,49===u){var c=fe(s,d);if(d+=4,1195456820===c){var f=s[d++];if(3===f){var g=s[d++],m=64&g,p=m?2+3*(31&g):0,v=new Uint8Array(p);if(m){v[0]=g;for(var y=1;y<p;y++)v[y]=s[d++]}r.push({type:f,payloadType:a,pts:i,bytes:v})}}}}}else if(5===a&&o>16){for(var E=[],T=0;T<16;T++){var S=s[d++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var A=o-16,L=new Uint8Array(A),R=0;R<A;R++)L[R]=s[d++];r.push({payloadType:a,pts:i,uuid:E.join(""),userData:J(L),userDataBytes:L})}}}function Ue(e){for(var t=e.byteLength,i=[],r=1;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;var s=t-i.length,n=new Uint8Array(s),a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=e[a];return n}function Be(e){var t=e[0],i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==ue(e.subarray(h,h+1));)i+=ue(e.subarray(h,h+1)),h+=1;for(i+=ue(e.subarray(h,h+1)),h+=1;"\0"!==ue(e.subarray(h,h+1));)r+=ue(e.subarray(h,h+1)),h+=1;r+=ue(e.subarray(h,h+1)),h+=1,s=fe(e,12),n=fe(e,16),o=fe(e,20),l=fe(e,24),h=28}else if(1===t){s=fe(e,h+=4);var d=fe(e,h+=4),u=fe(e,h+=4);for(h+=4,a=Math.pow(2,32)*d+u,C(a)||(a=Number.MAX_SAFE_INTEGER,q.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=fe(e,h),l=fe(e,h+=4),h+=4;"\0"!==ue(e.subarray(h,h+1));)i+=ue(e.subarray(h,h+1)),h+=1;for(i+=ue(e.subarray(h,h+1)),h+=1;"\0"!==ue(e.subarray(h,h+1));)r+=ue(e.subarray(h,h+1)),h+=1;r+=ue(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}function Ge(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var s=i.length,n=8,a=s;a--;)n+=i[a].byteLength;var o=new Uint8Array(n);for(o[0]=n>>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=255&n,o.set(e,4),a=0,n=8;a<s;a++)o.set(i[a],n),n+=i[a].byteLength;return o}function $e(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");var r,s,n;r=0,s=new Uint8Array,r>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;var a=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),Ge([112,115,115,104],new Uint8Array([r,0,0,0]),e,n,s,a,i||new Uint8Array)}function Ke(e){var t=[];if(e instanceof ArrayBuffer)for(var i=e.byteLength,r=0;r+32<i;){var s=Ve(new DataView(e,r));t.push(s),r+=s.size}return t}function Ve(e){var t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};var s=e.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:t};var n=e.buffer,a=Z.hexDump(new Uint8Array(n,i+12,16)),o=e.getUint32(28),l=null,h=null;if(0===s){if(t-32<o||o<22)return{offset:i,size:t};h=new Uint8Array(n,i+32,o)}else if(1===s){if(!o||r<i+32+16*o+16)return{offset:i,size:t};l=[];for(var d=0;d<o;d++)l.push(new Uint8Array(n,i+32+16*d,16))}return{version:s,systemId:a,kids:l,data:h,offset:i,size:t}}var He=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},Ye={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 We(e,t){var i=Ye[t];return!!i&&!!i[e.slice(0,4)]}function je(e,t,i){return void 0===i&&(i=!0),!e.split(",").some((function(e){return!qe(e,t,i)}))}function qe(e,t,i){var r;void 0===i&&(i=!0);var s=X(i);return null!=(r=null==s?void 0:s.isTypeSupported(Xe(e,t)))&&r}function Xe(e,t){return t+"/mp4;codecs="+e}function Qe(e){if(e){var t=e.substring(0,4);return Ye.video[t]}return 2}function ze(e){var t=He();return e.split(",").reduce((function(e,i){var r=t&&Me(i)?9:Ye.video[i];return r?(2*r+e)/(e?3:2):(Ye.audio[i]+e)/(e?2:1)}),0)}var Je={};function Ze(e,t){if(void 0===t&&(t=!0),Je[e])return Je[e];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],r=0;r<i.length;r++){var s;if(qe(i[r],"audio",t))return Je[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=X(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}var et=/flac|opus|mp4a\.40\.34/i;function tt(e,t){return void 0===t&&(t=!0),e.replace(et,(function(e){return Ze(e.toLowerCase(),t)}))}function it(e,t){var i=[];if(e)for(var r=e.split(","),s=0;s<r.length;s++)We(r[s],"video")||i.push(r[s]);return t&&i.push(t),i.join(",")}function rt(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){var i=t.split(",");if(i.length>1){if(e)for(var r=i.length;r--;)if(i[r].substring(0,4)===e.substring(0,4))return i[r];return i[0]}}return t||e}function st(e){for(var t=e.split(","),i=0;i<t.length;i++){var r=t[i].split(".");if(r.length>2){var s=r.shift()+".";s+=parseInt(r.shift()).toString(16),s+=("000"+parseInt(r.shift()).toString(16)).slice(-4),t[i]=s}}return t.join(",")}function nt(e){if(e.startsWith("av01.")){for(var t=e.split("."),i=["0","111","01","01","01","0"],r=t.length;r>4&&r<10;r++)t[r]=i[r-4];return t.join(".")}return e}function at(e){var t=X(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ot(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var lt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function ht(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}var dt={};function ut(e,t,i,r,s,n){var a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2,d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce((function(e,i){if(i){var r=t.groups[i];if(!r)throw new Error("Audio track group "+i+" not found");Object.keys(r.channels).forEach((function(t){e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!d&&P(h)&&Object.keys(d).some((function(e){return parseInt(e)>h}))}function ct(e,t,i){var r=e.videoCodec,s=e.audioCodec;if(!r&&!s||!i)return Promise.resolve(lt);var n=[];if(r){var a={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},o=e.videoRange;"SDR"!==o&&(a.transferFunction=o.toLowerCase());var l=r.split(","),h=navigator.userAgent;if(l.some((function(e){return Me(e)}))&&He())return Promise.resolve(ht(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: ("+h+")"),n));n.push.apply(n,l.map((function(e){return{type:"media-source",video:g(g({},a),{},{contentType:Xe(nt(e),"video")})}})))}return s&&e.audioGroups&&e.audioGroups.forEach((function(e){var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((function(t){if(t.groupId===e){var i=t.channels||"",r=parseFloat(i);P(r)&&r>2&&n.push.apply(n,s.split(",").map((function(e){return{type:"media-source",audio:{contentType:Xe(e,"audio"),channels:""+r}}})))}})))})),Promise.all(n.map((function(e){var t=ft(e);return dt[t]||(dt[t]=i.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:n,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:n,decodingInfoResults:[],error:e}}))}function ft(e){var t=e.audio,i=e.video,r=i||t;if(r){var s=ot(r.contentType);if(i)return"r"+i.height+"x"+i.width+"f"+Math.ceil(i.framerate)+(i.transferFunction||"sd")+"_"+s+"_"+Math.ceil(i.bitrate/1e5);if(t)return"c"+t.channels+(t.spatialRendering?"s":"n")+"_"+s}return""}var gt=["NONE","TYPE-0","TYPE-1",null];function mt(e){return gt.indexOf(e)>-1}var pt=["SDR","PQ","HLG"];function vt(e){return!!e&&pt.indexOf(e)>-1}var yt={No:"",Yes:"YES",v2:"v2"};function Et(e){var t=e.canSkipUntil,i=e.canSkipDateRanges,r=e.age;return t&&r<t/2?i?yt.v2:yt.Yes:yt.No}var Tt=function(){function e(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}return e.prototype.addDirectives=function(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href},e}(),St=function(){function e(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return!!e})).map((function(e){return e.substring(0,4)})).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;var i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=","+i.substring(0,4))}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}var t=e.prototype;return t.hasAudioGroup=function(e){return At(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return At(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(t)&&i.push(t)}else if("text"===e){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(t)&&r.push(t)}},t.addFallback=function(){},n(e,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}}])}();function At(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Lt(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}function Rt(e,t){var i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){var s="SDR"!==(r=t.allowedVideoRanges||pt.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:s&&Lt())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}var It=function(e){var t=new WeakSet;return function(i,r){if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}},bt=function(e,t){return JSON.stringify(e,It(t))};function Dt(e,t,i,r,s){for(var n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==s?void 0:s.videoCodec,h=a&&2===parseInt(a),d=!1,u=!1,c=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[],y=Rt(t,s),E=y.preferHDR,T=y.allowedVideoRanges,S=function(){var t=e[n[A]];d||(d=t.channels[2]>0),c=Math.min(c,t.minHeight),f=Math.min(f,t.minFramerate),g=Math.min(g,t.minBitrate),T.filter((function(e){return t.videoRanges[e]>0})).length>0&&(u=!0)},A=n.length;A--;)S();c=P(c)?c:0,f=P(f)?f:0;var L=Math.max(1080,c),R=Math.max(30,f);g=P(g)?g:i,i=Math.max(g,i),u||(t=void 0);var I=n.length>1;return{codecSet:n.reduce((function(t,r){var s=e[r];if(r===t)return t;if(v=u?T.filter((function(e){return s.videoRanges[e]>0})):[],I){if(s.minBitrate>i)return kt(r,"min bitrate of "+s.minBitrate+" > current estimate of "+i),t;if(!s.hasDefaultAudio)return kt(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return kt(r,'audio codec preference "'+o+'" not found'),t;if(a&&!h){if(!s.channels[a])return kt(r,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(s.channels)+")"),t}else if((!o||h)&&d&&0===s.channels[2])return kt(r,"no renditions with stereo sound found"),t;if(s.minHeight>L)return kt(r,"min resolution of "+s.minHeight+" > maximum of "+L),t;if(s.minFramerate>R)return kt(r,"min framerate of "+s.minFramerate+" > maximum of "+R),t;if(!v.some((function(e){return s.videoRanges[e]>0})))return kt(r,"no variants with VIDEO-RANGE of "+bt(v)+" found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return kt(r,'video codec preference "'+l+'" not found'),t;if(s.maxScore<p)return kt(r,"max score of "+s.maxScore+" < selected max of "+p),t}return t&&(ze(r)>=ze(t)||s.fragmentError>e[t].fragmentError)?t:(m=s.minIndex,p=s.maxScore,r)}),void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:m}}function kt(e,t){q.log('[abr] start candidates with "'+e+'" ignored because '+t)}function _t(e){return e.reduce((function(e,t){var i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);var r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Pt(e,t,i,r){return e.slice(i,r+1).reduce((function(e,i,r){if(!i.codecSet)return e;var s=i.audioGroups,n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);var a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,s&&s.forEach((function(e){if(e){var i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((function(e){n.channels[e]=(n.channels[e]||0)+i.channels[e]})))}})),e}),{})}function Ct(e){if(!e)return e;var t=e;return{lang:t.lang,assocLang:t.assocLang,characteristics:t.characteristics,channels:t.channels,audioCodec:t.audioCodec}}function wt(e,t,i){if("attrs"in e){var r=t.indexOf(e);if(-1!==r)return r}for(var s=0;s<t.length;s++)if(xt(e,t[s],i))return s;return-1}function xt(e,t,i){var r=e.groupId,s=e.name,n=e.lang,a=e.assocLang,o=e.default,l=e.forced;return(void 0===r||t.groupId===r)&&(void 0===s||t.name===s)&&(void 0===n||Ot(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||Mt(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function Ot(e,t){return void 0===t&&(t="--"),e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function Mt(e,t){void 0===t&&(t="");var i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some((function(e){return-1===r.indexOf(e)}))}function Ft(e,t){var i=e.audioCodec,r=e.channels;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function Nt(e,t,i,r,s){var n=t[r],a=t.reduce((function(e,t,i){var r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));var o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Ut(t,r,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;var r=t.audioGroups,n=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return wt(e,n,s)>-1}));return d>-1?d:Ut(t,r,(function(t){var r=t.audioGroups,n=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return wt(e,n,s)>-1}))}function Ut(e,t,i){for(var r=t;r>-1;r--)if(i(e[r]))return r;for(var s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function Bt(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}var Gt=function(e){function t(t){var i;return(i=e.call(this,"abr",t.logger)||this).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.bwEstimator=void 0,i._abandonRulesCheck=function(e){var t,r=i,s=r.fragCurrent,n=r.partCurrent,a=r.hls,o=a.autoLevelEnabled,l=a.media;if(s&&l){var h=performance.now(),d=n?n.stats:s.stats,u=n?n.duration:s.duration,c=h-d.loading.start,f=a.minAutoLevel,g=s.level,m=i._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var p=m>-1&&m!==g,v=!!e||p;if(v||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(v||null!==y){var E=i.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(!(c<=Math.max(E,u/(2*T)*1e3))){var S=y?y.len/T:0,A=d.loading.first?d.loading.first-d.loading.start:-1,L=d.loaded&&A>-1,R=i.getBwEstimate(),I=a.levels,b=I[g],D=Math.max(d.loaded,Math.round(u*(s.bitrate||b.averageBitrate)/8)),k=L?c-A:c;k<1&&L&&(k=Math.min(c,8*d.loaded/R));var _=L?1e3*d.loaded/k:0,C=E/1e3,w=_?(D-d.loaded)/_:8*D/R+C;if(!(w<=S)){var x,O=_?8*_:R,F=!0===(null==(t=(null==e?void 0:e.details)||i.hls.latestLevelDetails)?void 0:t.live),N=i.hls.config.abrBandWidthUpFactor,U=Number.POSITIVE_INFINITY;for(x=g-1;x>f;x--){var B=I[x].maxBitrate,G=!I[x].details||F;if((U=i.getTimeToLoadFrag(C,O,u*B,G))<Math.min(S,u+C))break}if(!(U>=w||U>10*u)){L?i.bwEstimator.sample(c-Math.min(E,A),d.loaded):i.bwEstimator.sampleTTFB(c);var $=I[x].maxBitrate;i.getBwEstimate()*N>$&&i.resetEstimator($);var K=i.findBestLevel($,f,x,0,S,1,1);K>-1&&(x=K),i.warn("Fragment "+s.sn+(n?" part "+n.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+s.duration.toFixed(3)+"\n Time to underbuffer: "+S.toFixed(3)+" s\n Estimated load time for current fragment: "+w.toFixed(3)+" s\n Estimated load time for down switch fragment: "+U.toFixed(3)+" s\n TTFB estimate: "+(0|A)+" ms\n Current BW estimate: "+(P(R)?0|R:"Unknown")+" bps\n New BW estimate: "+(0|i.getBwEstimate())+" bps\n Switching to level "+x+" @ "+(0|$)+" bps"),a.nextLoadLevel=a.nextAutoLevel=x,i.clearTimer();var V=function(){if(i.clearTimer(),i.fragCurrent===s&&i.hls.loadLevel===x&&x>0){var e=i.getStarvationDelay();if(i.warn("Aborting inflight request "+(x>0?"and switching down":"")+"\n Fragment duration: "+s.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),s.abortRequests(),i.fragCurrent=i.partCurrent=null,x>f){var t=i.findBestLevel(i.hls.levels[f].bitrate,f,x,0,e,1,1);-1===t&&(t=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=t,i.resetEstimator(i.hls.levels[t].bitrate)}}};p||w>2*U?V():i.timer=self.setInterval(V,1e3*U),a.trigger(M.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:d})}}}}}}}},i.hls=t,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}d(t,e);var i=t.prototype;return i.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},i.initEstimator=function(){var e=this.hls.config;return new B(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},i.registerListeners=function(){var e=this.hls;e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.FRAG_LOADING,this.onFragLoading,this),e.on(M.FRAG_LOADED,this.onFragLoaded,this),e.on(M.FRAG_BUFFERED,this.onFragBuffered,this),e.on(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(M.LEVEL_LOADED,this.onLevelLoaded,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(M.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(M.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.FRAG_LOADING,this.onFragLoading,this),e.off(M.FRAG_LOADED,this.onFragLoaded,this),e.off(M.FRAG_BUFFERED,this.onFragBuffered,this),e.off(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(M.LEVEL_LOADED,this.onLevelLoaded,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(M.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(M.ERROR,this.onError,this))},i.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},i.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},i.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},i.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},i.onFragLoading=function(e,t){var i,r=t.frag;this.ignoreFragment(r)||(r.bitrateTest||(this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},i.onLevelSwitching=function(e,t){this.clearTimer()},i.onError=function(e,t){if(!t.fatal)switch(t.details){case O.BUFFER_ADD_CODEC_ERROR:case O.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case O.FRAG_LOAD_TIMEOUT:var i=t.frag,r=this.fragCurrent,s=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var n=performance.now(),a=s?s.stats:i.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},i.getTimeToLoadFrag=function(e,t,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)},i.onLevelLoaded=function(e,t){var i=this.hls.config,r=t.stats.loading,s=r.end-r.first;P(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},i.onFragLoaded=function(e,t){var i=t.frag,r=t.part,s=r?r.stats:i.stats;if(i.type===N.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=r?r.duration:i.duration,a=this.hls.levels[i.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(i.bitrateTest){var h={stats:s,frag:i,part:r,id:i.type};this.onFragBuffered(M.FRAG_BUFFERED,h),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(!s.aborted&&!this.ignoreFragment(i)){var n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},i.ignoreFragment=function(e){return e.type!==N.MAIN||"initSegment"===e.sn},i.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},i.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},i.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,s=i.config,n=i.minAutoLevel,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(l){var u=this.findBestLevel(o,n,r,l,0,h,d);if(u>=0)return this.rebufferNotice=-1,u}var c=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-f,this.info("bitrate test took "+Math.round(1e3*f)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*c)+" ms"),h=d=1)}var g=this.findBestLevel(o,n,r,l,c,h,d);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var m=i.levels[n],p=i.loadLevelObj;return p&&(null==m?void 0:m.bitrate)<p.bitrate?n:i.loadLevel},i.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i},i.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},i.findBestLevel=function(e,t,i,r,s,n,a){var o,l=this,h=r+s,d=this.lastLoadedFragLevel,u=-1===d?this.hls.firstLevel:d,c=this.fragCurrent,f=this.partCurrent,g=this.hls,m=g.levels,p=g.allAudioTracks,v=g.loadLevel,y=g.config;if(1===m.length)return 0;var E,T=m[u],S=!(null==(o=this.hls.latestLevelDetails)||!o.live),A=-1===v||-1===d,L="SDR",R=(null==T?void 0:T.frameRate)||0,I=y.audioPreference,b=y.videoPreference,D=this.audioTracksByGroup||(this.audioTracksByGroup=_t(p)),k=-1;if(A){if(-1!==this.firstSelection)return this.firstSelection;var _=Dt(this.codecTiers||(this.codecTiers=Pt(m,D,t,i)),L,e,I,b),C=_.codecSet,w=_.videoRanges,x=_.minFramerate,O=_.minBitrate,M=_.minIndex,F=_.preferHDR;k=M,E=C,L=F?w[w.length-1]:w[0],R=x,e=Math.max(e,O),this.log("picked start tier "+bt(_))}else E=null==T?void 0:T.codecSet,L=null==T?void 0:T.videoRange;for(var N,U=f?f.duration:c?c.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,G=[],$=function(){var t,o=m[K],c=K>u;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&(ut(o,D,L,R,e,I)||Me(o.videoCodec))?(o.supportedPromise=ct(o,D,g),o.supportedPromise.then((function(e){if(l.hls){o.supportedResult=e;var t=l.hls.levels,i=t.indexOf(o);e.error?l.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+i+" "+bt(e)):e.supported||(l.warn("Unsupported MediaCapabilities decodingInfo result for level "+i+" "+bt(e)),i>-1&&t.length>1&&(l.log("Removing unsupported level "+i),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}}))):o.supportedResult=lt}if((E&&o.codecSet!==E||L&&o.videoRange!==L||c&&R>o.frameRate||!c&&R>0&&R<o.frameRate||o.supportedResult&&(null==(t=o.supportedResult.decodingInfoResults)||!t[0].smooth))&&(!A||K!==k))return G.push(K),0;var p,T=o.details,b=(f?null==T?void 0:T.partTarget:null==T?void 0:T.averagetargetduration)||U;p=c?a*e:n*e;var _=U&&r>=2*U&&0===s?o.averageBitrate:o.maxBitrate,C=l.getTimeToLoadFrag(B,p,_*b,void 0===T);if(p>=_&&(K===d||0===o.loadError&&0===o.fragmentError)&&(C<=B||!P(C)||S&&!l.bitrateTestDelay||C<h)){var w=l.forcedAutoLevel;return K===v||-1!==w&&w===v||(G.length&&l.trace("Skipped level(s) "+G.join(",")+" of "+i+' max with CODECS and VIDEO-RANGE:"'+m[G[0]].codecs+'" '+m[G[0]].videoRange+'; not compatible with "'+E+'" '+L),l.info("switch candidate:"+u+"->"+K+" adjustedbw("+Math.round(p)+")-bitrate="+Math.round(p-_)+" ttfb:"+B.toFixed(1)+" avgDuration:"+b.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+C.toFixed(1)+" firstSelection:"+A+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+v)),A&&(l.firstSelection=K),{v:K}}},K=i;K>=t;K--)if(0!==(N=$())&&N)return N.v;return-1},i.deriveNextAutoLevel=function(e){var t=this.hls,i=t.maxAutoLevel,r=t.minAutoLevel;return Math.min(Math.max(e,r),i)},n(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,i=e.minAutoLevel,r=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(r,i,t,0,s,1,1);if(n>-1)return n;var a=this.hls.firstLevel,o=Math.min(Math.max(a,i),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var s=this.hls.levels;if(s.length>Math.max(e,r)&&s[e].loadError<=s[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(G),$t={search:function(e,t){for(var i=0,r=e.length-1,s=null,n=null;i<=r;){var a=t(n=e[s=(i+r)/2|0]);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null}};function Kt(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!P(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(var r=0;r<e.length;++r){var s=e[r];if(Wt(t,i,s))return s}return null}function Vt(e,t,i,r,s){void 0===i&&(i=0),void 0===r&&(r=0),void 0===s&&(s=.005);var n=null;if(e){n=t[1+e.sn-t[0].sn]||null;var a=e.endDTS-i;a>0&&a<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Yt(i,r,n)||Ht(n,e,Math.min(s,r))))return n;var o=$t.search(t,Yt.bind(null,i,r));return!o||o===e&&n?n:o}function Ht(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var r=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),i);return e.start<=r}return!1}function Yt(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=0),i.start<=e&&i.start+i.duration>e)return 0;var r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function Wt(e,t,i){var r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function jt(e,t){return $t.search(e,(function(e){return e.cc<t?1:e.cc>t?-1:0}))}function qt(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){var r=i.start,s=i.end,n=e.fragments;if(!i.relurl){var a=e.fragmentHint;a&&(n=n.concat(a))}return $t.search(n,(function(e){return e.cc<t||e.end<=r?1:e.cc>t||e.start>=s?-1:0}))}return null}function Xt(e){switch(e.details){case O.FRAG_LOAD_TIMEOUT:case O.KEY_LOAD_TIMEOUT:case O.LEVEL_LOAD_TIMEOUT:case O.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Qt(e,t){var i=Xt(t);return e.default[(i?"timeout":"error")+"Retry"]}function zt(e,t){var i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function Jt(e){return g(g({},e),{errorRetry:null,timeoutRetry:null})}function Zt(e,t,i,r){if(!e)return!1;var s=null==r?void 0:r.code,n=t<e.maxNumRetry&&(ei(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}function ei(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}var ti={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ii={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2},ri=function(e){function t(t){var i;return(i=e.call(this,"error-controller",t.logger)||this).hls=void 0,i.playlistError=0,i.penalizedRenditions={},i.hls=t,i.registerListeners(),i}d(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(M.ERROR,this.onError,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(M.ERROR,this.onError,this),e.off(M.ERROR,this.onErrorOut,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this))},i.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},i.startLoad=function(e){},i.stopLoad=function(){this.playlistError=0},i.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===N.MAIN?e.level:this.hls.loadLevel},i.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},i.onLevelUpdated=function(){this.playlistError=0},i.onError=function(e,t){var i;if(!t.fatal){var r=this.hls,s=t.context;switch(t.details){case O.FRAG_LOAD_ERROR:case O.FRAG_LOAD_TIMEOUT:case O.KEY_LOAD_ERROR:case O.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case O.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=si());case O.FRAG_GAP:case O.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=ti.SendAlternateToPenaltyBox);case O.LEVEL_EMPTY_ERROR:case O.LEVEL_PARSING_ERROR:var n,a,o=t.parent===N.MAIN?t.level:r.loadLevel;return void(t.details===O.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(a=n.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o)));case O.LEVEL_LOAD_ERROR:case O.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level)));case O.AUDIO_TRACK_LOAD_ERROR:case O.AUDIO_TRACK_LOAD_TIMEOUT:case O.SUBTITLE_LOAD_ERROR:case O.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){var l=r.loadLevelObj;if(l&&(s.type===F.AUDIO_TRACK&&l.hasAudioGroup(s.groupId)||s.type===F.SUBTITLE_TRACK&&l.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=ti.SendAlternateToPenaltyBox,void(t.errorAction.flags=ii.MoveAllAlternatesMatchingHost)}return;case O.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=r.loadLevelObj,d=null==h?void 0:h.attrs["HDCP-LEVEL"];return void(d?t.errorAction={action:ti.SendAlternateToPenaltyBox,flags:ii.MoveAllAlternatesMatchingHDCP,hdcpLevel:d}:this.keySystemError(t));case O.BUFFER_ADD_CODEC_ERROR:case O.REMUX_ALLOC_ERROR:case O.BUFFER_APPEND_ERROR:var u;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(u=t.level)?u:r.loadLevel)));case O.INTERNAL_EXCEPTION:case O.BUFFER_APPENDING_ERROR:case O.BUFFER_FULL_ERROR:case O.LEVEL_SWITCH_ERROR:case O.BUFFER_STALLED_ERROR:case O.BUFFER_SEEK_OVER_HOLE:case O.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=si())}t.type===x.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},i.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},i.getPlaylistRetryOrSwitchAction=function(e,t){var i=Qt(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Zt(i,r,Xt(e),e.response))return{action:ti.RetryRequest,flags:ii.None,retryConfig:i,retryCount:r};var s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s},i.getFragRetryOrSwitchAction=function(e){var t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],s=t.config,n=s.fragLoadPolicy,a=s.keyLoadPolicy,o=Qt(e.details.startsWith("key")?a:n,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(r&&(e.details!==O.FRAG_GAP&&r.fragmentError++,Zt(o,l,Xt(e),e.response)))return{action:ti.RetryRequest,flags:ii.None,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,i);return o&&(h.retryConfig=o,h.retryCount=l),h},i.getLevelSwitchAction=function(e,t){var i=this.hls;null==t&&(t=i.loadLevel);var r=this.hls.levels[t];if(r){var s,n,a=e.details;r.loadError++,a===O.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,h=i.loadLevel,d=i.minAutoLevel,u=i.maxAutoLevel;i.autoLevelEnabled||(i.loadLevel=-1);for(var c,f=null==(s=e.frag)?void 0:s.type,g=(f===N.AUDIO&&a===O.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(a===O.BUFFER_ADD_CODEC_ERROR||a===O.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return r.audioCodec!==t})),m="video"===e.sourceBufferName&&(a===O.BUFFER_ADD_CODEC_ERROR||a===O.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,i=e.audioCodec;return r.codecSet!==t&&r.audioCodec===i})),p=null!=(n=e.context)?n:{},v=p.type,y=p.groupId,E=function(){var t=(T+h)%l.length;if(t!==h&&t>=d&&t<=u&&0===l[t].loadError){var i,s,n=l[t];if(a===O.FRAG_GAP&&f===N.MAIN&&e.frag){var c=l[t].details;if(c){var p=Vt(e.frag,c.fragments,e.frag.start);if(null!=p&&p.gap)return 0}}else{if(v===F.AUDIO_TRACK&&n.hasAudioGroup(y)||v===F.SUBTITLE_TRACK&&n.hasSubtitleGroup(y))return 0;if(f===N.AUDIO&&null!=(i=r.audioGroups)&&i.some((function(e){return n.hasAudioGroup(e)}))||f===N.SUBTITLE&&null!=(s=r.subtitleGroups)&&s.some((function(e){return n.hasSubtitleGroup(e)}))||g&&r.audioCodec===n.audioCodec||!g&&r.audioCodec!==n.audioCodec||m&&r.codecSet===n.codecSet)return 0}return o=t,1}},T=l.length;T--&&(0===(c=E())||1!==c););if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:ti.SendAlternateToPenaltyBox,flags:ii.None,nextAutoLevel:o}}return{action:ti.SendAlternateToPenaltyBox,flags:ii.MoveAllAlternatesMatchingHost}},i.onErrorOut=function(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case ti.DoNothing:break;case ti.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===O.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'+t.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},i.sendAlternateToPenaltyBox=function(e){var t=this.hls,i=e.errorAction;if(i){var r=i.flags,s=i.hdcpLevel,n=i.nextAutoLevel;switch(r){case ii.None:this.switchLevel(e,n);break;case ii.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=gt[gt.indexOf(s)-1],i.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')}i.resolved||this.switchLevel(e,n)}},i.switchLevel=function(e,t){if(void 0!==t&&e.errorAction&&(this.warn("switching to level "+t+" after "+e.details),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===O.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var i=ot(e.mimeType),r=this.hls.levels,s=r.length;s--;)r[s][e.sourceBufferName+"Codec"]===i&&this.hls.removeLevel(s)},t}(G);function si(e){var t={action:ti.DoNothing,flags:ii.None};return e&&(t.resolved=!0),t}var ni={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},ai=function(){function e(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}var t=e.prototype;return t._registerListeners=function(){var e=this.hls;e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.BUFFER_APPENDED,this.onBufferAppended,this),e.on(M.FRAG_BUFFERED,this.onFragBuffered,this),e.on(M.FRAG_LOADED,this.onFragLoaded,this)},t._unregisterListeners=function(){var e=this.hls;e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.BUFFER_APPENDED,this.onBufferAppended,this),e.off(M.FRAG_BUFFERED,this.onFragBuffered,this),e.off(M.FRAG_LOADED,this.onFragLoaded,this)},t.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var i=this.activePartLists[t];if(i)for(var r=i.length;r--;){var s=i[r];if(!s)break;var n=s.end;if(s.start<=e&&null!==n&&e<=n)return s}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,i){for(var r=this.fragments,s=Object.keys(r),n=s.length;n--;){var a=r[s[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){var o=a.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,i,r,s){var n=this;this.timeRanges&&(this.timeRanges[e]=t);var a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(r){var o=n.fragments[r];if(o&&!(a>=o.body.sn))if(o.buffered||o.loaded&&!s){var l=o.range[e];l&&(0!==l.time.length?l.time.some((function(e){var i=!n.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&n.removeFragment(o.body),i})):n.removeFragment(o.body))}else o.body.type===i&&n.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,i=this.timeRanges;if(i&&"initSegment"!==e.frag.sn){var r=e.frag,s=li(r),n=this.fragments[s];if(!(!n||n.buffered&&r.gap)){var a=!r.relurl;Object.keys(i).forEach((function(s){var o=r.elementaryStreams[s];if(o){var l=i[s],h=a||!0===o.partial;n.range[s]=t.getBufferedTimes(r,e.part,h,l)}})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=r.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),oi(n)||this.removeParts(r.sn-1,r.type)):this.removeFragment(n.body)}}},t.removeParts=function(e,t){var i=this.activePartLists[t];i&&(this.activePartLists[t]=hi(i,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var i=li(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)},t.getBufferedTimes=function(e,t,i,r){for(var s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n,h=0;h<r.length;h++){var d=r.start(h)-this.bufferPadding,u=r.end(h)+this.bufferPadding;if(l>=d&&o<=u){s.time.push({startPTS:Math.max(n,r.start(h)),endPTS:Math.min(a,r.end(h))});break}if(n<u&&a>d){var c=Math.max(n,r.start(h)),f=Math.min(a,r.end(h));f>c&&(s.partial=!0,s.time.push({startPTS:c,endPTS:f}))}else if(a<=d)break}return s},t.getPartialFragment=function(e){var t,i,r,s=null,n=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&oi(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||oi(t))},t.getState=function(e){var t=li(e),i=this.fragments[t];return i?i.buffered?oi(i)?ni.PARTIAL:ni.OK:ni.APPENDING:ni.NOT_LOADED},t.isTimeBuffered=function(e,t,i){for(var r,s,n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var i=t.frag,r=t.part?null:t,s=li(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var i=t.frag,r=t.part,s=t.timeRanges,n=t.type;if("initSegment"!==i.sn){var a=i.type;if(r){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=s;var l=s[n];this.detectEvictedFragments(n,l,a,r)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=li(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,i=Object.keys(t);if(!e)return i.length>0;for(var r=i.length;r--;){var s=t[i[r]];if((null==s?void 0:s.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,i,r,s){var n=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=n.fragments[a];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||s)&&n.removeFragment(l)}}))},t.removeFragment=function(e){var t=li(e);e.clearElementaryStreamInfo();var i=this.activePartLists[e.type];if(i){var r=e.sn;this.activePartLists[e.type]=hi(i,(function(e){return e.fragment.sn!==r}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var i=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;i&&i.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function oi(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function li(e){return e.type+"_"+e.level+"_"+e.sn}function hi(e,t){return e.filter((function(e){var i=t(e);return i||e.clearElementaryStreamInfo(),i}))}var di={cbc:0,ctr:1},ui=function(){function e(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case di.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case di.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}();function ci(e){var t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}var fi=function(){function e(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),i=new Uint32Array(4),r=0;r<4;r++)i[r]=t.getUint32(4*r);return i},t.initTable=function(){var e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256),f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){var p=g^g<<1^g<<2^g<<3^g<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var v=c[f],y=c[v],E=c[y],T=257*c[p]^16843008*p;r[f]=T<<24|T>>>8,s[f]=T<<16|T>>>16,n[f]=T<<8|T>>>24,a[f]=T,T=16843009*E^65537*y^257*v^16843008*f,l[p]=T<<24|T>>>8,h[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,u[p]=T,f?(f=v^c[c[c[E^v]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;r<t.length&&i;)i=t[r]===this.key[r],r++;if(!i){this.key=t;var s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);var n,a,o,l,h=this.ksRows=4*(s+6+1),d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,m=g[0],p=g[1],v=g[2],y=g[3];for(n=0;n<h;n++)n<s?o=d[n]=t[n]:(l=o,n%s==0?(l=c[(l=l<<8|l>>>24)>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[n/s|0]<<24):s>6&&n%s==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),d[n]=o=(d[n-s]^l)>>>0);for(a=0;a<h;a++)n=h-a,l=3&a?d[n]:d[n-4],u[a]=a<4||n<=4?l:m[c[l>>>24]]^p[c[l>>>16&255]]^v[c[l>>>8&255]]^y[c[255&l]],u[a]=u[a]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,i){for(var r,s,n,a,o,l,h,d,u,c,f,g,m,p,v=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,S=T[0],A=T[1],L=T[2],R=T[3],I=this.uint8ArrayToUint32Array_(i),b=I[0],D=I[1],k=I[2],_=I[3],P=new Int32Array(e),C=new Int32Array(P.length),w=this.networkToHostOrderSwap;t<P.length;){for(u=w(P[t]),c=w(P[t+1]),f=w(P[t+2]),g=w(P[t+3]),o=u^y[0],l=g^y[1],h=f^y[2],d=c^y[3],m=4,p=1;p<v;p++)r=S[o>>>24]^A[l>>16&255]^L[h>>8&255]^R[255&d]^y[m],s=S[l>>>24]^A[h>>16&255]^L[d>>8&255]^R[255&o]^y[m+1],n=S[h>>>24]^A[d>>16&255]^L[o>>8&255]^R[255&l]^y[m+2],a=S[d>>>24]^A[o>>16&255]^L[l>>8&255]^R[255&h]^y[m+3],o=r,l=s,h=n,d=a,m+=4;r=E[o>>>24]<<24^E[l>>16&255]<<16^E[h>>8&255]<<8^E[255&d]^y[m],s=E[l>>>24]<<24^E[h>>16&255]<<16^E[d>>8&255]<<8^E[255&o]^y[m+1],n=E[h>>>24]<<24^E[d>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[m+2],a=E[d>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&h]^y[m+3],C[t]=w(r^b),C[t+1]=w(a^D),C[t+2]=w(n^k),C[t+3]=w(s^_),b=u,D=c,k=f,_=g,t+=4}return C.buffer},e}(),gi=function(){function e(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}return e.prototype.expandKey=function(){var e=mi(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])},e}();function mi(e){switch(e){case di.cbc:return"AES-CBC";case di.ctr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+e)}}var pi=16,vi=function(){function e(e,t){var i=(void 0===t?{}:t).removePKCS7Padding,r=void 0===i||i;if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=r,r)try{var s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}var t=e.prototype;return t.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},t.isSync=function(){return this.useSoftware},t.flush=function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?ci(i):i},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,i,r){var s=this;return this.useSoftware?new Promise((function(n,a){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);s.softwareDecrypt(o,t,i,r);var l=s.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)},t.softwareDecrypt=function(e,t,i,r){var s=this.currentIV,n=this.currentResult,a=this.remainderData;if(r!==di.cbc||16!==t.byteLength)return q.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=xe(a,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;s&&(i=s);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new fi),l.expandKey(t);var h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null},t.webCryptoDecrypt=function(e,t,i,r){var s=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new gi(this.subtle,t,r)}return this.fastAesKey.expandKey().then((function(t){return s.subtle?(s.logOnce("WebCrypto AES decrypt"),new ui(s.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(n){return q.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+n.name+": "+n.message),s.onWebCryptoError(e,t,i,r)}))},t.onWebCryptoError=function(e,t,i,r){var s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);var n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")},t.getValidChunk=function(e){var t=e,i=e.length-e.length%pi;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t},t.logOnce=function(e){this.logEnabled&&(q.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),yi=Math.pow(2,17),Ei=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var i=this,r=e.url;if(!r)return Promise.reject(new Li({type:x.NETWORK_ERROR,details:O.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void l(Si(e));e.gap=!1}var h=i.loader=n?new n(s):new a(s),d=Ti(e);e.loader=h;var u=Jt(s.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:yi};e.stats=h.stats;var f={onSuccess:function(t,r,s,n){i.resetLoader(e,h);var a=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:n})},onError:function(t,s,n,a){i.resetLoader(e,h),l(new Li({type:x.NETWORK_ERROR,details:O.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:g({url:r,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:n,stats:a}))},onAbort:function(t,r,s){i.resetLoader(e,h),l(new Li({type:x.NETWORK_ERROR,details:O.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:function(t,r,s){i.resetLoader(e,h),l(new Li({type:x.NETWORK_ERROR,details:O.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+c.timeout+"ms"),networkDetails:s,stats:t}))}};t&&(f.onProgress=function(i,r,s,n){return t({frag:e,part:null,payload:s,networkDetails:n})}),h.load(d,c,f)}))},t.loadPart=function(e,t,i){var r=this;this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(r.loader&&r.loader.destroy(),e.gap||t.gap)l(Si(e,t));else{var h=r.loader=n?new n(s):new a(s),d=Ti(e,t);e.loader=h;var u=Jt(s.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:yi};t.stats=h.stats,h.load(d,c,{onSuccess:function(s,n,a,l){r.resetLoader(e,h),r.updateStatsFromPart(e,t);var d={frag:e,part:t,payload:s.data,networkDetails:l};i(d),o(d)},onError:function(i,s,n,a){r.resetLoader(e,h),l(new Li({type:x.NETWORK_ERROR,details:O.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:g({url:d.url,data:void 0},i),error:new Error("HTTP Error "+i.code+" "+i.text),networkDetails:n,stats:a}))},onAbort:function(i,s,n){e.stats.aborted=t.stats.aborted,r.resetLoader(e,h),l(new Li({type:x.NETWORK_ERROR,details:O.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:n,stats:i}))},onTimeout:function(i,s,n){r.resetLoader(e,h),l(new Li({type:x.NETWORK_ERROR,details:O.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+c.timeout+"ms"),networkDetails:n,stats:i}))}})}}))},t.updateStatsFromPart=function(e,t){var i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){var n=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/s),n),o=(n-a)*Math.round(i.loaded/a);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,h=r.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function Ti(e,t){void 0===t&&(t=null);var i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(P(s)&&P(n)){var a,o=s,l=n;if("initSegment"===e.sn&&Ai(null==(a=e.decryptdata)?void 0:a.method)){var h=n-s;h%16&&(l=n+(16-h%16)),0!==s&&(r.resetIV=!0,o=s-16)}r.rangeStart=o,r.rangeEnd=l}return r}function Si(e,t){var i=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),r={type:x.MEDIA_ERROR,details:O.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Li(r)}function Ai(e){return"AES-128"===e||"AES-256"===e}var Li=function(e){function t(t){var i;return(i=e.call(this,t.error.message)||this).data=void 0,i.data=t,i}return d(t,e),t}(E(Error)),Ri=function(e){function t(t,i){var r;return(r=e.call(this,t,i)||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}d(t,e);var i=t.prototype;return i.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},i.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},i.onHandlerDestroyed=function(){},i.hasInterval=function(){return!!this._tickInterval},i.hasNextTick=function(){return!!this._tickTimer},i.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},i.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},i.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},i.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},i.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},i.doTick=function(){},t}(G),Ii=function(e,t,i,r,s,n){void 0===r&&(r=0),void 0===s&&(s=-1),void 0===n&&(n=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=bi(),this.buffering={audio:bi(),video:bi(),audiovideo:bi()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=n};function bi(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Di={length:0,start:function(){return 0},end:function(){return 0}},ki=function(){function e(){}return e.isBuffered=function(t,i){if(t)for(var r=e.getBuffered(t),s=r.length;s--;)if(i>=r.start(s)&&i<=r.end(s))return!0;return!1},e.bufferedRanges=function(t){if(t){var i=e.getBuffered(t);return e.timeRangesToArray(i)}return[]},e.timeRangesToArray=function(e){for(var t=[],i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},e.bufferInfo=function(t,i,r){if(t){var s=e.bufferedRanges(t);if(s.length)return e.bufferedInfo(s,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}},e.bufferedInfo=function(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var r=-1,s=[];if(i)for(var n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(r=n);var a=s.length;if(a){var o=s[a-1].end;e[n].start-o<i?e[n].end>o&&(s[a-1].end=e[n].end):s.push(e[n])}else s.push(e[n])}else s=e;for(var l,h=0,d=t,u=t,c=0;c<s.length;c++){var f=s[c].start,g=s[c].end;if(-1===r&&t>=f&&t<=g&&(r=c),t+i>=f&&t<g)d=f,h=(u=g)-t;else if(t+i<f){l=f;break}}return{len:h,start:d||0,end:u||0,nextStart:l,buffered:e,bufferedIndex:r}},e.getBuffered=function(e){try{return e.buffered||Di}catch(e){return q.log("failed to get media.buffered",e),Di}},e}(),_i=/\{\$([a-zA-Z0-9-_]+)\}/g;function Pi(e){return _i.test(e)}function Ci(e,t){if(null!==e.variableList||e.hasVariableRefs){var i=e.variableList;return t.replace(_i,(function(t){var r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+r+'"')),t):s}))}return t}function wi(e,t,i){var r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{var a=new self.URL(i).searchParams;if(!a.has(r))throw new Error('"'+r+'" does not match any query parameter in URI: "'+i+'"');s=a.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+t.message))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+r+'"')):n[r]=s||""}function xi(e,t,i){var r=t.IMPORT;if(i&&r in i){var s=e.variableList;s||(e.variableList=s={}),s[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+r+'"'))}var Oi=/^(\d+)x(\d+)$/,Mi=/(.+?)=(".*?"|.*?)(?:,|$)/g,Fi=function(){function e(t,i){"string"==typeof t&&(t=e.parseAttrList(t,i)),l(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var i=new Uint8Array(t.length/2),r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(2*r,2*r+2),16);return i}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var i=this[e];return i?parseFloat(i):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=Oi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var i,r={},s='"';for(Mi.lastIndex=0;null!==(i=Mi.exec(e));){var n=i[1].trim(),a=i[2],o=0===a.indexOf(s)&&a.lastIndexOf(s)===a.length-1,l=!1;if(o)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(o||l))a=Ci(t,a);else if(!l&&!o)switch(n){case"CLOSED-CAPTIONS":if("NONE"===a)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":q.warn(e+": attribute "+n+" is missing quotes")}r[n]=a}return r},n(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}(),Ni="com.apple.hls.interstitial";function Ui(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function Bi(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var Gi=function(){function e(e,t,i){var r;if(void 0===i&&(i=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){var s=t.attr;for(var n in s)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==s[n]){q.warn('DATERANGE tag attribute: "'+n+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=n;break}e=l(new Fi({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){var a=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);P(a.getTime())&&(this._endDate=a)}}return n(e,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(q.warn('Expected tagAnchor Fragment with PDT set for DateRange "'+this.id+'": '+e),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(P(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return this.class===Ni}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&P(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}])}(),$i=10,Ki=function(){function e(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}return e.prototype.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},n(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&P(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||$i}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function Vi(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Hi(e){switch(e){case"AES-128":case"AES-256":return di.cbc;case"AES-256-CTR":return di.ctr;default:throw new Error("invalid full segment method "+e)}}function Yi(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function Wi(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}function ji(e){var t=Wi(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}function qi(e){var t=function(e,t,i){var r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function Xi(e){var t=e.split(":"),i=null;if("data"===t[0]&&2===t.length){var r=t[1].split(";"),s=r[r.length-1].split(",");if(2===s.length){var n="base64"===s[0],a=s[1];n?(r.splice(-1,1),i=Yi(a)):i=ji(a)}}return i}var Qi="undefined"!=typeof self?self:void 0,zi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ji={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Zi(e){switch(e){case Ji.FAIRPLAY:return zi.FAIRPLAY;case Ji.PLAYREADY:return zi.PLAYREADY;case Ji.WIDEVINE:return zi.WIDEVINE;case Ji.CLEARKEY:return zi.CLEARKEY}}var er={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function tr(e){return e===er.WIDEVINE?zi.WIDEVINE:e===er.PLAYREADY?zi.PLAYREADY:e===er.CENC||e===er.CLEARKEY?zi.CLEARKEY:void 0}function ir(e){switch(e){case zi.FAIRPLAY:return Ji.FAIRPLAY;case zi.PLAYREADY:return Ji.PLAYREADY;case zi.WIDEVINE:return Ji.WIDEVINE;case zi.CLEARKEY:return Ji.CLEARKEY}}function rr(e){var t=e.drmSystems,i=e.widevineLicenseUrl,r=t?[zi.FAIRPLAY,zi.WIDEVINE,zi.PLAYREADY,zi.CLEARKEY].filter((function(e){return!!t[e]})):[];return!r[zi.WIDEVINE]&&i&&r.push(zi.WIDEVINE),r}var sr,nr=null!=Qi&&null!=(sr=Qi.navigator)&&sr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function ar(e,t,i,r){var s;switch(e){case zi.FAIRPLAY:s=["cenc","sinf"];break;case zi.WIDEVINE:case zi.PLAYREADY:s=["cenc"];break;case zi.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+e)}return or(s,t,i,r)}function or(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((function(e){return{contentType:"audio/mp4; codecs="+e,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}})),videoCapabilities:i.map((function(e){return{contentType:"video/mp4; codecs="+e,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}}))}]}function lr(e){var t;return"persistent-license"===e.sessionType||!(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e})))}function hr(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),s=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){var n=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(n){var a=Yi(n).subarray(0,16);return qi(a),a}}return null}var dr={},ur=function(){function e(e,t,i,r,s){void 0===r&&(r=[1]),void 0===s&&(s=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Vi(e)}e.clearKeyUriToKeyIdMap=function(){dr={}};var t=e.prototype;return t.isSupported=function(){if(this.method){if(Vi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ji.FAIRPLAY:case Ji.WIDEVINE:case Ji.PLAYREADY:case Ji.CLEARKEY:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t){if(!this.encrypted||!this.uri)return null;if(Vi(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(q.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0);var i=cr(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}var r=Xi(this.uri);if(r)switch(this.keyFormat){case Ji.WIDEVINE:this.pssh=r,r.length>=22&&(this.keyId=r.subarray(r.length-22,r.length-6));break;case Ji.PLAYREADY:var s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=$e(s,null,r),this.keyId=hr(r);break;default:var n=r.subarray(0,16);if(16!==n.length){var a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n}if(!this.keyId||16!==this.keyId.byteLength){var o=dr[this.uri];if(!o){var l=Object.keys(dr).length%Number.MAX_SAFE_INTEGER;o=new Uint8Array(16),new DataView(o.buffer,12,4).setUint32(0,l),dr[this.uri]=o}this.keyId=o}return this},e}();function cr(e){for(var t=new Uint8Array(16),i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}var fr=/#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,gr=/#EXT-X-MEDIA:(.*)/g,mr=/^#EXT(?:INF|-X-TARGETDURATION):/m,pr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),vr=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("|")),yr=function(){function e(){}return e.findGroup=function(e,t){for(var i=0;i<e.length;i++){var r=e[i];if(r.id===t)return r}},e.resolve=function(e,t){return _.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return mr.test(e)},e.parseMasterPlaylist=function(t,i){var r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Pi(t)},n=[];for(fr.lastIndex=0;null!=(r=fr.exec(t));)if(r[1]){var a,o=new Fi(r[1],s),l=Ci(s,r[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,i)},d=o.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),Lr(o.CODECS,h);var u=o["SUPPLEMENTAL-CODECS"];u&&(h.supplemental={},Lr(u,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||n.push(h),s.levels.push(h)}else if(r[3]){var c=r[3],f=r[4];switch(c){case"SESSION-DATA":var g=new Fi(f,s),m=g["DATA-ID"];m&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[m]=g);break;case"SESSION-KEY":var p=Sr(f,i,s);p.encrypted&&p.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(p)):q.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":wi(s,new Fi(f,s),i);break;case"CONTENT-STEERING":var v=new Fi(f,s);s.contentSteering={uri:e.resolve(v["SERVER-URI"],i),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":s.startTimeOffset=Ar(f)}}var y=n.length>0&&n.length<s.levels.length;return s.levels=y?n:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s},e.parseMasterPlaylistMedia=function(t,i,r){var s,n={},a=r.levels,o={AUDIO:a.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),SUBTITLES:a.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(gr.lastIndex=0;null!==(s=gr.exec(t));){var h=new Fi(s[1],r),d=h.TYPE;if(d){var u=o[d],c=n[d]||[];n[d]=c;var f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],m=h.CHANNELS,p=h.CHARACTERISTICS,v=h["INSTREAM-ID"],y={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:d,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?e.resolve(h.URI,i):""};if(g&&(y.assocLang=g),m&&(y.channels=m),p&&(y.characteristics=p),v&&(y.instreamId=v),null!=u&&u.length){var E=e.findGroup(u,y.groupId)||u[0];Rr(y,E,"audioCodec"),Rr(y,E,"textCodec")}c.push(y)}}return n},e.parseLevelPlaylist=function(e,t,i,r,s,n){var a,o,h,d,u,c={url:t},f=new Ki(t),g=f.fragments,m=[],p=null,v=0,y=0,E=0,T=0,S=0,A=null,L=new se(r,c),R=-1,I=!1,b=null;if(pr.lastIndex=0,f.m3u8=e,f.hasVariableRefs=Pi(e),"#EXTM3U"!==(null==(a=pr.exec(e))?void 0:a[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(o=pr.exec(e));){I&&(I=!1,(L=new se(r,c)).playlistOffset=E,L.start=E,L.sn=v,L.cc=T,S&&(L.bitrate=S),L.level=i,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),b&&(L.setByteRange(b),b=null)));var D=o[1];if(D){L.duration=parseFloat(D);var k=(" "+o[2]).slice(1);L.title=k||null,L.tagList.push(k?["INF",D,k]:["INF",D])}else if(o[3]){if(P(L.duration)){L.playlistOffset=E,L.start=E,d&&kr(L,d,f),L.sn=v,L.level=i,L.cc=T,g.push(L);var _=(" "+o[3]).slice(1);L.relurl=Ci(f,_),br(L,A,m),A=L,E+=L.duration,v++,y=0,I=!0}}else{if(!(o=o[0].match(vr))){q.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<o.length&&void 0===o[h];h++);var C=(" "+o[h]).slice(1),w=(" "+o[h+1]).slice(1),x=o[h+2]?(" "+o[h+2]).slice(1):null;switch(C){case"BYTERANGE":A?L.setByteRange(w,A):L.setByteRange(w);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=w,L.tagList.push(["PROGRAM-DATE-TIME",w]),-1===R&&(R=g.length);break;case"PLAYLIST-TYPE":f.type&&_r(f,C,o),f.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?_r(f,C,o):g.length>0&&Pr(f,C,o),v=f.startSN=parseInt(w);break;case"SKIP":f.skippedSegments&&_r(f,C,o);var O=new Fi(w,f),M=O.decimalInteger("SKIPPED-SEGMENTS");if(P(M)){f.skippedSegments+=M;for(var F=M;F--;)g.push(null);v+=M}var N=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(N.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&_r(f,C,o),f.targetduration=Math.max(parseInt(w),1);break;case"VERSION":null!==f.version&&_r(f,C,o),f.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||_r(f,C,o),f.live=!1;break;case"#":(w||x)&&L.tagList.push(x?[w,x]:[w]);break;case"DISCONTINUITY":T++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([C]);break;case"BITRATE":L.tagList.push([C,w]),S=1e3*parseInt(w),P(S)?L.bitrate=S:S=0;break;case"DATERANGE":var U=new Fi(w,f),B=new Gi(U,f.dateRanges[U.ID],f.dateRangeTagCount);f.dateRangeTagCount++,B.isValid||f.skippedSegments?f.dateRanges[B.id]=B:q.warn('Ignoring invalid DATERANGE tag: "'+w+'"'),L.tagList.push(["EXT-X-DATERANGE",w]);break;case"DEFINE":var G=new Fi(w,f);"IMPORT"in G?xi(f,G,n):wi(f,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?_r(f,C,o):g.length>0&&Pr(f,C,o),f.startCC=T=parseInt(w);break;case"KEY":var $=Sr(w,t,f);if($.isSupported()){if("NONE"===$.method){d=void 0;break}d||(d={}),d[$.keyFormat]&&(d=l({},d)),d[$.keyFormat]=$}else q.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+w+'"');break;case"START":f.startTimeOffset=Ar(w);break;case"MAP":var K=new Fi(w,f);if(L.duration){var V=new se(r,c);Dr(V,K,i,d),p=V,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{var H=L.byteRangeEndOffset;if(H){var Y=L.byteRangeStartOffset;b=H-Y+"@"+Y}else b=null;Dr(L,K,i,d),p=L,I=!0}p.cc=T;break;case"SERVER-CONTROL":u&&_r(f,C,o),u=new Fi(w),f.canBlockReload=u.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=u.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&u.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=u.optionalFloat("PART-HOLD-BACK",0),f.holdBack=u.optionalFloat("HOLD-BACK",0);break;case"PART-INF":f.partTarget&&_r(f,C,o);var W=new Fi(w);f.partTarget=W.decimalFloatingPoint("PART-TARGET");break;case"PART":var j=f.partList;j||(j=f.partList=[]);var X=y>0?j[j.length-1]:void 0,Q=y++,z=new Fi(w,f),J=new ne(z,L,c,Q,X);j.push(J),L.duration+=J.duration;break;case"PRELOAD-HINT":var Z=new Fi(w,f);f.preloadHint=Z;break;case"RENDITION-REPORT":var ee=new Fi(w,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(ee);break;default:q.warn("line parsed but not handled: "+o)}}}A&&!A.relurl?(g.pop(),E-=A.duration,f.partList&&(f.fragmentHint=A)):f.partList&&(br(L,A,m),L.cc=T,f.fragmentHint=L,d&&kr(L,d,f)),f.targetduration||(f.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));var te=g.length,ie=g[0],re=g[te-1];if((E+=f.skippedSegments*f.targetduration)>0&&te&&re){f.averagetargetduration=E/te;var ae=re.sn;f.endSN="initSegment"!==ae?ae:0,f.live||(re.endList=!0),ie&&void 0===f.startCC&&(f.startCC=ie.cc),R>0&&(Ir(g,R),ie&&m.unshift(ie))}else f.endSN=0,f.startCC=0;return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,m.length&&f.dateRangeTagCount&&ie&&Er(m,f),f.endCC=T,f},e}();function Er(e,t){for(var i=e.length,r=e[i-1],s=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges),a=n.length;a--;){var o=t.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=r.ref;for(var h=i;h--;){var d=Tr(t,l,e,h,s);if(-1!==d){o.tagAnchor=t.fragments[d].ref;break}}}}function Tr(e,t,i,r,s){var n=i[r];if(n){var a,o=n.programDateTime;if((t>=o||0===r)&&t<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||s)-n.start)){var l=i[r].sn-e.startSN,h=e.fragments;if(h.length>i.length)for(var d=(i[r+1]||h[h.length-1]).sn-e.startSN;d>l;d--){var u=h[d].programDateTime;if(t>=u&&t<u+1e3*h[d].duration)return d}return l}}return-1}function Sr(e,t,i){var r,s,n=new Fi(e,i),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&q.error("Invalid IV: "+n.IV);var u=o?yr.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ur(a,u,d,c,l)}function Ar(e){var t=new Fi(e).decimalFloatingPoint("TIME-OFFSET");return P(t)?t:null}function Lr(e,t){var i=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var r=i.filter((function(t){return We(t,e)}));r.length&&(t[e+"Codec"]=r.map((function(e){return e.split("/")[0]})).join(","),i=i.filter((function(e){return-1===r.indexOf(e)})))})),t.unknownCodecs=i}function Rr(e,t,i){var r=t[i];r&&(e[i]=r)}function Ir(e,t){for(var i=e[t],r=t;r--;){var s=e[r];if(!s)return;s.programDateTime=i.programDateTime-1e3*s.duration,i=s}}function br(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Dr(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function kr(e,t,i){e.levelkeys=t;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||r.push(e)}function _r(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+i[0]+")")}function Pr(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+i[0]+")")}function Cr(e,t){var i=t.startPTS;if(P(i)){var r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function wr(e,t,i,r,s,n){r-i<=0&&(q.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);var a=i,o=r,l=t.startPTS,h=t.endPTS;if(P(l)){var d=Math.abs(l-i);P(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,a=Math.max(i,l),i=Math.min(i,l),s=Math.min(s,t.startDTS),o=Math.min(r,h),r=Math.max(r,h),n=Math.max(n,t.endDTS)}var u=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=n;var c,f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;var g=f-e.startSN,m=e.fragments;for(m[g]=t,c=g;c>0;c--)Cr(m[c],m[c-1]);for(c=g;c<m.length-1;c++)Cr(m[c],m[c+1]);return e.fragmentHint&&Cr(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function xr(e,t){if(e!==t){for(var i,r=null,s=e.fragments,n=s.length-1;n>=0;n--){var a=s[n].initSegment;if(a){r=a;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,Fr(e,t,(function(s,n,a,o){if(!t.startCC&&n.cc!==s.cc){for(var l,h,d=s.cc-n.cc,u=a;u<o.length;u++)o[u].cc+=d;t.startCC=null!=(l=null==(h=$r(e,t.startSN-1))?void 0:h.cc)?l:o[0].cc,t.endCC=o[o.length-1].cc}P(s.startPTS)&&P(s.endPTS)&&(n.setStart(n.startPTS=s.startPTS),n.startDTS=s.startDTS,n.maxStartPTS=s.maxStartPTS,n.endPTS=s.endPTS,n.endDTS=s.endDTS,n.minEndPTS=s.minEndPTS,n.setDuration(s.endPTS-s.startPTS),n.duration&&(i=n),t.PTSKnown=t.alignedSliding=!0),s.hasStreams&&(n.elementaryStreams=s.elementaryStreams),n.loader=s.loader,s.hasStats&&(n.stats=s.stats),s.initSegment&&(n.initSegment=s.initSegment,r=s.initSegment)}));var o=t.fragments,l=t.fragmentHint?o.concat(t.fragmentHint):o;if(r&&l.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)})),t.skippedSegments)if(t.deltaUpdateFailed=o.some((function(e){return!e})),t.deltaUpdateFailed){q.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var h=t.skippedSegments;h--;)o.shift();t.startSN=o[0].sn}else{t.endCC=o[o.length-1].cc,t.canSkipDateRanges&&(t.dateRanges=Or(e.dateRanges,t));var d=e.fragments.filter((function(e){return e.rawProgramDateTime}));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var u=1;u<l.length;u++)null===l[u].programDateTime&&br(l[u],l[u-1],d);Er(d,t)}Mr(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),i?wr(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):Ur(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var c=t.advancedDateTime;if(t.advanced&&c){var f=t.edge;t.driftStart||(t.driftStartTime=c,t.driftStart=f),t.driftEndTime=c,t.driftEnd=f}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Or(e,t){var i=t.dateRanges,r=t.recentlyRemovedDateranges,s=l({},e);r&&r.forEach((function(e){delete s[e]}));var n=Object.keys(s).length;return n&&Object.keys(i).forEach((function(e){var t=s[e],r=new Gi(i[e].attr,t);r.isValid?(s[e]=r,t||(r.tagOrder+=n)):q.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+bt(i[e].attr)+'"')})),s}function Mr(e,t,i){if(e&&t)for(var r=0,s=0,n=e.length;s<=n;s++){var a=e[s],o=t[s+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):r--}}function Fr(e,t,i){for(var r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=s;h<=n;h++){var d=l[a+h],u=o[h];if(r&&!u&&d&&(u=t.fragments[h]=d),d&&u){if(i(d,u,h,o),d.url&&d.url!==u.url)return void(t.playlistParsingError=Nr("media sequence mismatch "+u.sn+":",e,t,d,u));if(d.cc!==u.cc)return void(t.playlistParsingError=Nr("discontinuity sequence mismatch ("+d.cc+"!="+u.cc+")",e,t,d,u))}}}function Nr(e,t,i,r,s){return new Error(e+" "+s.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+i.startSN+"\n"+i.m3u8)}function Ur(e,t,i){void 0===i&&(i=!0);var r=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,n=r>=0,a=0;if(n&&r<s.length)a=s[r].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}Br(t,a)}function Br(e,t){if(t){for(var i=e.fragments,r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Gr(e,t){void 0===t&&(t=1/0);var i=1e3*e.targetduration;if(e.updated){var r=e.fragments,s=4;if(r.length&&i*s>t){var n=1e3*r[r.length-1].duration;n<i&&(i=n)}}else i/=2;return Math.round(i)}function $r(e,t,i){if(!e)return null;var r=e.fragments[t-e.startSN];return r||((r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function Kr(e,t,i){return e?Vr(e.partList,t,i):null}function Vr(e,t,i){if(e)for(var r=e.length;r--;){var s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function Hr(e){e.forEach((function(e,t){var i;null==(i=e.details)||i.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function Yr(e,t){for(var i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function Wr(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function jr(e,t){if(e){var i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function qr(e,t){for(var i=t.fragments,r=0,s=i.length;r<s;r++)jr(i[r],e);t.fragmentHint&&jr(t.fragmentHint,e),t.alignedSliding=!0}function Xr(e,t){e&&(Qr(t,e),!t.alignedSliding&&e&&zr(t,e),t.alignedSliding||!e||t.skippedSegments||Ur(e,t,!1))}function Qr(e,t){if(Wr(t,e)){var i=Math.min(t.endCC,e.endCC),r=Yr(t.fragments,i),s=Yr(e.fragments,i);r&&s&&(q.log("Aligning playlist at start of dicontinuity sequence "+i),qr(r.start-s.start,e))}}function zr(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i=e.fragments,r=t.fragments;if(i.length&&r.length){var s,n,a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=Yr(r,a),n=Yr(i,a)),s&&n||(n=Yr(i,(s=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.length/2)]);var o=s.programDateTime,l=n.programDateTime;o&&l&&qr((l-o)/1e3-(n.start-s.start),e)}}}var Jr={toString:function(e){for(var t="",i=e.length,r=0;r<i;r++)t+="["+e.start(r).toFixed(3)+"-"+e.end(r).toFixed(3)+"]";return t}},Zr={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},es=function(e){function t(t,i,r,s,n){var a;return(a=e.call(this,s,t.logger)||this).hls=void 0,a.fragPrevious=null,a.fragCurrent=null,a.fragmentTracker=void 0,a.transmuxer=null,a._state=Zr.STOPPED,a.playlistType=void 0,a.media=null,a.mediaBuffer=null,a.config=void 0,a.bitrateTest=!1,a.lastCurrentTime=0,a.nextLoadPosition=0,a.startPosition=0,a.startTimeOffset=null,a.retryDate=0,a.levels=null,a.fragmentLoader=void 0,a.keyLoader=void 0,a.levelLastLoaded=null,a.startFragRequested=!1,a.decrypter=void 0,a.initPTS=[],a.buffering=!0,a.loadingParts=!1,a.loopSn=void 0,a.onMediaSeeking=function(){var e=a,t=e.config,i=e.fragCurrent,r=e.media,s=e.mediaBuffer,n=e.state,o=r?r.currentTime:0,l=ki.bufferInfo(s||r,o,t.maxBufferHole);if(a.log("media seeking to "+(P(o)?o.toFixed(3):o)+", state: "+n),a.state===Zr.ENDED)a.resetLoadingState();else if(i){var h=t.maxFragLookUpTolerance,d=i.start-h,u=i.start+i.duration+h;if(!l.len||u<l.start||d>l.end){var c=o>u;(o<d||c)&&(c&&i.loader&&(a.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),i.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(r&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var f=Math.max(l.end,o),g=a.shouldLoadParts(a.getLevelDetails(),f);g&&(a.log("LL-Part loading ON after seeking to "+o.toFixed(2)+" with buffer @"+f.toFixed(2)),a.loadingParts=g)}a.hls.hasEnoughToStart||l.len||(a.log("setting startPosition to "+o+" because of seek before start"),a.nextLoadPosition=a.startPosition=o),a.tickImmediate()},a.onMediaEnded=function(){a.log("setting startPosition to 0 because media ended"),a.startPosition=a.lastCurrentTime=0},a.playlistType=n,a.hls=t,a.fragmentLoader=new Ei(t.config),a.keyLoader=r,a.fragmentTracker=i,a.config=t.config,a.decrypter=new vi(t.config),a}d(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.ERROR,this.onError,this)},i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(e){},i.stopLoad=function(){if(this.state!==Zr.STOPPED){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Zr.STOPPED}},i.pauseBuffering=function(){this.buffering=!1},i.resumeBuffering=function(){this.buffering=!0},i._streamEnded=function(e,t){if(t.live||!this.media)return!1;var i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var s=e.nextStart;if(s&&s>r&&s<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var n=t.partList;if(null!=n&&n.length){var a=n[n.length-1];return ki.isBuffered(this.media,a.start+a.duration/2)}var o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)},i.getLevelDetails=function(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details},i.onMediaAttached=function(e,t){var i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===Zr.STOPPED&&this.startLoad(r.startPosition)},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},i.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},i.onError=function(e,t){},i.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},i.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},i.onHandlerDestroyed=function(){this.state=Zr.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,e.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)},i._loadFragForPlayback=function(e,t,i){var r=this,s=function(e){var t=e.frag;if(r.fragContextChanged(t))return r.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+r.fragInfo(t,!1,e.part)+") was dropped during download."),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)};this._doFragLoad(e,t,i,s).then((function(e){if(e){var t=r.state,i=e.frag;r.fragContextChanged(i)?(t===Zr.FRAG_LOADING||!r.fragCurrent&&t===Zr.PARSING)&&(r.fragmentTracker.removeFragment(i),r.state=Zr.IDLE):("payload"in e&&(r.log("Loaded "+i.type+" sn: "+i.sn+" of "+r.playlistLabel()+" "+i.level),r.hls.trigger(M.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}})).catch((function(t){r.state!==Zr.STOPPED&&r.state!==Zr.ERROR&&(r.warn("Frag error: "+((null==t?void 0:t.message)||t)),r.resetFragmentLoading(e))}))},i.clearTrackerIfNeeded=function(e){var t,i=this.fragmentTracker;if(i.getState(e)===ni.APPENDING){var r=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,r),n=Math.max(e.duration,s?s.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(n,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===ni.PARTIAL&&i.removeFragment(e))},i.checkLiveUpdate=function(e){if(e.updated&&!e.live){var t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)},i.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},i.flushMainBuffer=function(e,t,i){if(void 0===i&&(i=null),e-t){var r={startOffset:e,endOffset:t,type:i};this.hls.trigger(M.BUFFER_FLUSHING,r)}},i._loadInitSegment=function(e,t){var i=this;this._doFragLoad(e,t).then((function(e){var t=null==e?void 0:e.frag;if(!t||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e})).then((function(e){var t=i.hls,r=e.frag,s=e.payload,n=r.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&Vi(n.method)){var a=self.performance.now();return i.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,Hi(n.method)).catch((function(e){throw t.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e})).then((function(s){var n=self.performance.now();return t.trigger(M.FRAG_DECRYPTED,{frag:r,payload:s,stats:{tstart:a,tdecrypt:n}}),e.payload=s,i.completeInitSegmentLoad(e)}))}return i.completeInitSegmentLoad(e)})).catch((function(t){i.state!==Zr.STOPPED&&i.state!==Zr.ERROR&&(i.warn(t),i.resetFragmentLoading(e))}))},i.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==Zr.STOPPED&&(this.state=Zr.IDLE),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},i.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},i.fragBufferedComplete=function(e,t){var i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+" > buffer:"+(i?Jr.toString(ki.getBuffered(i)):"(detached)")+")"),re(e)){var r;if(e.type!==N.SUBTITLE){var s=e.elementaryStreams;if(!Object.keys(s).some((function(e){return!!s[e]})))return void(this.state=Zr.IDLE)}var n=null==(r=this.levels)?void 0:r[e.level];null!=n&&n.fragmentError&&(this.log("Resetting level fragment error count of "+n.fragmentError+" on frag buffered"),n.fragmentError=0)}this.state=Zr.IDLE},i._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var i=e.frag,r=e.part,s=e.partsLoaded,n=!s||0===s.length||s.some((function(e){return!e})),a=new Ii(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}},i._handleFragmentLoadProgress=function(e){},i._doFragLoad=function(e,t,i,r){var s,n=this;void 0===i&&(i=null),this.fragCurrent=e;var a=null==t?void 0:t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var o=null;!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments):(this.log("Loading key for "+e.sn+" of ["+a.startSN+"-"+a.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=Zr.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(M.KEY_LOADED,e),n.state===Zr.KEY_LOADING&&(n.state=Zr.IDLE),e})),this.hls.trigger(M.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));var l=this.fragPrevious;if(re(e)&&(!l||e.sn!==l.sn)){var h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log("LL-Part loading "+(h?"ON":"OFF")+" loading sn "+(null==l?void 0:l.sn)+"->"+e.sn),this.loadingParts=h)}if(i=Math.max(e.start,i||0),this.loadingParts&&re(e)){var d=a.partList;if(d&&r){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);var u=this.getNextPart(d,e,i);if(u>-1){var c,f=d[u];return e=this.fragCurrent=f.fragment,this.log("Loading "+e.type+" sn: "+e.sn+" part: "+f.index+" ("+u+"/"+(d.length-1)+") of "+this.fragInfo(e,!1,f)+") cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(i.toFixed(3))),this.nextLoadPosition=f.start+f.duration,this.state=Zr.FRAG_LOADING,c=o?o.then((function(i){return!i||n.fragContextChanged(i.frag)?null:n.doFragPartsLoad(e,f,t,r)})).catch((function(e){return n.handleFragLoadError(e)})):this.doFragPartsLoad(e,f,t,r).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(M.FRAG_LOADING,{frag:e,part:f,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}if(re(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+i.toFixed(2)),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" of "+this.fragInfo(e,!1)+") cc: "+e.cc+" "+(a?"["+a.startSN+"-"+a.endSN+"]":"")+", target: "+parseFloat(i.toFixed(3))),P(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Zr.FRAG_LOADING;var g,m=this.config.progressive;return g=m&&o?o.then((function(t){return!t||n.fragContextChanged(null==t?void 0:t.frag)?null:n.fragmentLoader.load(e,r)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,m?r:void 0),o]).then((function(e){var t=e[0];return!m&&t&&r&&r(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(M.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g},i.doFragPartsLoad=function(e,t,i,r){var s=this;return new Promise((function(n,a){var o,l=[],h=null==(o=i.details)?void 0:o.partList,d=function(t){s.fragmentLoader.loadPart(e,t,r).then((function(r){l[t.index]=r;var a=r.part;s.hls.trigger(M.FRAG_LOADED,r);var o=Kr(i.details,e.sn,t.index+1)||Vr(h,e.sn,t.index+1);if(!o)return n({frag:e,part:a,partsLoaded:l});d(o)})).catch(a)};d(t)}))},i.handleFragLoadError=function(e){if("data"in e){var t=e.data;e.data&&t.details===O.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(M.ERROR,t)}else this.hls.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},i._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===Zr.PARSING){var i=t.frag,r=t.part,s=t.level,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n);var a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+i.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(i,r,s,e.partial)}else this.fragCurrent||this.state===Zr.STOPPED||this.state===Zr.ERROR||(this.state=Zr.IDLE)},i.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var i,r,s=e.partList[0];if(t>=s.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1},i.getCurrentContext=function(e){var t=this.levels,i=this.fragCurrent,r=e.level,s=e.sn,n=e.part;if(null==t||!t[r])return this.warn("Levels object was unset while buffering fragment "+s+" of "+this.playlistLabel()+" "+r+". The current chunk will not be buffered."),null;var a=t[r],o=a.details,l=n>-1?Kr(o,s,n):null,h=l?l.fragment:$r(o,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null},i.bufferFragmentData=function(e,t,i,r,s){var n;if(e&&this.state===Zr.PARSING){var a=e.data1,o=e.data2,l=a;if(a&&o&&(l=xe(a,o)),null!=(n=l)&&n.length){var h={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(M.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}}},i.flushBufferGap=function(e){var t=this.media;if(t)if(ki.isBuffered(t,t.currentTime)){var i=t.currentTime,r=ki.bufferInfo(t,i,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,r.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},i.getFwdBufferInfo=function(e,t){var i,r=this.getLoadPosition();if(!P(r))return null;var s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,s)},i.getFwdBufferInfoAtPos=function(e,t,i,r){var s=ki.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){var n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(s.nextStart<=n.end||n.gap)){var a=Math.max(Math.min(s.nextStart,n.end)-t,r);return ki.bufferInfo(e,t,a)}}return s},i.getMaxBufferLength=function(e){var t,i=this.config;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)},i.reduceMaxBufferLength=function(e,t){var i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn("Reduce max buffer length to "+s+"s"),!0)},i.getAppendedFrag=function(e,t){var i;void 0===t&&(t=N.MAIN);var r=null==(i=this.fragmentTracker)?void 0:i.getAppendedFrag(e,t);return r&&"fragment"in r?r.fragment:r},i.getNextFragment=function(e,t){var i=t.fragments,r=i.length;if(!r)return null;var s=this.config,n=i[0].start,a=s.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=s.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: "+r+", need: "+l+")"),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var h;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t,i);var d=this.hls.startPosition,u=this.hls.liveSyncPosition,c=o?(-1!==d&&d>=n?d:u)||o.start:e;this.log("Setting startPosition to "+c+" to match start frag at live edge. mainStart: "+d+" liveSyncPosition: "+u+" frag.start: "+(null==(h=o)?void 0:h.start)),this.startPosition=this.nextLoadPosition=c}}else e<=n&&(o=i[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var g=this.filterReplacedPrimary(o,t);if(!g&&o){var m=o.sn-t.startSN;g=this.filterReplacedPrimary(i[m+1]||null,t)}return this.mapToInitFragWhenRequired(g)},i.isLoopLoading=function(e,t){var i=this.fragmentTracker.getState(e);return(i===ni.OK||i===ni.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t},i.getNextFragmentLoopLoading=function(e,t,i,r,s){var n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t))&&!n.gap&&i.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==a&&i.len+a.len>=s){var o=n.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+r+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,n},i.filterReplacedPrimary=function(e,t){if(!e)return e;if(ts(this.hls.config)&&e.type!==N.SUBTITLE){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var s=r.event;if(s){if(s.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}var n=null==i?void 0:i.playerQueue;if(n)for(var a=n.length;a--;){var o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e},i.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment},i.getNextPart=function(e,t,i){for(var r=-1,s=!1,n=!0,a=0,o=e.length;a<o;a++){var l=e[a];if(n=n&&!l.independent,r>-1&&i<l.start)break;var h=l.loaded;h?r=-1:(s||l.independent||n)&&l.fragment===t&&(r=a),s=h}return r},i.loadedEndOfParts=function(e,t){var i=e[e.length-1];return i&&t>i.start&&i.loaded},i.getInitialLiveFragment=function(e,t){var i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+i.programDateTime),r=Kt(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){var n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=jt(t,i.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(r=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r},i.getFragmentAtPosition=function(e,t,i){var r,s,n=this.config,a=this.fragPrevious,o=i.fragments,l=i.endSN,h=i.fragmentHint,d=n.maxFragLookUpTolerance,u=i.partList,c=!!(this.loadingParts&&null!=u&&u.length&&h);if(c&&h&&!this.bitrateTest&&u[u.length-1].fragment.sn===h.sn&&(o=o.concat(h),l=h.sn),r=e<t?Vt(a,o,e,e<this.lastCurrentTime||e>t-d||null!=(s=this.media)&&s.paused||!this.startFragRequested?0:d):o[o.length-1]){var f=r.sn-i.startSN,g=this.fragmentTracker.getState(r);if((g===ni.OK||g===ni.PARTIAL&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||u[0].fragment.sn>r.sn||!i.live&&!c)&&a&&r.level===a.level){var m=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(m)!==ni.OK?m:null}}return r},i.alignPlaylists=function(e,t,i){var r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;var s=e.fragmentStart,n=!t,a=e.alignedSliding&&P(s);if(n||!a&&!s){Xr(i,e);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+r),o}return s},i.waitForCdnTuneIn=function(e){var t=3;return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*t)},i.setStartPosition=function(e,t){var i=this.startPosition;i<t&&(i=-1);var r=this.timelineOffset;if(-1===i){var s=null!==this.startTimeOffset,n=s?this.startTimeOffset:e.startTimeOffset;null!==n&&P(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log("Setting startPosition to "+i+" for start time offset "+n+" found in "+(s?"multivariant":"media")+" playlist"),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge "+i),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r},i.getLoadPosition=function(){var e,t=this.media,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i},i.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&re(e)&&e.stats.aborted&&(this.warn("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},i.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Zr.FRAG_LOADING_WAITING_RETRY)||(this.state=Zr.IDLE)},i.onFragmentOrKeyLoadError=function(e,t){if(t.chunkMeta&&!t.frag){var i=this.getCurrentContext(t.chunkMeta);i&&(t.frag=i.frag)}var r=t.frag;if(r&&r.type===e&&this.levels)if(this.fragContextChanged(r)){var s;this.warn("Frag load error must match current frag to retry "+r.url+" > "+(null==(s=this.fragCurrent)?void 0:s.url))}else{var n=t.details===O.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(r,!0);var a=t.errorAction,o=a||{},l=o.action,h=o.flags,d=o.retryCount,u=void 0===d?0:d,c=o.retryConfig,f=!!a&&!!c,g=f&&l===ti.RetryRequest,m=f&&!a.resolved&&h===ii.MoveAllAlternatesMatchingHost;if(!g&&m&&re(r)&&!r.endList)this.resetFragmentErrors(e),this.treatAsGap(r),a.resolved=!0;else if((g||m)&&u<c.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);var p=zt(c,u);this.warn("Fragment "+r.sn+" of "+e+" "+r.level+" errored with "+t.details+", retrying loading "+(u+1)+"/"+c.maxNumRetry+" in "+p+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+p,this.state=Zr.FRAG_LOADING_WAITING_RETRY}else if(c&&a){if(this.resetFragmentErrors(e),!(u<c.maxNumRetry))return void this.warn(t.details+" reached or exceeded max retry ("+u+")");n||l===ti.RemoveAlternatePermanently||(a.resolved=!0)}else l===ti.SendAlternateToPenaltyBox?this.state=Zr.WAITING_LEVEL:this.state=Zr.ERROR;this.tickImmediate()}},i.reduceLengthAndFlushBuffer=function(e){if(this.state===Zr.PARSING||this.state===Zr.PARSED){var t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);var n=!s;return n&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+i+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1},i.resetFragmentErrors=function(e){e===N.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Zr.STOPPED&&(this.state=Zr.IDLE)},i.afterBufferFlushed=function(e,t,i){if(e){var r=ki.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===Zr.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Zr.STOPPED&&(this.state=Zr.IDLE)},i.resetStartWhenNotLoaded=function(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},i.resetWhenMissingContext=function(e){this.warn("The loading context changed while buffering fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},i.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(e,t,i,r){var s=this,n=i.details;if(n){var a;if(!Object.keys(e.elementaryStreams).reduce((function(t,a){var o=e.elementaryStreams[a];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return s.warn("Could not parse fragment "+e.sn+" "+a+" duration reliably ("+l+")"),t||!1;var h=r?0:wr(n,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return s.hls.trigger(M.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(a=this.transmuxer)?void 0:a.error))){var o=new Error("Found no media in fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+" resetting transmuxer to fallback to playlist timing");if(this.warn(o.message),this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+i.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=Zr.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+")"),this.hls.trigger(M.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},i.playlistLabel=function(){return this.playlistType===N.MAIN?"level":"track"},i.fragInfo=function(e,t,i){var r,s;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(i?"part":"frag")+":["+(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)+"-"+(null!=(s=t&&!i?e.endPTS:(i||e).end)?s:NaN).toFixed(3)+"]"+(i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"")},i.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},i.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},i.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},n(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e,t;return!(!ts(this.hls.config)||!(null==(e=this.hls.interstitialsManager)||null==(t=e.playingItem)?void 0:t.event))}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(Ri);function ts(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var is=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,i=this.dataLength;return t.length?(e=1===t.length?t[0]:rs(t,i),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function rs(e,t){for(var i=new Uint8Array(t),r=0,s=0;s<e.length;s++){var n=e[s];i.set(n,r),r+=n.length}return i}function ss(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function ns(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function as(e,t){var i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3]}function os(e,t){for(var i=t,r=0;ns(e,t);)r+=10,r+=as(e,t+6),ss(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)}function ls(e,t,i,r){var s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=t[i+2],a=n>>2&15;if(!(a>12)){var o=1+(n>>6&3),l=t[i+3]>>6&3|(1&n)<<2,h="mp4a.40."+o,d=s[a],u=a;5!==o&&29!==o||(u-=3);var c=[o<<3|(14&u)>>1,(1&u)<<7|l<<3];return q.log("manifest codec:"+r+", parsed codec:"+h+", channels:"+l+", rate:"+d+" (ADTS object type:"+o+" sampling index:"+a+")"),{config:c,samplerate:d,channelCount:l,codec:h,parsedCodec:h,manifestCodec:r}}var f=new Error("invalid ADTS sampling index:"+a);e.emit(M.ERROR,M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message})}function hs(e,t){return 255===e[t]&&240==(246&e[t+1])}function ds(e,t){return 1&e[t+1]?7:9}function us(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function cs(e,t){return t+5<e.length}function fs(e,t){return t+1<e.length&&hs(e,t)}function gs(e,t){return cs(e,t)&&hs(e,t)&&us(e,t)<=e.length-t}function ms(e,t){if(fs(e,t)){var i=ds(e,t);if(t+i>=e.length)return!1;var r=us(e,t);if(r<=i)return!1;var s=t+r;return s===e.length||fs(e,s)}return!1}function ps(e,t,i,r,s){if(!e.samplerate){var n=ls(t,i,r,s);if(!n)return;l(e,n)}}function vs(e){return 9216e4/e}function ys(e,t){var i=ds(e,t);if(t+i<=e.length){var r=us(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}function Es(e,t,i,r,s){var n,a=r+s*vs(e.samplerate),o=ys(t,i);if(o){var l=o.frameLength,h=o.headerLength,d=h+l,u=Math.max(0,i+d-t.length);u?(n=new Uint8Array(d-h)).set(t.subarray(i+h,t.length),0):n=t.subarray(i+h,i+d);var c={unit:n,pts:a};return u||e.samples.push(c),{sample:c,length:d,missing:u}}var f=t.length-i;return(n=new Uint8Array(f)).set(t.subarray(i,t.length),0),{sample:{unit:n,pts:a},length:f,missing:-1}}function Ts(e,t){return ns(e,t)&&as(e,t+6)+10<=e.length-t}function Ss(e){if(!(e.size<2)){var t=J(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}}function As(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,i=J(e.data.subarray(t),!0);t+=i.length+1;var r=J(e.data.subarray(t));return{key:e.type,info:i,data:r}}var s=J(e.data.subarray(1));return{key:e.type,info:"",data:s}}}function Ls(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,i=J(e.data.subarray(t),!0);t+=i.length+1;var r=J(e.data.subarray(t));return{key:e.type,info:i,data:r}}var s=J(e.data);return{key:e.type,info:"",data:s}}function Rs(e){return btoa(String.fromCharCode.apply(String,e))}function Is(e,t){if(e<0)return-Is(-e,t);var i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){var r=Math.floor(e*i);return(r%2==0?r:r+1)/i}return Math.round(e*i)/i}function bs(e,t){var i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;for(var s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}function Ds(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function ks(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1/0),_s(e,t,i,Uint8Array)}function _s(e,t,i,r){var s=Ps(e),n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);var a=Cs(e)?e.byteOffset:0,o=(a+e.byteLength)/n,l=(a+t)/n,h=Math.floor(Math.max(0,Math.min(l,o)));return new r(s,h,Math.floor(Math.min(h+Math.max(i,0),o))-h)}function Ps(e){return e instanceof ArrayBuffer?e:e.buffer}function Cs(e){return e&&e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&void 0!==e.byteOffset}function ws(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},i=3;if(!(e.size<2))if(e.data[0]===i){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var s=J(ks(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var o,l=J(ks(e.data,3+r,a));return o="--\x3e"===s?J(ks(e.data,4+r+a)):Ds(e.data.subarray(4+r+a)),t.mimeType=s,t.pictureType=n,t.description=l,t.data=o,t}}}else console.log("Ignore frame with unrecognized character encoding")}function xs(e){return"PRIV"===e.type?Ss(e):"W"===e.type[0]?Ls(e):"APIC"===e.type?ws(e):As(e)}function Os(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=as(e,4),r=10;return{type:t,size:i,data:e.subarray(r,r+i)}}var Ms=10,Fs=10;function Ns(e){for(var t=0,i=[];ns(e,t);){var r=as(e,t+6);e[t+5]>>6&1&&(t+=Ms);for(var s=(t+=Ms)+r;t+Fs<s;){var n=Os(e.subarray(t)),a=xs(n);a&&i.push(a),t+=n.size+Ms}ss(e,t)&&(t+=Ms)}return i}function Us(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Bs(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Gs(e){for(var t=Ns(e),i=0;i<t.length;i++){var r=t[i];if(Us(r))return Bs(r)}}var $s=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Ks(e,t){return void 0===e&&(e=""),void 0===t&&(t=9e4),{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Vs=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,i){},t.demux=function(e,t){this.cachedData&&(e=xe(this.cachedData,e),this.cachedData=null);var i,r=os(e,0),s=r?r.length:0,n=this._audioTrack,a=this._id3Track,o=r?Gs(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&P(o))&&(this.basePTS=Hs(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:$s.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){var h=this.appendFrame(n,e,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i=s+=h.length):s=l}else Ts(e,s)?(r=os(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:$s.audioId3,duration:Number.POSITIVE_INFINITY}),i=s+=r.length):s++;if(s===l&&i!==l){var d=e.slice(i);this.cachedData?this.cachedData=xe(this.cachedData,d):this.cachedData=d}}return{audioTrack:n,videoTrack:Ks(),id3Track:a,textTrack:Ks()}},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},t.flush=function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ks(),id3Track:this._id3Track,textTrack:Ks()}},t.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},e}(),Hs=function(e,t,i){return P(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0)},Ys=null,Ws=[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],js=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],qs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Xs=[0,1,1,4];function Qs(e,t,i,r,s){if(!(i+24>t.length)){var n=zs(t,i);if(n&&i+n.frameLength<=t.length){var a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function zs(e,t){var i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ws[14*(3===i?3-r:3===r?3:4)+s-1],h=js[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,u=qs[i][r],c=Xs[r],f=8*u*c,g=Math.floor(u*l/h+a)*c;if(null===Ys){var m=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ys=m?parseInt(m[1]):0}return!!Ys&&Ys<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function Js(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Zs(e,t){return t+1<e.length&&Js(e,t)}function en(e,t){var i=4;return Js(e,t)&&i<=e.length-t}function tn(e,t){if(t+1<e.length&&Js(e,t)){var i=4,r=zs(e,t),s=i;null!=r&&r.frameLength&&(s=r.frameLength);var n=t+s;return n===e.length||Zs(e,n)}return!1}var rn=function(e){function t(t,i){var r;return(r=e.call(this)||this).observer=void 0,r.config=void 0,r.observer=t,r.config=i,r}d(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var i=os(e,0),r=(null==i?void 0:i.length)||0;if(tn(e,r))return!1;for(var s=e.length;r<s;r++)if(ms(e,r))return t.log("ADTS sync word found !"),!0;return!1},i.canParse=function(e,t){return gs(e,t)},i.appendFrame=function(e,t,i){ps(e,this.observer,t,i,e.manifestCodec);var r=Es(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r},t}(Vs),sn=function(e,t){var i=0,r=5;t+=r;for(var s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);r>0;){a[0]=e[t];var o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],t+=1,r-=o}return i},nn=function(e){function t(t){var i;return(i=e.call(this)||this).observer=void 0,i.observer=t,i}d(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},i.canParse=function(e,t){return t+64<e.length},i.appendFrame=function(e,t,i){var r=an(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}},t.probe=function(e){if(!e)return!1;var t=os(e,0);if(!t)return!1;var i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Gs(t)&&sn(e,i)<16},t}(Vs);function an(e,t,i,r,s){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;var n=t[i+4]>>6;if(n>=3)return-1;var a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;var h=t[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));var u=(t[i+6]<<8|t[i+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][h]+u,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=m,e.channelCount=c,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}var on=function(e){function t(){return e.apply(this,arguments)||this}d(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=os(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Gs(t)&&sn(e,i)<=16)return!1;for(var r=e.length;i<r;i++)if(tn(e,i))return q.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(e,t){return en(e,t)},i.appendFrame=function(e,t,i){if(null!==this.basePTS)return Qs(e,t,i,this.basePTS,this.frameIndex)},t}(Vs),ln=/\/emsg[-/]ID3/i,hn=function(){function e(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}var t=e.prototype;return t.resetTimeStamp=function(){},t.resetInitSegment=function(e,t,i,r){var s=this.videoTrack=Ks("video",1),n=this.audioTrack=Ks("audio",1),a=this.txtTrack=Ks("text",1);if(this.id3Track=Ks("id3",1),this.timeOffset=0,null!=e&&e.byteLength){var o=Te(e);if(o.video){var l=o.video,h=l.id,d=l.timescale,u=l.codec,c=l.supplemental;s.id=h,s.timescale=a.timescale=d,s.codec=u,s.supplemental=c}if(o.audio){var f=o.audio,g=f.id,m=f.timescale,p=f.codec;n.id=g,n.timescale=m,n.codec=p}a.id=de.text,s.sampleDuration=0,s.duration=n.duration=r}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return ve(e)},t.demux=function(e,t){this.timeOffset=t;var i=e,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=xe(this.remainderData,e));var n=we(i);this.remainderData=n.remainder,r.samples=n.valid||new Uint8Array}else r.samples=i;var a=this.extractID3Track(r,t);return s.samples=Oe(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(t,this.timeOffset);return i.samples=Oe(e,t),{videoTrack:t,audioTrack:Ks(),id3Track:r,textTrack:Ks()}},t.extractID3Track=function(e,t){var i=this,r=this.id3Track;if(e.samples.length){var s=ye(e.samples,["emsg"]);s&&s.forEach((function(e){var s=Be(e);if(ln.test(s.schemeIdUri)){var n=dn(s,t),a=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=s.payload;r.samples.push({data:o,len:o.byteLength,dts:n,pts:n,type:$s.emsg,duration:a})}else if(i.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=dn(s,t);r.samples.push({data:s.payload,len:s.payload.byteLength,dts:l,pts:l,type:$s.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return r},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},e}();function dn(e,t){return P(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var un=function(){function e(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new vi(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,di.cbc)},t.decryptAacSample=function(e,t,i){var r=this,s=e[t].unit;if(!(s.length<=16)){var n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then((function(n){var a=new Uint8Array(n);s.set(a,16),r.decrypter.isSync()||r.decryptAacSamples(e,t+1,i)}))}},t.decryptAacSamples=function(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,i),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0,s=32;s<e.length-16;s+=160,r+=16)i.set(e.subarray(s,s+16),r);return i},t.getAvcDecryptedUnit=function(e,t){for(var i=new Uint8Array(t),r=0,s=32;s<e.length-16;s+=160,r+=16)e.set(i.subarray(r,r+16),s);return e},t.decryptAvcSample=function(e,t,i,r,s){var n=this,a=Ue(s.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then((function(o){s.data=n.getAvcDecryptedUnit(a,o),n.decrypter.isSync()||n.decryptAvcSamples(e,t,i+1,r)}))},t.decryptAvcSamples=function(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();for(var s=e[t].units;!(i>=s.length);i++){var n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}},e}(),cn=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}},t.getLastNalUnit=function(e){var t,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){var s=r.units;i=s[s.length-1]}return i},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var i=t.samples,r=i.length;if(!r)return void t.dropped++;var s=i[r-1];e.pts=s.pts,e.dts=s.dts}t.samples.push(e)}},t.parseNALu=function(e,t,i){var r,s,n=t.byteLength,a=e.naluState||0,o=a,l=[],h=0,d=-1,u=0;for(-1===a&&(d=0,u=this.getNALuType(t,0),a=0,h=1);h<n;)if(r=t[h++],a)if(1!==a)if(r)if(1===r){if(s=h-a-1,d>=0){var c={data:t.subarray(d,s),type:u};l.push(c)}else{var f=this.getLastNalUnit(e.samples);f&&(o&&h<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),s>0&&(f.data=xe(f.data,t.subarray(0,s)),f.state=0))}h<n?(d=h,u=this.getNALuType(t,h),a=0):a=-1}else a=0;else a=3;else a=r?0:2;else a=r?0:1;if(d>=0&&a>=0){var g={data:t.subarray(d,n),type:u,state:a};l.push(g)}if(0===l.length){var m=this.getLastNalUnit(e.samples);m&&(m.data=xe(m.data,t))}return e.naluState=a,l},e}(),fn=function(){function e(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&q.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},e}(),gn=function(e){function t(){return e.apply(this,arguments)||this}d(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var s,n=this,a=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,h;switch(r.type){case 1:var d=!1;s=!0;var u,c=r.data;if(l&&c.length>4){var f=n.readSliceType(c);2!==f&&4!==f&&7!==f&&9!==f||(d=!0)}d&&null!=(u=o)&&u.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=d;break;case 5:s=!0,null!=(a=o)&&a.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:s=!0,Ne(r.data,1,i.pts,t.samples);break;case 7:var g,m;s=!0,l=!0;var p=r.data,v=n.readSPS(p);if(!e.sps||e.width!==v.width||e.height!==v.height||(null==(g=e.pixelRatio)?void 0:g[0])!==v.pixelRatio[0]||(null==(m=e.pixelRatio)?void 0:m[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[p];for(var y=p.subarray(1,4),E="avc1.",T=0;T<3;T++){var S=y[T].toString(16);S.length<2&&(S="0"+S),E+=S}e.codec=E}break;case 8:s=!0,e.pps=[r.data];break;case 9:s=!0,e.audFound=!0,null!=(h=o)&&h.frame&&(n.pushAccessUnit(o,e),o=null),o||(o=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts));break;case 12:s=!0;break;default:s=!1}o&&s&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},i.getNALuType=function(e,t){return 31&e[t]},i.readSliceType=function(e){var t=new fn(e);return t.readUByte(),t.readUEG(),t.readUEG()},i.skipScalingList=function(e,t){for(var i=8,r=8,s=0;s<e;s++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r},i.readSPS=function(e){var t,i,r,s=new fn(e),n=0,a=0,o=0,l=0,h=s.readUByte.bind(s),d=s.readBits.bind(s),u=s.readUEG.bind(s),c=s.readBoolean.bind(s),f=s.skipBits.bind(s),g=s.skipEG.bind(s),m=s.skipUEG.bind(s),p=this.skipScalingList.bind(this);h();var v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){var y=u();if(3===y&&f(1),m(),m(),f(1),c())for(i=3!==y?8:12,r=0;r<i;r++)c()&&p(r<6?16:64,s)}m();var E=u();if(0===E)u();else if(1===E)for(f(1),g(),g(),t=u(),r=0;r<t;r++)g();m(),f(1);var T=u(),S=u(),A=d(1);0===A&&f(1),f(1),c()&&(n=u(),a=u(),o=u(),l=u());var L=[1,1];if(c()&&c())switch(h()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(T+1)-2*n-2*a),height:(2-A)*(S+1)*16-(A?2:4)*(o+l),pixelRatio:L}},t}(cn),mn=function(e){function t(){for(var t,i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return(t=e.call.apply(e,[this].concat(r))||this).initVPS=null,t}d(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var s,n=this,a=this.parseNALu(e,i.data,r),o=this.VideoSample,h=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,d;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:var u;s=!0,h&&null!=(u=o)&&u.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:s=!0,null!=(a=o)&&a.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:s=!0,Ne(r.data,2,i.pts,t.samples);break;case 32:s=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=l(e.params,n.readVPS(r.data)),n.initVPS=r.data),e.vps=[r.data];break;case 33:if(s=!0,h=!0,void 0===e.vps||e.vps[0]===n.initVPS||void 0===e.sps||n.matchSPS(e.sps[0],r.data)||(n.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var c=n.readSPS(r.data);for(var f in e.width=c.width,e.height=c.height,e.pixelRatio=c.pixelRatio,e.codec=c.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),c.params)e.params[f]=c.params[f]}n.pushParameterSet(e.sps,r.data,e.vps),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(s=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];var g=n.readPPS(r.data);for(var m in g)e.params[m]=g[m]}n.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:s=!0,e.audFound=!0,null!=(d=o)&&d.frame&&(n.pushAccessUnit(o,e),o=null),o||(o=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts));break;default:s=!1}o&&s&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},i.pushParameterSet=function(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)},i.getNALuType=function(e,t){return(126&e[t])>>>1},i.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),i=0,r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)},i.pushAccessUnit=function(t,i){e.prototype.pushAccessUnit.call(this,t,i),this.initVPS&&(this.initVPS=null)},i.readVPS=function(e){var t=new fn(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},i.readSPS=function(e){var t=new fn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var i=t.readBits(3);t.readBoolean();for(var r=t.readBits(2),s=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=[],y=[],E=0;E<i;E++)v.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(var T=i;T<8;T++)t.readBits(2);for(var S=0;S<i;S++)v[S]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[S]&&t.readUByte();t.readUEG();var A=t.readUEG();3==A&&t.skipBits(1);var L=t.readUEG(),R=t.readUEG(),I=t.readBoolean(),b=0,D=0,k=0,_=0;I&&(b+=t.readUEG(),D+=t.readUEG(),k+=t.readUEG(),_+=t.readUEG());for(var P=t.readUEG(),C=t.readUEG(),w=t.readUEG(),x=t.readBoolean()?0:i;x<=i;x++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(var O=0;O<4;O++)for(var M=0;M<(3===O?2:6);M++)if(t.readBoolean()){var F=Math.min(64,1<<4+(O<<1));O>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var U=t.readUEG(),B=0,G=0;G<U;G++){var $=!1;if(0!==G&&($=t.readBoolean()),$){G===U&&t.readUEG(),t.readBoolean(),t.readUEG();for(var K=0,V=0;V<=B;V++){var H=t.readBoolean(),Y=!1;H||(Y=t.readBoolean()),(H||Y)&&K++}B=K}else{var W=t.readUEG(),j=t.readUEG();B=W+j;for(var q=0;q<W;q++)t.readUEG(),t.readBoolean();for(var X=0;X<j;X++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var Q=t.readUEG(),z=0;z<Q;z++){for(var J=0;J<w+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,ie=!0,re=1,se=0;t.readBoolean(),t.readBoolean();var ne=!1;if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),(ne=t.readBoolean())&&(b+=t.readUEG(),D+=t.readUEG(),k+=t.readUEG(),_+=t.readUEG()),t.readBoolean()&&(re=t.readBits(32),se=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var oe=t.readBoolean(),le=t.readBoolean(),he=!1;(oe||le)&&((he=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),he&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var de=0;de<=i;de++){var ue=!1;(ie=t.readBoolean())||t.readBoolean()?t.readEG():ue=t.readBoolean();var ce=ue?1:t.readUEG()+1;if(oe)for(var fe=0;fe<ce;fe++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(le)for(var ge=0;ge<ce;ge++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var me=L,pe=R;if(I||ne){var ve=1,ye=1;1===A?ve=ye=2:2==A&&(ve=2),me=L-ve*D-ve*b,pe=R-ye*_-ye*k}for(var Ee=r?["A","B","C"][r]:"",Te=a<<24|o<<16|l<<8|h,Se=0,Ae=0;Ae<32;Ae++)Se=(Se|(Te>>Ae&1)<<31-Ae)>>>0;var Le=Se.toString(16);return 1===n&&"2"===Le&&(Le="6"),{codecString:"hvc1."+Ee+n+"."+Le+"."+(s?"H":"L")+p+".B0",params:{general_tier_flag:s,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,u,c,f,g,m],general_level_idc:p,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:C,min_spatial_segmentation_idc:Z,chroma_format_idc:A,frame_rate:{fixed:ie,fps:se/re}},width:me,height:pe,pixelRatio:[ee,te]}},i.readPPS=function(e){var t=new fn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var i=t.readBoolean(),r=t.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}},i.matchSPS=function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)},t}(cn),pn=188,vn=function(){function e(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}e.probe=function(t,i){var r=e.syncOffset(t);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=e.length,i=Math.min(5*pn,t-pn)+1,r=0;r<i;){for(var s=!1,n=-1,a=0,o=r;o<t;o+=pn){if(71!==e[o]||t-o!==pn&&71!==e[o+pn]){if(a)return-1;break}if(a++,-1===n&&0!==(n=o)&&(i=Math.min(n+99*pn,e.length-pn)+1),s||(s=0===yn(e,o)),s&&a>1&&(0===n&&a>2||o+pn>i))return n}r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:de[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,i,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=e.createTrack("audio",s),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=r},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,i=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,i,r,s){var n;void 0===r&&(r=!1),void 0===s&&(s=!1),r||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,d=a.pid,u=a.pesData,c=o.pid,f=l.pid,g=o.pesData,m=l.pesData,p=null,v=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=xe(this.remainderData,t)).length,this.remainderData=null),E<pn&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var T=Math.max(0,e.syncOffset(t));(E-=(E-T)%pn)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var S=0,A=T;A<E;A+=pn)if(71===t[A]){var L=!!(64&t[A+1]),R=yn(t,A),I=void 0;if((48&t[A+3])>>4>1){if((I=A+5+t[A+4])===A+pn)continue}else I=A+4;switch(R){case d:if(L){if(u&&(n=Ln(u,this.logger))){if(null===this.videoParser)switch(a.segmentCodec){case"avc":this.videoParser=new gn;break;case"hevc":this.videoParser=new mn}null!==this.videoParser&&this.videoParser.parsePES(a,h,n,!1)}u={data:[],size:0}}u&&(u.data.push(t.subarray(I,A+pn)),u.size+=A+pn-I);break;case c:if(L){if(g&&(n=Ln(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}g={data:[],size:0}}g&&(g.data.push(t.subarray(I,A+pn)),g.size+=A+pn-I);break;case f:L&&(m&&(n=Ln(m,this.logger))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(t.subarray(I,A+pn)),m.size+=A+pn-I);break;case 0:L&&(I+=t[I]+1),y=this._pmtId=En(t,I);break;case y:L&&(I+=t[I]+1);var b=Tn(t,I,this.typeSupported,r,this.observer,this.logger);(d=b.videoPid)>0&&(a.pid=d,a.segmentCodec=b.segmentVideoCodec),(c=b.audioPid)>0&&(o.pid=c,o.segmentCodec=b.segmentAudioCodec),(f=b.id3Pid)>0&&(l.pid=f),null===p||v||(this.logger.warn("MPEG-TS PMT found at "+A+" after unknown PID '"+p+"'. Backtracking to sync byte @"+T+" to parse all TS packets."),p=null,A=T-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=R}}else S++;S>0&&Sn(this.observer,new Error("Found "+S+" TS packet/s that do not start with 0x47"),void 0,this.logger),a.pesData=u,o.pesData=g,l.pesData=m;var D={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(D),D},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,i=e.audioTrack,r=e.videoTrack,s=e.id3Track,n=e.textTrack,a=r.pesData,o=i.pesData,l=s.pesData;if(a&&(t=Ln(a,this.logger))){if(null===this.videoParser)switch(r.segmentCodec){case"avc":this.videoParser=new gn;break;case"hevc":this.videoParser=new mn}null!==this.videoParser&&(this.videoParser.parsePES(r,n,t,!0),r.pesData=null)}else r.pesData=a;if(o&&(t=Ln(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=Ln(l,this.logger))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=l},t.demuxSampleAes=function(e,t,i){var r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new un(this.observer,this.config,t);return this.decrypt(r,s)},t.decrypt=function(e,t){return new Promise((function(i){var r=e.audioTrack,s=e.videoTrack;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(function(){s.samples?t.decryptAvcSamples(s.samples,0,0,(function(){i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(function(){i(e)}))}))},t.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0},t.parseAACPES=function(e,t){var i,r,s,n=0,a=this.aacOverFlow,o=t.data;if(a){this.aacOverFlow=null;var l=a.missing,h=a.sample.unit.byteLength;if(-1===l)o=xe(a.sample.unit,o);else{var d=h-l;a.sample.unit.set(o.subarray(0,l),d),e.samples.push(a.sample),n=a.missing}}for(i=n,r=o.length;i<r-1&&!fs(o,i);i++);if(i!==n){var u,c=i<r-1;if(u=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",Sn(this.observer,new Error(u),c,this.logger),!c)return}if(ps(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=vs(e.samplerate);s=a.sample.pts+f}for(var g,m=0;i<r;){if(i+=(g=Es(e,o,i,s,m)).length,g.missing){this.aacOverFlow=g;break}for(m++;i<r-1&&!fs(o,i);i++);}},t.parseMPEGPES=function(e,t){var i=t.data,r=i.length,s=0,n=0,a=t.pts;if(void 0!==a)for(;n<r;)if(Zs(i,n)){var o=Qs(e,i,n,a,s);if(!o)break;n+=o.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},t.parseAC3PES=function(e,t){var i=t.data,r=t.pts;if(void 0!==r)for(var s,n=i.length,a=0,o=0;o<n&&(s=an(e,i,o,r,a++))>0;)o+=s;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var i=l({},t,{type:this._videoTrack?$s.emsg:$s.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function yn(e,t){return((31&e[t+1])<<8)+e[t+2]}function En(e,t){return(31&e[t+10])<<8|e[t+11]}function Tn(e,t,i,r,s,n){var a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){var l=yn(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){An("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=l);break;case 21:-1===a.id3Pid&&(a.id3Pid=l);break;case 219:if(!r){An("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){An("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&h>0)for(var d=t+5,u=h;u>2;){106===e[d]&&(!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=l,a.segmentAudioCodec="ac3"));var c=e[d+1]+2;d+=c,u-=c}break;case 194:case 135:return Sn(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=l,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=h+5}return a}function Sn(e,t,i,r){r.warn("parsing error: "+t.message),e.emit(M.ERROR,M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function An(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function Ln(e,t){var i,r,s,n,a,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=xe(l[0],l[1]),l.splice(1,1);if(1===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;var h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?n-(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2)>54e5&&(t.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var d=(s=i[8])+9;if(e.size<=d)return null;e.size-=d;for(var u=new Uint8Array(e.size),c=0,f=l.length;c<f;c++){var g=(i=l[c]).byteLength;if(d){if(d>g){d-=g;continue}i=i.subarray(d),g-=d,d=0}u.set(i,o),o+=g}return r&&(r-=s+3),{data:u,pts:n,dts:a,len:r}}return null}var Rn=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)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])}},e}(),In=Math.pow(2,32)-1,bn=function(){function e(){}return e.init=function(){var t;for(t in e.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:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var i=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:i,audio:r};var s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=n,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,l,a,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,s))},e.box=function(e){for(var t=8,i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];for(var n=r.length,a=n;n--;)t+=r[n].byteLength;var o=new Uint8Array(t);for(o[0]=t>>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),n=0,t=8;n<a;n++)o.set(r[n],t),t+=r[n].byteLength;return o},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,i){i*=t;var r=Math.floor(i/(In+1)),s=Math.floor(i%(In+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))},e.moov=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(e.mvex(t)))},e.mvex=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex].concat(r))},e.mvhd=function(t,i){i*=t;var r=Math.floor(i/(In+1)),s=Math.floor(i%(In+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,n)},e.sdtp=function(t){var i,r,s=t.samples||[],n=new Uint8Array(4+s.length);for(i=0;i<s.length;i++)r=s[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,n)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var i,r,s,n=[],a=[];for(i=0;i<t.sps.length;i++)s=(r=t.sps[i]).byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)s=(r=t.pps[i]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(r));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,d=t.pixelRatio[0],u=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))},e.esds=function(e){var t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){var i=t.segmentCodec;if("audio"===t.type){if("aac"===i)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===i&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===i&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===i)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===i&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+i+"/"+t.codec+")")},e.tkhd=function(t){var i=t.id,r=(t.duration||0)*(t.timescale||0),s=t.width||0,n=t.height||0,a=Math.floor(r/(In+1)),o=Math.floor(r%(In+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,n>>8&255,255&n,0,0]))},e.traf=function(t,i){var r=e.sdtp(t),s=t.id,n=Math.floor(i/(In+1)),a=Math.floor(i%(In+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,r.length+16+20+8+16+8+8),r)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,i){var r,s,n,a,o,l,h=t.samples||[],d=h.length,u=12+16*d,c=new Uint8Array(u);for(i+=8+u,c.set(["video"===t.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<d;r++)n=(s=h[r]).duration,a=s.size,o=s.flags,l=s.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var i=e.moov(t);return xe(e.FTYP,i)},e.hvc1=function(t){for(var i=t.params,r=[t.vps,t.sps,t.pps],s=4,n=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),s-1|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),a=n.length,o=0;o<r.length;o+=1){a+=3;for(var l=0;l<r[o].length;l+=1)a+=2+r[o][l].length}var h=new Uint8Array(a);h.set(n,0),a=n.length;for(var d=r.length-1,u=0;u<r.length;u+=1){h.set(new Uint8Array([32+u|(u===d?128:0),0,r[u].length]),a),a+=3;for(var c=0;c<r[u].length;c+=1)h.set(new Uint8Array([r[u][c].length>>8,255&r[u][c].length]),a),a+=2,h.set(r[u][c],a),a+=r[u][c].length}var f=e.box(e.types.hvcC,h),g=t.width,m=t.height,p=t.pixelRatio[0],v=t.pixelRatio[1];return e.box(e.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,g>>8&255,255&g,m>>8&255,255&m,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),f,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,255&p,v>>24,v>>16&255,v>>8&255,255&v])))},e}();bn.types=void 0,bn.HDLR_TYPES=void 0,bn.STTS=void 0,bn.STSC=void 0,bn.STCO=void 0,bn.STSZ=void 0,bn.VMHD=void 0,bn.SMHD=void 0,bn.STSD=void 0,bn.FTYP=void 0,bn.DINF=void 0;var Dn=9e4;function kn(e,t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var s=e*t*i;return r?Math.round(s):s}function _n(e,t,i,r){return void 0===i&&(i=1),void 0===r&&(r=!1),kn(e,t,1/i,r)}function Pn(e,t){return kn(e,1e3,1/Dn,t)}function Cn(e,t){return void 0===t&&(t=1),kn(e,Dn,1/t)}var wn=1e4,xn=1024,On=1152,Mn=1536,Fn=null,Nn=null;function Un(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Bn=function(){function e(e,t,i,r){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.ISGenerated=!1,null===Fn){var s=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fn=s?parseInt(s[1]):0}if(null===Nn){var n=navigator.userAgent.match(/Safari\/(\d+)/i);Nn=n?parseInt(n[1]):0}}var t=e.prototype;return t.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},t.resetTimeStamp=function(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e},t.resetNextTimestamp=function(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},t.resetInitSegment=function(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},t.getVideoStartPts=function(e){var t=!1,i=e[0].pts,r=e.reduce((function(e,r){var s=r.pts,n=s-e;return n<-4294967296&&(t=!0,n=(s=Gn(s,i))-e),n>0?e:s}),i);return t&&this.logger.debug("PTS rollover detected"),r},t.remux=function(e,t,i,r,s,n,a,o){var l,h,d,u,c,f,g=s,m=s,p=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,R,I=this.videoTrackConfig;(I&&(t.width!==I.width||t.height!==I.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(A=I.pixelRatio)?void 0:A[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(R=I.pixelRatio)?void 0:R[1]))||!I&&T||null===this.nextAudioPts&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,s,n));var b,D=this.isVideoContiguous,k=-1;if(T&&(k=$n(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,k>0){this.logger.warn("[mp4-remuxer]: Dropped "+k+" out of "+y+" video samples due to a missing keyframe");var _=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(k),t.dropped+=k,b=m+=(t.samples[0].pts-_)/t.inputTimeScale}else-1===k&&(this.logger.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&T){var P=this.getVideoStartPts(t.samples),C=(Gn(e.samples[0].pts,P)-P)/t.inputTimeScale;g+=Math.max(0,C),m+=Math.max(0,-C)}if(E){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||T||o===N.AUDIO?m:void 0),T){var w=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,m,D,w)}}else T&&(l=this.remuxVideo(t,m,D,0));l&&(l.firstKeyFrame=k,l.independent=-1!==k,l.firstKeyFramePTS=b)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=Kn(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=Vn(r,s,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:u,id3:c}},t.generateIS=function(e,t,i,r){var s,n,a,o=e.samples,l=t.samples,h=this.typeSupported,d={},u=this._initPTS,c=!u||r,f="audio/mp4";if(c&&(s=n=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",e.codec=""):h.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}d.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&h.mpeg?new Uint8Array(0):bn.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(a=e.inputTimeScale,u&&a===u.timescale?c=!1:s=n=o[0].pts-Math.round(a*i))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:bn.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(a=t.inputTimeScale,u&&a===u.timescale)c=!1;else{var g=this.getVideoStartPts(l),m=Math.round(a*i);n=Math.min(n,Gn(l[0].dts,g)-m),s=Math.min(s,g-m)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:s,timescale:a},this._initDTS={baseTime:n,timescale:a}):s=a=void 0,{tracks:d,initPTS:s,timescale:a}},t.remuxVideo=function(e,t,i,r){var s,n,a=e.inputTimeScale,o=e.samples,h=[],d=o.length,u=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||null===c){var y=t*a,E=o[0].pts-Gn(o[0].dts,o[0].pts);Fn&&null!==c&&Math.abs(y-E-c)<15e3?i=!0:c=y-E}for(var T=u.baseTime*a/u.timescale,S=0;S<d;S++){var A=o[S];A.pts=Gn(A.pts-T,c),A.dts=Gn(A.dts-T,c),A.dts<o[S>0?S-1:S].dts&&(v=!0)}v&&o.sort((function(e,t){var i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),s=o[0].dts;var L=(n=o[o.length-1].dts)-s,R=L?Math.round(L/(d-1)):g||e.inputTimeScale/30;if(i){var I=s-c,b=I>R,D=I<-1;if((b||D)&&(b?this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+Pn(I,!0)+" ms ("+I+"dts) hole between fragments detected at "+t.toFixed(3)):this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+Pn(-I,!0)+" ms ("+I+"dts) overlapping between fragments detected at "+t.toFixed(3)),!D||c>=o[0].pts||Fn)){s=c;var k=o[0].pts-I;if(b)o[0].dts=s,o[0].pts=k;else for(var _=!0,P=0;P<o.length&&!(o[P].dts>k&&_);P++){var C=o[P].pts;if(o[P].dts-=I,o[P].pts-=I,P<o.length-1){var w=o[P+1].pts;_=w<=o[P].pts==w<=C}}this.logger.log("Video: Initial PTS/DTS adjusted: "+Pn(k,!0)+"/"+Pn(s,!0)+", delta: "+Pn(I,!0)+" ms")}}for(var F=0,N=0,U=s=Math.max(0,s),B=0;B<d;B++){for(var G=o[B],$=G.units,K=$.length,V=0,H=0;H<K;H++)V+=$[H].data.length;N+=V,F+=K,G.length=V,G.dts<U?(G.dts=U,U+=R/4|0||1):U=G.dts,m=Math.min(G.pts,m),p=Math.max(G.pts,p)}n=o[d-1].dts;var Y,W=N+4*F+8;try{Y=new Uint8Array(W)}catch(e){return void this.observer.emit(M.ERROR,M.ERROR,{type:x.MUX_ERROR,details:O.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:W,reason:"fail allocating video mdat "+W})}var j=new DataView(Y.buffer);j.setUint32(0,W),Y.set(bn.types.mdat,4);for(var q=!1,X=Number.POSITIVE_INFINITY,Q=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY,Z=0;Z<d;Z++){for(var ee=o[Z],te=ee.units,ie=0,re=0,se=te.length;re<se;re++){var ne=te[re],ae=ne.data,oe=ne.data.byteLength;j.setUint32(f,oe),f+=4,Y.set(ae,f),f+=oe,ie+=4+oe}var le=void 0;if(Z<d-1)g=o[Z+1].dts-ee.dts,le=o[Z+1].pts-ee.pts;else{var he=this.config,de=Z>0?ee.dts-o[Z-1].dts:R;if(le=Z>0?ee.pts-o[Z-1].pts:R,he.stretchShortVideoTrack&&null!==this.nextAudioPts){var ue=Math.floor(he.maxBufferHole*a),ce=(r?m+r*a:this.nextAudioPts)-ee.pts;ce>ue?((g=ce-de)<0?g=de:q=!0,this.logger.log("[mp4-remuxer]: It is approximately "+ce/90+" ms to the next segment; using duration "+g/90+" ms for the last video frame.")):g=de}else g=de}var fe=Math.round(ee.pts-ee.dts);X=Math.min(X,g),z=Math.max(z,g),Q=Math.min(Q,le),J=Math.max(J,le),h.push(Un(ee.key,g,ie,fe))}if(h.length)if(Fn){if(Fn<70){var ge=h[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(Nn&&J-Q<z-X&&R/z<.025&&0===h[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var me=s,pe=0,ve=h.length;pe<ve;pe++){var ye=me+h[pe].duration,Ee=me+h[pe].cts;if(pe<ve-1){var Te=ye+h[pe+1].cts;h[pe].duration=Te-Ee}else h[pe].duration=pe?h[pe-1].duration:R;h[pe].cts=0,me=ye}}g=q||!g?R:g,this.nextAvcDts=c=n+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;var Se={data1:bn.moof(e.sequenceNumber++,s,l(e,{samples:h})),data2:Y,startPTS:m/a,endPTS:(p+g)/a,startDTS:s/a,endDTS:c/a,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Se},t.getSamplesPerFrame=function(e){switch(e.segmentCodec){case"mp3":return On;case"ac3":return Mn;default:return xn}},t.remuxAudio=function(e,t,i,r,s){var n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),h=o*a,d=this._initPTS,u="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],f=void 0!==s,g=e.samples,m=u?0:8,p=this.nextAudioPts||-1,v=t*n,y=d.baseTime*n/d.timescale;if(this.isAudioContiguous=i=i||g.length&&p>0&&(r&&Math.abs(v-p)<9e3||Math.abs(Gn(g[0].pts-y,v)-p)<20*h),g.forEach((function(e){e.pts=Gn(e.pts-y,v)})),!i||p<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;p=0===s?0:r&&!f?Math.max(0,v):g[0].pts}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,T=0,S=p;T<g.length;T++){var A=g[T],L=A.pts,R=L-S,I=Math.abs(1e3*R/n);if(R<=-E*h&&f)0===T&&(this.logger.warn("Audio frame @ "+(L/n).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*R/n)+" ms."),this.nextAudioPts=p=S=L);else if(R>=E*h&&I<wn&&f){var b=Math.round(R/h);(S=L-b*h)<0&&(b--,S+=h),0===T&&(this.nextAudioPts=p=S),this.logger.warn("[mp4-remuxer]: Injecting "+b+" audio frame @ "+(S/n).toFixed(3)+"s due to "+Math.round(1e3*R/n)+" ms gap.");for(var D=0;D<b;D++){var k=Math.max(S,0),_=Rn.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);_||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),_=A.unit.subarray()),g.splice(T,0,{unit:_,pts:k}),S+=h,T++}}A.pts=S,S+=h}for(var P,C=null,w=null,F=0,N=g.length;N--;)F+=g[N].unit.byteLength;for(var U=0,B=g.length;U<B;U++){var G=g[U],$=G.unit,K=G.pts;if(null!==w)c[U-1].duration=Math.round((K-w)/a);else{if(i&&"aac"===e.segmentCodec&&(K=p),C=K,!(F>0))return;F+=m;try{P=new Uint8Array(F)}catch(e){return void this.observer.emit(M.ERROR,M.ERROR,{type:x.MUX_ERROR,details:O.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:F,reason:"fail allocating audio mdat "+F})}u||(new DataView(P.buffer).setUint32(0,F),P.set(bn.types.mdat,4))}P.set($,m);var V=$.byteLength;m+=V,c.push(Un(!0,o,V,0)),w=K}var H=c.length;if(H){var Y=c[c.length-1];this.nextAudioPts=p=w+a*Y.duration;var W=u?new Uint8Array(0):bn.moof(e.sequenceNumber++,C/a,l({},e,{samples:c}));e.samples=[];var j=C/n,q=p/n,X={data1:W,data2:P,startPTS:j,endPTS:q,startDTS:j,endDTS:q,type:"audio",hasAudio:!0,hasVideo:!1,nb:H};return this.isAudioContiguous=!0,X}},e}();function Gn(e,t){var i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function $n(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}function Kn(e,t,i,r){var s=e.samples.length;if(s){for(var n=e.inputTimeScale,a=0;a<s;a++){var o=e.samples[a];o.pts=Gn(o.pts-i.baseTime*n/i.timescale,t*n)/n,o.dts=Gn(o.dts-r.baseTime*n/r.timescale,t*n)/n}var l=e.samples;return e.samples=[],{samples:l}}}function Vn(e,t,i){var r=e.samples.length;if(r){for(var s=e.inputTimeScale,n=0;n<r;n++){var a=e.samples[n];a.pts=Gn(a.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort((function(e,t){return e.pts-t.pts}));var o=e.samples;return e.samples=[],{samples:o}}}var Hn,Yn=function(){function e(e,t,i,r){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=r}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this.initPTS=e,this.lastEndTime=null},t.resetNextTimestamp=function(){this.lastEndTime=null},t.resetInitSegment=function(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(be(e,r)),this.emitInitSegment=!0},t.generateInitSegment=function(e){var t=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var r=this.initData=Te(e);r.audio&&(t=jn(r.audio,te.AUDIO)),r.video&&(i=jn(r.video,te.VIDEO));var s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s},t.remux=function(e,t,i,r,s,n){var a,o,l=this.initPTS,h=this.lastEndTime,d={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};P(h)||(h=this.lastEndTime=s||0);var u=t.samples;if(null==u||!u.length)return d;var c={initPTS:void 0,timescale:1},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=_e(u,f),m=ke(f,u),p=null===m?s:m;!n&&l||!Wn(l,p,s,g)&&c.timescale===l.timescale||(c.initPTS=p-s,l&&1===l.timescale&&this.logger.warn("Adjusting initPTS @"+s+" from "+l.baseTime/l.timescale+" to "+c.initPTS),this.initPTS=l={baseTime:c.initPTS,timescale:1});var v=e?p-l.baseTime/l.timescale:h,y=v+g;Ce(f,u,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var E=!!f.audio,T=!!f.video,S="";E&&(S+="audio"),T&&(S+="video");var A={data1:u,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:S,hasAudio:E,hasVideo:T,nb:1,dropped:0};return d.audio="audio"===A.type?A:void 0,d.video="audio"!==A.type?A:void 0,d.initSegment=c,d.id3=Kn(i,s,l,l),r.samples.length&&(d.text=Vn(r,s,l)),d},e}();function Wn(e,t,i,r){if(null===e)return!0;var s=Math.max(r,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>s}function jn(e,t){var i=null==e?void 0:e.codec;return i&&i.length>4?i:t===te.AUDIO?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?tt(i,!1):(q.warn('Unhandled audio codec "'+i+'" in mp4 MAP'),i||"mp4a"):(q.warn('Unhandled video codec "'+i+'" in mp4 MAP'),i||"avc1")}try{Hn=self.performance.now.bind(self.performance)}catch(e){Hn=Date.now}var qn=[{demux:hn,remux:Yn},{demux:vn,remux:Bn},{demux:rn,remux:Bn},{demux:on,remux:Bn}];qn.splice(2,0,{demux:nn,remux:Bn});var Xn=function(){function e(e,t,i,r,s,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=n}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,i,r){var s=this,n=i.transmuxing;n.executeStart=Hn();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var h=r||o,d=h.contiguous,u=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,m=h.initSegmentChange,p=l.audioCodec,v=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,S=Qn(a,t);if(S&&Vi(S.method)){var A=this.getDecrypter(),L=Hi(S.method);if(!A.isSync())return this.asyncResult=!0,this.decryptionPromise=A.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,L).then((function(e){var t=s.push(e,null,i);return s.decryptionPromise=null,t})),this.decryptionPromise;var R=A.softwareDecrypt(a,S.key.buffer,S.iv.buffer,L);if(i.part>-1){var I=A.flush();R=I?I.buffer:I}if(!R)return n.executeEnd=Hn(),zn(i);a=new Uint8Array(R)}var b=this.needsProbing(u,c);if(b){var D=this.configureTransmuxer(a);if(D)return this.logger.warn("[transmuxer] "+D.message),this.observer.emit(M.ERROR,M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),n.executeEnd=Hn(),zn(i)}(u||c||m||b)&&this.resetInitSegment(T,p,v,E,t),(u||m||b)&&this.resetInitialTimestamp(y),d||this.resetContiguity();var k=this.transmux(a,S,g,f,i);this.asyncResult=Jn(k);var _=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,n.executeEnd=Hn(),k},t.flush=function(e){var t=this,i=e.transmuxing;i.executeStart=Hn();var r=this.decrypter,s=this.currentTransmuxState,n=this.decryptionPromise;if(n)return this.asyncResult=!0,n.then((function(){return t.flush(e)}));var a=[],o=s.timeOffset;if(r){var l=r.flush();l&&a.push(this.push(l.buffer,null,e))}var h=this.demuxer,d=this.remuxer;if(!h||!d){i.executeEnd=Hn();var u=[zn(e)];return this.asyncResult?Promise.resolve(u):u}var c=h.flush(o);return Jn(c)?(this.asyncResult=!0,c.then((function(i){return t.flushRemux(a,i,e),a}))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)},t.flushRemux=function(e,t,i){var r=t.audioTrack,s=t.videoTrack,n=t.id3Track,a=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+i.sn+(i.part>-1?" part: "+i.part:"")+" of "+(this.id===N.MAIN?"level":"track")+" "+i.level);var d=this.remuxer.remux(r,s,n,a,h,l,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Hn()},t.resetInitialTimestamp=function(e){var t=this.demuxer,i=this.remuxer;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,i,r,s){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,i,r,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s)},t.transmuxUnencrypted=function(e,t,i,r){var s=this.demuxer.demux(e,t,!1,!this.config.progressive),n=s.audioTrack,a=s.videoTrack,o=s.id3Track,l=s.textTrack;return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:r}},t.transmuxSampleAes=function(e,t,i,r,s){var n=this;return this.demuxer.demuxSampleAes(e,t,i).then((function(e){return{remuxResult:n.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,n.id),chunkMeta:s}}))},t.configureTransmuxer=function(e){for(var t,i=this.config,r=this.observer,s=this.typeSupported,n=0,a=qn.length;n<a;n++){var o;if(null!=(o=qn[n].demux)&&o.probe(e,this.logger)){t=qn[n];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,h=this.remuxer,d=t.remux,u=t.demux;h&&h instanceof d||(this.remuxer=new d(r,i,s,this.logger)),l&&l instanceof u||(this.demuxer=new u(r,i,s,this.logger),this.probe=u.probe)},t.needsProbing=function(e,t){return!this.demuxer||!this.remuxer||e||t},t.getDecrypter=function(){var e=this.decrypter;return e||(e=this.decrypter=new vi(this.config)),e},e}();function Qn(e,t){var i=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t),i}var zn=function(e){return{remuxResult:{},chunkMeta:e}};function Jn(e){return"then"in e&&e.then instanceof Function}var Zn=function(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null},ea=function(e,t,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n},ta=[];function ia(){self.addEventListener("message",(function(e){var t=e.data,i=t.instanceNo;if(void 0!==i){var r=ta[i];if("reset"===t.cmd&&(delete ta[t.resetNo],r&&r.destroy(),t.cmd="init"),"init"===t.cmd){var s=JSON.parse(t.config),n=new b;n.on(M.FRAG_DECRYPTED,aa),n.on(M.ERROR,aa);var a=j(s.debug,t.id);return oa(a,i),ta[i]=new Xn(n,t.typeSupported,s,"",t.id,a),void aa("init",null,i)}if(r)switch(t.cmd){case"configure":r.configure(t.config);break;case"demux":var o=r.push(t.data,t.decryptdata,t.chunkMeta,t.state);Jn(o)?o.then((function(e){ra(self,e,i)})).catch((function(e){aa(M.ERROR,{instanceNo:i,type:x.MEDIA_ERROR,details:O.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},i)})):ra(self,o,i);break;case"flush":var l=t.chunkMeta,h=r.flush(l);Jn(h)?h.then((function(e){na(self,e,l,i)})).catch((function(e){aa(M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},i)})):na(self,h,l,i)}}}))}function ra(e,t,i){if(la(t.remuxResult))return!1;var r=[],s=t.remuxResult,n=s.audio,a=s.video;return n&&sa(r,n),a&&sa(r,a),e.postMessage({event:"transmuxComplete",data:t,instanceNo:i},r),!0}function sa(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function na(e,t,i,r){t.reduce((function(t,i){return ra(e,i,r)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:r}),e.postMessage({event:"flush",data:i,instanceNo:r})}function aa(e,t,i){self.postMessage({event:e,data:t,instanceNo:i})}function oa(e,t){var i=function(i){var r=function(e){aa("workerLog",{logType:i,message:e},t)};e[i]=r};for(var r in e)i(r)}function la(e){return!(e.audio||e.video||e.text||e.id3||e.initSegment)}void 0!==t&&t&&ia();var ha="1.6.2",da={};function ua(){return!0}function ca(){var t=da[ha];if(t)return t.clientCount++,t;var i=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+e.toString()+")(true);"],{type:"text/javascript"}),r=self.URL.createObjectURL(i),s={worker:new self.Worker(r),objectURL:r,clientCount:1};return da[ha]=s,s}function fa(e){var t=da[e];if(t)return t.clientCount++,t;var i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return da[e]=r,r}function ga(e){var t=da[e||ha];if(t&&1==t.clientCount--){var i=t.worker,r=t.objectURL;delete da[e||ha],r&&self.URL.revokeObjectURL(r),i.terminate()}}var ma=0,pa=function(){function e(e,t,i,r){var s=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=ma++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,i=s.hls;if(i&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var r,n=null==(r=s.workerContext)?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=s.frag,t.data.part=s.part,t.data.id=s.id,i.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(s.hls){var t=new Error(e.message+" ("+e.filename+":"+e.lineno+")");s.hls.config.enableWorker=!1,s.hls.logger.warn('Error in "'+s.id+'" Web Worker, fallback to inline'),s.hls.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;var a=function(e,t){(t=t||{}).frag=s.frag||void 0,e===M.ERROR&&(t.parent=s.id,t.part=s.part,s.error=t.error),s.hls.trigger(e,t)};this.observer=new b,this.observer.on(M.FRAG_DECRYPTED,a),this.observer.on(M.ERROR,a);var o=at(n.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var l=this.hls.logger;if(n.workerPath||ua()){try{n.workerPath?(l.log("loading Web Worker "+n.workerPath+' for "'+t+'"'),this.workerContext=fa(n.workerPath)):(l.log('injecting Web Worker for "'+t+'"'),this.workerContext=ca());var h=this.workerContext.worker;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:bt(n)})}catch(i){l.warn('Error setting up "'+t+'" Web Worker, fallback to inline',i),this.terminateWorker(),this.error=null,this.transmuxer=new Xn(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Xn(this.observer,o,n,"",t,e.logger)}var t=e.prototype;return t.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=ma++;var t=this.hls.config,i=at(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:bt(t)})}},t.terminateWorker=function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),ga(this.hls.config.workerPath)}},t.destroy=function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},t.push=function(e,t,i,r,s,n,a,o,l,h){var d,u,c=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,g=this.transmuxer,m=n?n.start:s.start,p=s.decryptdata,v=this.frag,y=!(v&&s.cc===v.cc),E=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,S=this.part?l.part-this.part.index:-1,A=0===T&&l.id>1&&l.id===(null==v?void 0:v.stats.chunkCount),L=!E&&(1===T||0===T&&(1===S||A&&S<=0)),R=self.performance.now();(E||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=R),!n||!S&&L||(n.stats.parsing.start=R);var I=!(v&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=v.initSegment)?void 0:u.url)),b=new ea(y,L,o,E,m,I);if(!L||y||I){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+s.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===N.MAIN?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+m+"\n initSegmentChange: "+I);var D=new Zn(i,r,t,a,h);this.configureTransmuxer(D)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:b},e instanceof ArrayBuffer?[e]:[]);else if(g){var k=g.push(e,p,l,b);Jn(k)?k.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(k)}},t.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:e});else if(r){var s=r.flush(e);Jn(s)?s.then((function(i){t.handleFlushResult(i,e)})).catch((function(i){t.transmuxerError(i,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}},t.transmuxerError=function(e,t,i){this.hls&&(this.error=e,this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))},t.handleFlushResult=function(e,t){var i=this;e.forEach((function(e){i.handleTransmuxComplete(e)})),this.onFlush(t)},t.configureTransmuxer=function(e){var t=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)},t.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}(),va=100,ya=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"audio-stream-controller",N.AUDIO)||this).mainAnchor=null,s.mainFragLoading=null,s.audioOnly=!1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s.registerListeners(),s}d(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},i.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(M.LEVEL_LOADED,this.onLevelLoaded,this),t.on(M.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(M.BUFFER_RESET,this.onBufferReset,this),t.on(M.BUFFER_CREATED,this.onBufferCreated,this),t.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(M.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(M.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(M.FRAG_LOADING,this.onFragLoading,this),t.on(M.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(M.LEVEL_LOADED,this.onLevelLoaded,this),t.off(M.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(M.BUFFER_RESET,this.onBufferReset,this),t.off(M.BUFFER_CREATED,this.onBufferCreated,this),t.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(M.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(M.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(M.FRAG_LOADING,this.onFragLoading,this),t.off(M.FRAG_BUFFERED,this.onFragBuffered,this))},i.onInitPtsFound=function(e,t){var i=t.frag,r=t.id,s=t.initPTS,n=t.timescale;if(r===N.MAIN){var a=i.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:s,timescale:n},this.log("InitPTS for cc: "+a+" found from main: "+s+"/"+n),this.mainAnchor=i,this.state===Zr.WAITING_INIT_PTS){var l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==a)&&(this.nextLoadPosition=this.findSyncFrag(i).start),this.tick()}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(i).start,o.abortRequests(),this.resetLoadingState()):this.state===Zr.IDLE&&this.tick()}},i.findSyncFrag=function(e){var t=this.getLevelDetails(),i=e.cc;return qt(t,i,e)||t&&jt(t.fragments,i)||e},i.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Zr.STOPPED);var i=this.lastCurrentTime;this.stopLoad(),this.setInterval(va),i>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i,this.state=Zr.IDLE):this.state=Zr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.doTick=function(){switch(this.state){case Zr.IDLE:this.doTickIdle();break;case Zr.WAITING_TRACK:var t=this.levels,i=this.trackId,r=null==t?void 0:t[i],s=null==r?void 0:r.details;if(s&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(s))break;this.state=Zr.WAITING_INIT_PTS}break;case Zr.FRAG_LOADING_WAITING_RETRY:var n,a=performance.now(),o=this.retryDate;if(!o||a>=o||null!=(n=this.media)&&n.seeking){var l=this.levels,h=this.trackId;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==l?void 0:l[h])||null),this.state=Zr.IDLE}break;case Zr.WAITING_INIT_PTS:var d=this.waitingData;if(d){var u=d.frag,c=d.part,f=d.cache,g=d.complete,m=this.mainAnchor;if(void 0!==this.initPTS[u.cc]){this.waitingData=null,this.state=Zr.FRAG_LOADING;var p={frag:u,part:c,payload:f.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(p),g&&e.prototype._handleFragmentLoadComplete.call(this,p)}else m&&m.cc!==d.frag.cc&&(this.log("Waiting fragment cc ("+u.cc+") cancelled because video is at cc "+m.cc),this.nextLoadPosition=this.findSyncFrag(m).start,this.clearWaitingFragment())}else this.state=Zr.IDLE}this.onTickEnd()},i.clearWaitingFragment=function(){var e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==Zr.STOPPED&&(this.state=Zr.IDLE))},i.resetLoadingState=function(){this.clearWaitingFragment(),e.prototype.resetLoadingState.call(this)},i.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)},i.doTickIdle=function(){var e,t=this.hls,i=this.levels,r=this.media,s=this.trackId,n=t.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&n.startFragPrefetch)&&null!=i&&i[s]){var a=i[s],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Zr.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,te.AUDIO,N.AUDIO));var h=this.getFwdBufferInfo(l,N.AUDIO);if(null!==h){if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(M.BUFFER_EOS,{type:"audio"}),void(this.state=Zr.ENDED);var d=h.len,u=t.maxBufferLength,c=o.fragments,f=c[0].start,g=this.getLoadPosition(),m=this.flushing?g:h.end;if(this.switchingTrack&&r){var p=g;o.PTSKnown&&p<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(d>=u&&!this.switchingTrack&&m<c[c.length-1].start)){var v=this.getNextFragment(m,o);if(v&&this.isLoopLoading(v,m)&&(v=this.getNextFragmentLoopLoading(v,o,h,N.MAIN,u)),v){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&re(v)&&!v.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===ni.OK&&(this.mainFragLoading=y=null),y&&re(y))){if(v.start>y.end){var E=this.fragmentTracker.getFragAtPos(m,N.MAIN);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(v.start>y.end)return}this.loadFragment(v,a,m)}else this.bufferFlushed=!0}}}},i.onMediaDetaching=function(t,i){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,i)},i.onAudioTracksUpdated=function(e,t){var i=t.audioTracks;this.resetTransmuxer(),this.levels=i.map((function(e){return new St(e)}))},i.onAudioTrackSwitching=function(e,t){var i=!!t.url;this.trackId=t.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Zr.STOPPED&&(this.setInterval(va),this.state=Zr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},i.onLevelLoaded=function(e,t){this.mainDetails=t.details;var i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(M.AUDIO_TRACK_LOADED,i))},i.onAudioTrackLoaded=function(e,t){var i,r=this.levels,s=t.details,n=t.id,a=t.groupId,o=t.track;if(r){var l=this.mainDetails;if(!l||s.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Zr.STOPPED&&(this.state=Zr.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+n+' "'+o.name+'" of "'+a+'" loaded ['+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration);var h=r[n],d=0;if(s.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;var u;h.details&&(d=this.alignPlaylists(s,h.details,null==(u=this.levelLastLoaded)?void 0:u.details)),s.alignedSliding||(Qr(s,l),s.alignedSliding||zr(s,l),d=s.fragmentStart)}h.details=s,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(M.AUDIO_TRACK_UPDATED,{details:s,id:n,groupId:t.groupId}),this.state!==Zr.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=Zr.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+n+' "'+o.name+'" of "'+a+'"')},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,s=e.payload,n=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);var d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new pa(this.hls,N.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){var g=!1,m=r?r.index:-1,p=-1!==m,v=new Ii(i.level,i.sn,i.stats.chunkCount,s.byteLength,m,p);u.push(s,f,d,"",i,r,h.totalduration,g,v,c)}else this.log("Unknown video PTS for cc "+i.cc+", waiting for video PTS before demuxing audio frag "+i.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new is,complete:!1}).cache.push(new Uint8Array(s)),this.state!==Zr.STOPPED&&(this.state=Zr.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},i.onBufferReset=function(){this.mediaBuffer=null},i.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)},i.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===N.MAIN&&re(t.frag)&&(this.mainFragLoading=t,this.state===Zr.IDLE&&this.tick())},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part;if(i.type===N.AUDIO)if(this.fragContextChanged(i))this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if(re(i)){this.fragPrevious=i;var s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(M.AUDIO_TRACK_SWITCHED,g({},s)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==N.MAIN||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},i.onError=function(t,i){var r;if(i.fatal)this.state=Zr.ERROR;else switch(i.details){case O.FRAG_GAP:case O.FRAG_PARSING_ERROR:case O.FRAG_DECRYPT_ERROR:case O.FRAG_LOAD_ERROR:case O.FRAG_LOAD_TIMEOUT:case O.KEY_LOAD_ERROR:case O.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.AUDIO,i);break;case O.AUDIO_TRACK_LOAD_ERROR:case O.AUDIO_TRACK_LOAD_TIMEOUT:case O.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==Zr.WAITING_TRACK||(null==(r=i.context)?void 0:r.type)!==F.AUDIO_TRACK||(this.state=Zr.IDLE);break;case O.BUFFER_ADD_CODEC_ERROR:case O.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.resetLoadingState();break;case O.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case O.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}},i.onBufferFlushing=function(e,t){t.type!==te.VIDEO&&(this.flushing=!0)},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==te.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Zr.ENDED&&(this.state=Zr.IDLE);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,N.AUDIO),this.tick())}},i._handleTransmuxComplete=function(e){var t,i="audio",r=this.hls,s=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var o=a.frag,h=a.part,d=a.level,u=d.details,c=s.audio,f=s.text,g=s.id3,m=s.initSegment;if(!this.fragContextChanged(o)&&u){if(this.state=Zr.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){var p=o.initSegment||o;this._bufferInitSegment(d,m.tracks,p,n),r.trigger(M.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:m.tracks})}if(c){var v=c.startPTS,y=c.endPTS,E=c.startDTS,T=c.endDTS;h&&(h.elementaryStreams[te.AUDIO]={startPTS:v,endPTS:y,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(te.AUDIO,v,y,E,T),this.bufferFragmentData(c,o,h,n)}if(null!=g&&null!=(t=g.samples)&&t.length){var S=l({id:i,frag:o,details:u},g);r.trigger(M.FRAG_PARSING_METADATA,S)}if(f){var A=l({id:i,frag:o,details:u},f);r.trigger(M.FRAG_PARSING_USERDATA,A)}}else this.fragmentTracker.removeFragment(o)}else this.resetWhenMissingContext(n)},i._bufferInitSegment=function(e,t,i,r){if(this.state===Zr.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var s=t.audio;s.id=N.AUDIO;var n=e.audioCodec;this.log("Init audio buffer, container:"+s.container+", codecs[level/parsed]=["+n+"/"+s.codec+"]"),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(M.BUFFER_CODECS,t);var a=s.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(M.BUFFER_APPENDING,o)}this.tickImmediate()}},i.loadFragment=function(t,i,r){var s,n=this.fragmentTracker.getState(t);if(this.switchingTrack||n===ni.NOT_LOADED||n===ni.PARTIAL)if(re(t))if(null!=(s=i.details)&&s.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=Zr.WAITING_INIT_PTS;var a=this.mainDetails;a&&a.fragmentStart!==i.details.fragmentStart&&zr(i.details,a)}else e.prototype.loadFragment.call(this,t,i,r);else this._loadInitSegment(t,i);else this.clearTrackerIfNeeded(t)},i.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;xt({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.channels},t,Ft)||(Bt(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},i.completeAudioSwitch=function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(M.AUDIO_TRACK_SWITCHED,g({},e))},t}(es),Ea=function(e){function t(t,i){var r;return(r=e.call(this,i,t.logger)||this).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=t,r}d(t,e);var i=t.prototype;return i.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},i.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},i.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},i.stopLoad=function(){this.canLoad=!1,this.clearTimer()},i.switchParams=function(e,t,i){var r=null==t?void 0:t.renditionReports;if(r){for(var s=-1,n=0;n<r.length;n++){var a=r[n],o=void 0;try{o=new self.URL(a.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: "+e),o=a.URI||""}if(o===e){s=n;break}o===e.substring(0,o.length)&&(s=n)}if(-1!==s){var l=r[s],h=parseInt(l["LAST-MSN"])||(null==t?void 0:t.lastPartSn),d=parseInt(l["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){var u=Math.min(t.age-t.partTarget,t.targetduration);d>=0&&u>t.partTarget&&(d+=1)}var c=i&&Et(i);return new Tt(h,d>=0?d:void 0,c)}}},i.loadPlaylist=function(e){this.clearTimer()},i.loadingPlaylist=function(e,t){this.clearTimer()},i.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},i.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},i.playlistLoaded=function(e,t,i){var r=t.details,s=t.stats,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;r.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach((function(e){e.start=e.playlistOffset+l}))}if(r.live||null!=i&&i.live){var h="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){xr(i,r);var d=r.playlistParsingError;if(d){this.warn(d);var u=this.hls;if(!u.config.ignorePlaylistParsingErrors){var c,f=t.networkDetails;return void u.trigger(M.ERROR,{type:x.NETWORK_ERROR,details:O.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:d,reason:d.message,level:t.level||void 0,parent:null==(c=r.fragments[0])?void 0:c.type,networkDetails:f,stats:s})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);var g,m=this.hls.mainForwardBufferInfo,p=m?m.end-m.len:0,v=Gr(r,1e3*(r.edge-p));if(r.requestScheduled+v<n?r.requestScheduled=n:r.requestScheduled+=v,this.log("live playlist "+e+" "+(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var T=this.hls.config.lowLatencyMode,S=r.lastPartSn,A=r.endSN,L=r.lastPartIndex,R=S===A;-1!==L?R?(y=A+1,E=T?0:L):(y=S,E=T?L+1:r.maxPartIndex):y=A+1;var I=r.age,b=I+r.ageHeader,D=Math.min(b-r.partTarget,1.5*r.targetduration);if(D>0){if(b>3*r.targetduration)this.log("Playlist last advanced "+I.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=i&&i.tuneInGoal&&b-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+i.tuneInGoal+" to: "+D+" with playlist age: "+r.age),D=0;else{var k=Math.floor(D/r.targetduration);y+=k,void 0!==E&&(E+=Math.round(D%r.targetduration/r.partTarget)),this.log("CDN Tune-in age: "+r.ageHeader+"s last advanced "+I.toFixed(2)+"s goal: "+D+" skip sn "+k+" to part "+E)}r.tuneInGoal=D}if(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E),T||!R)return r.requestScheduled=n,void this.loadingPlaylist(h,g)}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E));g&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(v-2*a,v/2)),this.scheduleLoading(h,g,r)}else this.clearTimer()},i.scheduleLoading=function(e,t,i){var r=this,s=i||e.details;if(s){var n=self.performance.now(),a=s.requestScheduled;if(n>=a)this.loadingPlaylist(e,t);else{var o=a-n;this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return r.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},i.getDeliveryDirectives=function(e,t,i,r){var s=Et(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=yt.No),new Tt(i,r,s)},i.checkRetry=function(e){var t=this,i=e.details,r=Xt(e),s=e.errorAction,n=s||{},a=n.action,o=n.retryCount,l=void 0===o?0:o,h=n.retryConfig,d=!!s&&!!h&&(a===ti.RetryRequest||!s.resolved&&a===ti.SendAlternateToPenaltyBox);if(d){var u;if(l>=h.maxNumRetry)return!1;if(r&&null!=(u=e.context)&&u.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" without delivery-directives'),this.loadPlaylist();else{var c=zt(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" in '+c+"ms")}e.levelRetry=!0,s.resolved=!0}return d},t}(G);function Ta(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!Sa(e[i].attrs,t[i].attrs))return!1;return!0}function Sa(e,t,i){var r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(i){return e[i]!==t[i]}))}function Aa(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var La=function(e){function t(t){var i;return(i=e.call(this,t,"audio-track-controller")||this).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.registerListeners(),i}d(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.LEVEL_LOADING,this.onLevelLoading,this),e.on(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(M.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.LEVEL_LOADING,this.onLevelLoading,this),e.off(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(M.ERROR,this.onError,this)},i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,e.prototype.destroy.call(this)},i.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.audioTracks||[]},i.onAudioTrackLoaded=function(e,t){var i=t.id,r=t.groupId,s=t.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=t.details,this.log("Audio track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Audio track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(e,t){e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.audioPreference;if(!s&&a){var o=wt(a,n,Ft);if(o>-1)s=n[o];else{var l=wt(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var d={audioTracks:n};this.log("Updating audio tracks, "+n.length+" track(s) found in group(s): "+(null==i?void 0:i.join(","))),this.hls.trigger(M.AUDIO_TRACKS_UPDATED,d);var u=this.trackId;if(-1!==h&&-1===u)this.setAudioTrack(h);else if(n.length&&-1===u){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+n.length);this.warn(f.message),this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==F.AUDIO_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&xt(e,r,Ft))return r;var s=wt(e,this.tracksInGroup,Ft);if(s>-1){var n=this.tracksInGroup[s];return this.setAudioTrack(s),n}if(r){var a=t.loadLevel;-1===a&&(a=t.firstAutoLevel);var o=Nt(e,t.levels,i,a,Ft);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=wt(e,i);if(l>-1)return i[l]}}}return null},i.setAudioTrack=function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(!(e===this.trackId&&r===i&&s||(this.log("Switching to audio-track "+e+' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId+" channels:"+r.channels),this.trackId=e,this.currentTrack=r,this.hls.trigger(M.AUDIO_TRACK_SWITCHING,g({},r)),s))){var n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=0;i<t.length;i++){var r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||xt(e,r,Ft)))return i}if(e){for(var s=e.name,n=e.lang,a=e.assocLang,o=e.characteristics,l=e.audioCodec,h=e.channels,d=0;d<t.length;d++)if(xt({name:s,lang:n,assocLang:a,characteristics:o,audioCodec:l,channels:h},t[d],Ft))return d;for(var u=0;u<t.length;u++){var c=t[u];if(Sa(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return u}for(var f=0;f<t.length;f++){var g=t[f];if(Sa(e.attrs,g.attrs,["LANGUAGE"]))return f}}return-1},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var i=this.currentTrack;this.shouldLoadPlaylist(i)&&Bt(i.url,this.hls)&&this.scheduleLoading(i,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading audio-track "+r+' "'+t.name+'" lang:'+t.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type?" "+a.type||0:""):"")+" "+n),this.hls.trigger(M.AUDIO_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:t})},n(t,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}}])}(Ea),Ra=function(){function e(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}var t=e.prototype;return t.destroy=function(){this.tracks=this.queues=null},t.append=function(e,t,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(r,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(i){if(t.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(r)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))},t.unblockAudio=function(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")},t.executeNext=function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var i=t[0];try{i.execute()}catch(t){var r;if(i.onError(t),null===this.queues||null===this.tracks)return;var s=null==(r=this.tracks[e])?void 0:r.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(e)}}}},t.shiftAndExecuteNext=function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))},t.current=function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null},t.toString=function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?"SourceBuffer"+(r.updating?" updating":"")+(i.ended?" ended":"")+(i.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),Ia=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ba="HlsJsTrackRemovedError",Da=function(e){function t(t){var i;return(i=e.call(this,t)||this).name=ba,i}return d(t,e),t}(E(Error)),ka=function(e){function t(t,i){var r;return(r=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(e){var t;r.hls&&"open"===(null==(t=r.mediaSource)?void 0:t.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(e){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(e){var t=r,i=t.media,s=t.mediaSource;e&&r.log("Media source opened"),i&&s&&(s.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(M.MEDIA_ATTACHED,{media:i,mediaSource:s}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var e=r,t=e.mediaSrc,i=e._objectUrl;t!==i&&r.error("Media element src was set while attaching MediaSource ("+i+" > "+t+")")},r.hls=t,r.fragmentTracker=i,r.appendSource=Q(X(t.config.preferManagedMediaSource)),r.initTracks(),r.registerListeners(),r}d(t,e);var i=t.prototype;return i.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},i.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null},i.registerListeners=function(){var e=this.hls;e.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.BUFFER_RESET,this.onBufferReset,this),e.on(M.BUFFER_APPENDING,this.onBufferAppending,this),e.on(M.BUFFER_CODECS,this.onBufferCodecs,this),e.on(M.BUFFER_EOS,this.onBufferEos,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.FRAG_PARSED,this.onFragParsed,this),e.on(M.FRAG_CHANGED,this.onFragChanged,this),e.on(M.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.BUFFER_RESET,this.onBufferReset,this),e.off(M.BUFFER_APPENDING,this.onBufferAppending,this),e.off(M.BUFFER_CODECS,this.onBufferCodecs,this),e.off(M.BUFFER_EOS,this.onBufferEos,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.FRAG_PARSED,this.onFragParsed,this),e.off(M.FRAG_CHANGED,this.onFragChanged,this),e.off(M.ERROR,this.onError,this)},i.transferMedia=function(){var e=this,t=this.media,i=this.mediaSource;if(!t)return null;var r={};if(this.operationQueue){var s=this.isUpdating();s||this.operationQueue.removeBlockers();var n=this.isQueued();(s||n)&&this.warn("Transfering MediaSource with"+(n?" operations in queue":"")+(s?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===i?l(r,a.tracks):this.sourceBuffers.forEach((function(t){var i=t[0];i&&(r[i]=l({},e.tracks[i]),e.removeBuffer(i)),t[0]=t[1]=null})),{media:t,mediaSource:i,tracks:r}},i.initTracks=function(){var e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},i.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},i.onManifestParsed=function(e,t){var i,r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(r+" bufferCodec event(s) expected."),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()},i.onMediaAttaching=function(e,t){var i=this.media=t.media,r=X(this.appendSource);if(this.transferData=this.overrides=void 0,i&&r){var s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var n=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(n),s)this._objectUrl=i.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&n instanceof o,_a(i),Pa(i,a),i.load()}catch(e){i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}},i.assignMediaSource=function(e){var t,i;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(i=e.constructor)?void 0:i.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))},i.attachTransferred=function(){var e=this,t=this.media,i=this.transferData;if(i&&t){var r=this.tracks,s=i.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()};if(s&&n&&a){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+bt(r,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+bt(s,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!z(s,r)){i.mediaSource=null,i.tracks=void 0;var l=t.currentTime,h=this.details,d=Math.max(l,(null==h?void 0:h.fragments[0].start)||0);return d-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+d):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(s)+'"->"'+Object.keys(r)+'") start time: '+d+" currentTime: "+l),this.onMediaDetaching(M.MEDIA_DETACHING,{}),this.onMediaAttaching(M.MEDIA_ATTACHING,i),void(t.currentTime=d))}this.transferData=void 0,n.forEach((function(t){var i=t,r=s[i];if(r){var n=r.buffer;if(n){var a=e.fragmentTracker,o=r.id;if(a.hasFragments(o)||a.hasParts(o)){var l=ki.getBuffered(n);a.detectEvictedFragments(i,l,o,null,!0)}var h=Ca(i),d=[i,n];e.sourceBuffers[h]=d,n.updating&&e.operationQueue&&e.operationQueue.prependBlocker(i),e.trackSourceBuffer(i,r)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},i.onMediaDetaching=function(e,t){var i=this,r=!!t.transferMedia;this.transferData=this.overrides=void 0;var s=this.media,n=this.mediaSource,a=this._objectUrl;if(n){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===n.readyState;try{for(var l=n.sourceBuffers,h=l.length;h--;)o&&l[h].abort(),n.removeSourceBuffer(l[h]);o&&n.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&_a(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(M.MEDIA_DETACHED,t)},i.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];i&&e.resetBuffer(i)})),this.initTracks()},i.resetBuffer=function(e){var t,i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},i.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[Ca(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},i.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Ra(this.tracks)},i.onBufferCodecs=function(e,t){var i=this,r=this.tracks,s=Object.keys(t);this.log('BUFFER_CODECS: "'+s+'" (current SB count '+this.sourceBufferCount+")");var n="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&s.some((function(e){return!r[e]}));n||a?this.warn('Unsupported transition between "'+Object.keys(r)+'" and "'+s+'" SourceBuffers'):(s.forEach((function(e){var s,n,a,o=t[e],l=o.id,h=o.codec,d=o.levelCodec,u=o.container,c=o.metadata,f=o.supplemental,g=r[e],m=null==(s=i.transferData)||null==(n=s.tracks)?void 0:n[e],p=null!=m&&m.buffer?m:g,v=(null==p?void 0:p.pendingCodec)||(null==p?void 0:p.codec),y=null==p?void 0:p.levelCodec;g||(g=r[e]={buffer:void 0,listeners:[],codec:h,supplemental:f,container:u,levelCodec:d,metadata:c,id:l});var E=rt(v,y),T=null==E?void 0:E.replace(Ia,"$1"),S=rt(h,d),A=null==(a=S)?void 0:a.replace(Ia,"$1");S&&E&&T!==A&&("audio"===e.slice(0,5)&&(S=tt(S,i.appendSource)),i.log("switching codec "+v+" to "+S),S!==(g.pendingCodec||g.codec)&&(g.pendingCodec=S),g.container=u,i.appendChangeType(e,u,S))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())},i.appendChangeType=function(e,t,i){var r=this,s=t+";codecs="+i,n={label:"change-type="+s,execute:function(){var n=r.tracks[e];if(n){var a=n.buffer;null!=a&&a.changeType&&(r.log("changing "+e+" sourceBuffer type to "+s),a.changeType(s),n.codec=i,n.container=t)}r.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(n,e,this.isPending(this.tracks[e]))},i.blockAudio=function(e){var t,i=this,r=e.start,s=r+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(r,N.MAIN))?void 0:t.gap)){var n={label:"block-audio",execute:function(){var e,t=i.tracks.video;(i.lastVideoAppendEnd>s||null!=t&&t.buffer&&ki.isBuffered(t.buffer,s)||!0===(null==(e=i.fragmentTracker.getAppendedFrag(s,N.MAIN))?void 0:e.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){i.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}},i.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},i.onBufferAppending=function(e,t){var i=this,r=this.tracks,s=t.data,n=t.type,a=t.parent,o=t.frag,l=t.part,h=t.chunkMeta,d=h.buffering[n],u=o.sn,c=self.performance.now();d.start=c;var f=o.stats.buffering,g=l?l.stats.buffering:null;0===f.start&&(f.start=c),g&&0===g.start&&(g.start=c);var m=r.audio,p=!1;"audio"===n&&"audio/mpeg"===(null==m?void 0:m.container)&&(p=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var v=this.tracks.video,y=null==v?void 0:v.buffer;if(y&&"initSegment"!==u){var E=l||o,T=this.blockedAudioAppend;if("audio"!==n||"main"===a||this.blockedAudioAppend){if("video"===n){var S=E.end;if(T){var A=T.frag.start;(S>A||S<this.lastVideoAppendEnd||ki.isBuffered(y,A))&&this.unblockAudio()}this.lastVideoAppendEnd=S}}else{var L=E.start+.05*E.duration,R=y.buffered,I=this.currentOp("video");R.length||I?!I&&!ki.isBuffered(y,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(E):this.blockAudio(E)}}var b=(l||o).start,D={label:"append-"+n,execute:function(){if(d.executeStart=self.performance.now(),p){var e=i.tracks[n];if(e){var t=e.buffer;if(t){var r=b-t.timestampOffset;Math.abs(r)>=.1&&(i.log("Updating audio SourceBuffer timestampOffset to "+b+" (delta: "+r+") sn: "+u+")"),t.timestampOffset=b)}}}i.appendExecutor(s,n)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===f.first&&(f.first=e),g&&0===g.first&&(g.first=e);var t={};i.sourceBuffers.forEach((function(e){var i=e[0],r=e[1];i&&(t[i]=ki.getBuffered(r))})),i.appendErrors[n]=0,"audio"===n||"video"===n?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(M.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:t})},onError:function(e){var t,r={type:x.MEDIA_ERROR,parent:o.type,details:O.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1},s=null==(t=i.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)r.details=O.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!s)r.errorAction=si(!0);else if(e.name===ba&&0===i.sourceBufferCount)r.errorAction=si(!0);else{var a=++i.appendErrors[n];i.warn("Failed "+a+"/"+i.hls.config.appendErrorMaxRetry+' times to append segment in "'+n+'" sourceBuffer ('+(s||"no media error")+")"),(a>=i.hls.config.appendErrorMaxRetry||s)&&(r.fatal=!0)}i.hls.trigger(M.ERROR,r)}};this.append(D,n,this.isPending(this.tracks[n]))},i.getFlushOp=function(e,t,i){var r=this;return this.log('queuing "'+e+'" remove '+t+"-"+i),{label:"remove",execute:function(){r.removeExecutor(e,t,i)},onStart:function(){},onComplete:function(){r.hls.trigger(M.BUFFER_FLUSHED,{type:e})},onError:function(s){r.warn("Failed to remove "+t+"-"+i+' from "'+e+'" SourceBuffer',s)}}},i.onBufferFlushing=function(e,t){var i=this,r=t.type,s=t.startOffset,n=t.endOffset;r?this.append(this.getFlushOp(r,s,n),r):this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.append(i.getFlushOp(t,s,n),t)}))},i.onFragParsed=function(e,t){var i=this,r=t.frag,s=t.part,n=[],a=s?s.elementaryStreams:r.elementaryStreams;a[te.AUDIOVIDEO]?n.push("audiovideo"):(a[te.AUDIO]&&n.push("audio"),a[te.VIDEO]&&n.push("video"));var o=function(){var e=self.performance.now();r.stats.buffering.end=e,s&&(s.stats.buffering.end=e);var t=s?s.stats:r.stats;i.hls.trigger(M.FRAG_BUFFERED,{frag:r,part:s,stats:t,id:r.type})};0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+r.type+" level: "+r.level+" sn: "+r.sn),this.blockBuffers(o,n).catch((function(e){i.warn("Fragment buffered callback "+e),i.stepOperationQueue(i.sourceBufferTypes)}))},i.onFragChanged=function(e,t){this.trimBuffers()},i.onBufferEos=function(e,t){var i,r=this;this.sourceBuffers.forEach((function(e){var i=e[0];if(i){var s=r.tracks[i];t.type&&t.type!==i||(s.ending=!0,s.ended||(s.ended=!0,r.log(i+" buffer reached EOS")))}}));var s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,i=e[0];return i&&!(null!=(t=r.tracks[i])&&t.ended)}))&&(s?(this.log("Queueing EOS"),this.blockUntilOpen((function(){r.tracksEnded();var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream(),r.hls.trigger(M.BUFFERED_TO_END,void 0)):e&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(M.BUFFERED_TO_END,void 0)))},i.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];if(null!==i){var r=e.tracks[i];r&&(r.ending=!1)}}))},i.onLevelUpdated=function(e,t){var i=t.details;i.fragments.length&&(this.details=i,this.updateDuration())},i.updateDuration=function(){var e=this,t=this.getDurationAndRange();t&&this.blockUntilOpen((function(){return e.updateMediaSource(t)}))},i.onError=function(e,t){if(t.details===O.BUFFER_APPEND_ERROR&&t.frag){var i,r=null==(i=t.errorAction)?void 0:i.nextAutoLevel;P(r)&&r!==t.frag.level&&this.resetAppendErrors()}},i.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},i.trimBuffers=function(){var e=this.hls,t=this.details,i=this.media;if(i&&null!==t&&this.sourceBufferCount){var r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(P(a)&&a>=0){var o=Math.max(a,n),l=Math.floor(s/n)*n-o;this.flushBackBuffer(s,n,l)}if(P(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){var h=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),d=Math.max(h,n),u=Math.floor(s/n)*n+d;this.flushFrontBuffer(s,n,u)}}},i.flushBackBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(e){var t=e[0],s=e[1];if(s){var n=ki.getBuffered(s);if(n.length>0&&i>n.start(0)){var a;r.hls.trigger(M.BACK_BUFFER_REACHED,{bufferEnd:i});var o=r.tracks[t];if(null!=(a=r.details)&&a.live)r.hls.trigger(M.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=o&&o.ended)return void r.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");r.hls.trigger(M.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}}))},i.flushFrontBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(t){var s=t[0],n=t[1];if(n){var a=ki.getBuffered(n),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(i>l||e>=l&&e<=h)return;r.hls.trigger(M.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}}))},i.getDurationAndRange=function(){var e,t=this.details,i=this.mediaSource;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){var s=Math.max(0,t.fragmentStart);return{duration:1/0,start:s,end:Math.max(s,r)}}return{duration:1/0}}var n=null==(e=this.overrides)?void 0:e.duration;if(n)return P(n)?{duration:n}:null;var a=this.media.duration;return r>(P(i.duration)?i.duration:0)&&r>a||!P(a)?{duration:r}:null},i.updateMediaSource=function(e){var t=e.duration,i=e.start,r=e.end,s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(P(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),s.duration=t),void 0!==i&&void 0!==r&&(this.log("MediaSource duration is set to "+s.duration+". Setting seekable range to "+i+"-"+r+"."),s.setLiveSeekableRange(i,r)))},i.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,i=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+bt(i)),this.tracksReady){var r,s=null==(r=this.transferData)?void 0:r.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}},i.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(i){var r=i[0],s=i[1];if(r){var n=e.tracks[r];t[r]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}})),this.hls.trigger(M.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var i=t[0];e.executeNext(i)}))}else{var i=new Error("could not create source buffer for media codec(s)");this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:i,reason:i.message})}},i.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in e){var s=r,n=e[s];if(this.isPending(n)){var a=this.getTrackCodec(n,s),o=n.container+";codecs="+a;n.codec=a,this.log("creating sourceBuffer("+o+")"+(this.currentOp(s)?" Queued":"")+" "+bt(n));try{var l=i.addSourceBuffer(o),h=Ca(s),d=[s,l];t[h]=d,n.buffer=l}catch(e){var u;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(s),null==(u=this.operationQueue)||u.removeBlockers(),delete this.tracks[s],void this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:o,parent:n.id})}this.trackSourceBuffer(s,n)}}this.bufferCreated()},i.getTrackCodec=function(e,t){var i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&je(i,"video")&&(r=it(r,i));var s=rt(r,e.levelCodec);return s?"audio"===t.slice(0,5)?tt(s,this.appendSource):s:""},i.trackSourceBuffer=function(e,t){var i=this,r=t.buffer;if(r){var s=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(function(e,t){var r=t.removedRanges;null!=r&&r.length&&i.hls.trigger(M.BUFFER_FLUSHED,{type:e})}))}},i.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},i.onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)},i.onSBUpdateError=function(e,t){var i,r=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(i=this.mediaSource)?void 0:i.readyState));this.error(""+r,t),this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});var s=this.currentOp(e);s&&s.onError(r)},i.removeExecutor=function(e,t,i){var r=this.media,s=this.mediaSource,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!r||!s||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=P(r.duration)?r.duration:1/0,l=P(s.duration)?s.duration:1/0,h=Math.max(0,t),d=Math.min(i,o,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log("Removing ["+h+","+d+"] from the "+e+" SourceBuffer"),a.remove(h,d)):this.shiftAndExecuteNext(e)},i.appendExecutor=function(e,t){var i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new Da("Attempting to append to the "+t+" SourceBuffer, but it does not exist");i.ending=!1,i.ended=!1,r.appendBuffer(e)},i.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},i.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],i=e[1];return t&&i.updating}))},i.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var i=t[0];return i&&!!e.currentOp(i)}))},i.isPending=function(e){return!!e&&!e.buffer},i.blockBuffers=function(e,t){var i=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var r=this.operationQueue,s=t.map((function(e){return i.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((function(t){r===i.operationQueue&&(e(),i.stepOperationQueue(i.sourceBufferTypes))}))},i.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var i,r=null==(i=t.tracks[e])?void 0:i.buffer;r&&!r.updating&&t.shiftAndExecuteNext(e)}))},i.append=function(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)},i.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},i.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},i.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},i.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},i.addBufferListener=function(e,t,i){var r=this.tracks[e];if(r){var s=r.buffer;if(s){var n=i.bind(this,e);r.listeners.push({event:t,listener:n}),s.addEventListener(t,n)}}},i.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var i=t.buffer;i&&(t.listeners.forEach((function(e){i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},n(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){var r=e.tracks[i];return t[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var i,r,s=t[0];return s&&(!(null!=(i=e.tracks[s])&&i.ended)||(null==(r=e.tracks[s])?void 0:r.ending))}))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var e,t,i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){return t+(e.isPending(e.tracks[i])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(G);function _a(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function Pa(e,t){var i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}function Ca(e){return"audio"===e?1:0}var wa,xa=function(){function e(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},t.registerListeners=function(){var e=this.hls;e.on(M.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(M.BUFFER_CODECS,this.onBufferCodecs,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListener=function(){var e=this.hls;e.off(M.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(M.BUFFER_CODECS,this.onBufferCodecs,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this)},t.onFpsDropLevelCapping=function(e,t){var i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})},t.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},t.onManifestParsed=function(e,t){var i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&P(this.autoLevelCapping)&&this.detectPlayerSize()},t.onBufferCodecs=function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+i+": "+e[i].height+"p@"+e[i].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var i=this,r=this.hls.levels;if(!r.length)return-1;var s=r.filter((function(e,r){return i.isLevelAllowed(e)&&r<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,i){if(null==e||!e.length)return-1;for(var r=function(e,t){return!t||e.width!==t.width||e.height!==t.height},s=e.length-1,n=Math.max(t,i),a=0;a<e.length;a+=1){var o=e[a];if((o.width>=n||o.height>=n)&&r(o,e[a+1])){s=a;break}}return s},n(e,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}}])}(),Oa={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Ma={HLS:"h"},Fa={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},Na=((wa={})[Fa.OBJECT]=["br","d","ot","tb"],wa[Fa.REQUEST]=["bl","dl","mtp","nor","nrr","su"],wa[Fa.SESSION]=["cid","pr","sf","sid","st","v"],wa[Fa.STATUS]=["bs","rtp"],wa),Ua=function e(t,i){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=i},Ba="Dict";function Ga(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}function $a(e,t,i,r){return new Error("failed to "+e+' "'+Ga(t)+'" as '+i,{cause:r})}function Ka(e,t,i){return $a("serialize",e,t,i)}var Va=function(e){this.description=e},Ha="Bare Item",Ya="Boolean";function Wa(e){if("boolean"!=typeof e)throw Ka(e,Ya);return e?"?1":"?0"}var ja="Byte Sequence";function qa(e){if(!1===ArrayBuffer.isView(e))throw Ka(e,ja);return":"+Rs(e)+":"}var Xa="Integer";function Qa(e){return e<-999999999999999||999999999999999<e}function za(e){if(Qa(e))throw Ka(e,Xa);return e.toString()}function Ja(e){return"@"+za(e.getTime()/1e3)}var Za="Decimal";function eo(e){var t=Is(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ka(e,Za);var i=t.toString();return i.includes(".")?i:i+".0"}var to="String",io=/[\x00-\x1f\x7f]+/;function ro(e){if(io.test(e))throw Ka(e,to);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function so(e){return e.description||e.toString().slice(7,-1)}var no="Token";function ao(e){var t=so(e);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Ka(t,no);return t}function oo(e){switch(typeof e){case"number":if(!P(e))throw Ka(e,Ha);return Number.isInteger(e)?za(e):eo(e);case"string":return ro(e);case"symbol":return ao(e);case"boolean":return Wa(e);case"object":if(e instanceof Date)return Ja(e);if(e instanceof Uint8Array)return qa(e);if(e instanceof Va)return ao(e);default:throw Ka(e,Ha)}}var lo="Key";function ho(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Ka(e,lo);return e}function uo(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],i=e[1];return!0===i?";"+ho(t):";"+ho(t)+"="+oo(i)})).join("")}function co(e){return e instanceof Ua?""+oo(e.value)+uo(e.params):oo(e)}function fo(e){return"("+e.value.map(co).join(" ")+")"+uo(e.params)}function go(e,t){if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e)throw Ka(e,Ba);var i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((function(e){var t=e[0],i=e[1];i instanceof Ua==0&&(i=new Ua(i));var r=ho(t);return!0===i.value?r+=uo(i.params):(r+="=",Array.isArray(i.value)?r+=fo(i):r+=co(i)),r})).join(","+r)}function mo(e,t){return go(e,t)}function po(e){return"ot"===e||"sf"===e||"st"===e}function vo(e){return"number"==typeof e?P(e):null!=e&&""!==e&&!1!==e}var yo=function(e){return Math.round(e)},Eo=function(e){return 100*yo(e/100)},To={br:yo,d:yo,bl:Eo,dl:Eo,mtp:Eo,nor:function(e,t){return(null==t?void 0:t.baseUrl)&&(e=bs(e,t.baseUrl)),encodeURIComponent(e)},rtp:Eo,tb:yo};function So(e,t){var i={};if(null==e||"object"!=typeof e)return i;var r=Object.keys(e).sort(),s=l({},To,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return r.forEach((function(r){if(!(null==n?void 0:n(r))){var a=e[r],o=s[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||vo(a)&&(po(r)&&"string"==typeof a&&(a=new Va(a)),i[r]=a)}})),i}function Ao(e,t){return void 0===t&&(t={}),e?mo(So(e,t),l({whitespace:!1},t)):""}function Lo(e,t){void 0===t&&(t={});var i={};if(!e)return i;var r=Object.entries(e),s=Object.entries(Na).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),n=r.reduce((function(e,t){var i,r,n=t[0],a=t[1],o=(null===(i=s.find((function(e){return e[1].includes(n)})))||void 0===i?void 0:i[0])||Fa.REQUEST;return null!==(r=e[o])&&void 0!==r||(e[o]={}),e[o][n]=a,e}),{});return Object.entries(n).reduce((function(e,i){var r=i[0],s=i[1];return e[r]=Ao(s,t),e}),i)}function Ro(e,t,i){return l(e,Lo(t,i))}var Io="CMCD";function bo(e,t){if(void 0===t&&(t={}),!e)return"";var i=Ao(e,t);return Io+"="+encodeURIComponent(i)}var Do=/CMCD=[^&#]+/;function ko(e,t,i){var r=bo(t,i);if(!r)return e;if(Do.test(e))return e.replace(Do,r);var s=e.includes("?")?"&":"?";return""+e+s+r}var _o=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){t.initialized&&(t.starved=!0),t.buffering=!0},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1},this.applyPlaylistData=function(e){try{t.apply(e,{ot:Oa.MANIFEST,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var i=e.frag,r=e.part,s=t.hls.levels[i.level],n=t.getObjectType(i),a={d:1e3*(r||i).duration,ot:n};n!==Oa.VIDEO&&n!==Oa.AUDIO&&n!=Oa.MUXED||(a.br=s.bitrate/1e3,a.tb=t.getTopBandwidth(n)/1e3,a.bl=t.getBufferLength(n));var o=r?t.getNextPart(r):t.getNextFrag(i);null!=o&&o.url&&o.url!==i.url&&(a.nor=o.url),t.apply(e,a)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;var i=this.config=e.config,r=i.cmcd;null!=r&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHED,this.onMediaDetached,this),e.on(M.BUFFER_CREATED,this.onBufferCreated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHED,this.onMediaDetached,this),e.off(M.BUFFER_CREATED,this.onBufferCreated,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},t.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},t.onBufferCreated=function(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer},t.createData=function(){var e;return{v:1,sf:Ma.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},t.apply=function(e,t){void 0===t&&(t={}),l(t,this.createData());var i=t.ot===Oa.INIT||t.ot===Oa.VIDEO||t.ot===Oa.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var r=this.includeKeys;r&&(t=Object.keys(t).reduce((function(e,i){return r.includes(i)&&(e[i]=t[i]),e}),{}));var s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Ro(e.headers,t,s)):e.url=ko(e.url,t,s)},t.getNextFrag=function(e){var t,i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){var r=e.sn-i.startSN;return i.fragments[r+1]}},t.getNextPart=function(e){var t,i,r=e.index,s=e.fragment,n=null==(t=this.hls.levels[s.level])||null==(i=t.details)?void 0:i.partList;if(n)for(var a=s.sn,o=n.length-1;o>=0;o--){var l=n[o];if(l.index===r&&l.fragment.sn===a)return n[o+1]}},t.getObjectType=function(e){var t=e.type;return"subtitle"===t?Oa.TIMED_TEXT:"initSegment"===e.sn?Oa.INIT:"audio"===t?Oa.AUDIO:"main"===t?this.hls.audioTracks.length?Oa.VIDEO:Oa.MUXED:void 0},t.getTopBandwidth=function(e){var t,i=0,r=this.hls;if(e===Oa.AUDIO)t=r.audioTracks;else{var s=r.maxAutoLevel,n=s>-1?s+1:r.levels.length;t=r.levels.slice(0,n)}for(var o,l=a(t);!(o=l()).done;){var h=o.value;h.bitrate>i&&(i=h.bitrate)}return i>0?i:NaN},t.getBufferLength=function(e){var t=this.media,i=e===Oa.AUDIO?this.audioBuffer:this.videoBuffer;return i&&t?1e3*ki.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var r=e.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(e,i,r){t(e),this.loader.load(e,i,r)},n(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var r=e.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(e,i,r){t(e),this.loader.load(e,i,r)},n(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e}(),Po=3e5,Co=function(e){function t(t){var i;return(i=e.call(this,"content-steering",t.logger)||this).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=t,i.registerListeners(),i}d(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.ERROR,this.onError,this))},i.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},i.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},i.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},i.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},i.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},i.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},i.onManifestLoaded=function(e,t){var i=t.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())},i.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},i.onError=function(e,t){var i=t.errorAction;if((null==i?void 0:i.action)===ti.SendAlternateToPenaltyBox&&i.flags===ii.MoveAllAlternatesMatchingHost){var r=this.levels,s=this._pathwayPriority,n=this.pathwayId;if(t.context){var a=t.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&r?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&r&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n),i.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+n+" levels: "+(r?r.length:r)+" priorities: "+bt(s)+" penalized: "+bt(this.penalizedPathways))}},i.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var i=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+i+'"'),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},i.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},i.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((function(e){r-i[e]>Po&&delete i[e]}));for(var s=0;s<e.length;s++){var n=e[s];if(!(n in i)){if(n===this.pathwayId)return;var a=this.hls.nextLoadLevel,o=this.hls.levels[a];if((t=this.getLevelsForPathway(n)).length>0){this.log('Setting Pathway to "'+n+'"'),this.pathwayId=n,Hr(t),this.hls.trigger(M.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=a);break}}}},i.getPathwayForGroupId=function(e,t,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),s=0;s<r.length;s++)if(t===F.AUDIO_TRACK&&r[s].hasAudioGroup(e)||t===F.SUBTITLE_TRACK&&r[s].hasSubtitleGroup(e))return r[s].pathwayId;return i},i.clonePathways=function(e){var t=this,i=this.levels;if(i){var r={},s={};e.forEach((function(e){var n=e.ID,a=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!i.some((function(e){return e.pathwayId===n}))){var l=t.getLevelsForPathway(a).map((function(e){var t=new Fi(e.attrs);t["PATHWAY-ID"]=n;var i=t.AUDIO&&t.AUDIO+"_clone_"+n,a=t.SUBTITLES&&t.SUBTITLES+"_clone_"+n;i&&(r[t.AUDIO]=i,t.AUDIO=i),a&&(s[t.SUBTITLES]=a,t.SUBTITLES=a);var l=xo(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new St({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var d=1;d<e.audioGroups.length;d++)h.addGroupId("audio",e.audioGroups[d]+"_clone_"+n);if(e.subtitleGroups)for(var u=1;u<e.subtitleGroups.length;u++)h.addGroupId("text",e.subtitleGroups[u]+"_clone_"+n);return h}));i.push.apply(i,l),wo(t.audioTracks,r,o,n),wo(t.subtitleTracks,s,o,n)}}))}},i.loadSteeringManifest=function(e){var t,i=this,r=this.hls.config,s=r.loader;this.loader&&this.loader.destroy(),this.loader=new s(r);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+e)}if("data:"!==t.protocol){var n=0|(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+n)}var a={responseType:"json",url:t.href},o=r.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},d={onSuccess:function(e,r,s,n){i.log('Loaded steering manifest: "'+t+'"');var a=e.data;if(1===(null==a?void 0:a.VERSION)){i.updated=performance.now(),i.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,t).href}catch(e){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}i.scheduleRefresh(i.uri||s.url),l&&i.clonePathways(l);var d={steeringManifest:a,url:t.toString()};i.hls.trigger(M.STEERING_MANIFEST_LOADED,d),h&&i.updatePathwayPriority(h)}else i.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(e,t,r,s){if(i.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),i.stopLoad(),410===e.code)return i.enabled=!1,void i.log("Steering manifest "+t.url+" no longer available");var n=1e3*i.timeToLoad;if(429!==e.code)i.scheduleRefresh(i.uri||t.url,n);else{var a=i.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(n=1e3*parseFloat(o))}i.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,r){i.log("Timeout loading steering manifest ("+t.url+")"),i.scheduleRefresh(i.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(a,h,d)},i.scheduleRefresh=function(e,t){var i=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,r=null==(t=i.hls)?void 0:t.media;!r||r.ended?i.scheduleRefresh(e,1e3*i.timeToLoad):i.loadSteeringManifest(e)}),t)},n(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(G);function wo(e,t,i,r){e&&Object.keys(t).forEach((function(s){var n=e.filter((function(e){return e.groupId===s})).map((function(e){var n=l({},e);return n.details=void 0,n.attrs=new Fi(n.attrs),n.url=n.attrs.URI=xo(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=r,n}));e.push.apply(e,n)}))}function xo(e,t,i,r){var s,n=r.HOST,a=r.PARAMS,o=r[i];t&&(s=null==o?void 0:o[t])&&(e=s);var l=new self.URL(e);return n&&!s&&(l.host=n),a&&Object.keys(a).sort().forEach((function(e){e&&l.searchParams.set(e,a[e])})),l.href}var Oo=function(e){function t(i){var r;return(r=e.call(this,"eme",i.logger)||this).hls=void 0,r.config=void 0,r.media=null,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,s='"'+e.type+'" event: init data type: "'+t+'"';if(r.debug(s),null!==i){if(!r.keyFormatPromise){var n=Object.keys(r.keySystemAccessPromises);n.length||(n=rr(r.config));var a=n.map(ir).filter((function(e){return!!e}));r.keyFormatPromise=r.getKeyFormatPromise(a)}r.keyFormatPromise.then((function(n){var a,o,l=Zi(n);if("sinf"===t){if(l!==zi.FAIRPLAY)return void r.warn('Ignoring unexpected "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+l);var h=ue(new Uint8Array(i));try{var d=De(Yi(JSON.parse(h).sinf));if(!d)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(d.subarray(8,24)),o=zi.FAIRPLAY}catch(e){return void r.warn(s+" Failed to parse sinf: "+e)}}else{if(l!==zi.WIDEVINE&&l!==zi.PLAYREADY)return void r.warn('Ignoring unexpected "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+l);var u=Ke(i),c=u.filter((function(e){return!!e.systemId&&tr(e.systemId)===l}));c.length>1&&r.warn(s+" Using first of "+c.length+" pssh found for selected key-system "+l);var f=c[0];if(!f)return void(0===u.length||u.some((function(e){return!e.systemId}))?r.warn(s+" contains incomplete or invalid pssh data"):r.log("ignoring "+s+" for "+u.map((function(e){return tr(e.systemId)})).join(",")+" pssh data in favor of playlist keys"));if(o=tr(f.systemId),0===f.version&&f.data)if(o===zi.WIDEVINE){var g=f.data.length-22;a=new Uint8Array(f.data.subarray(g,g+16))}else o===zi.PLAYREADY&&(a=hr(f.data))}if(o&&a){for(var m,p=Z.hexDump(a),v=r,y=v.keyIdToKeySessionPromise,E=v.mediaKeySessions,T=y[p],S=function(){var e=E[A],s=e.decryptdata;if(!s.keyId)return 0;var n=Z.hexDump(s.keyId);return p===n||-1!==s.uri.replace(/-/g,"").indexOf(p)?(T=y[n],s.pssh||(delete y[n],s.pssh=new Uint8Array(i),s.keyId=a,(T=y[p]=T.then((function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")}))).catch((function(e){return r.handleError(e)}))),1):void 0},A=0;A<E.length&&(0===(m=S())||1!==m);A++);if(!T){if(o!==l)return void r.log('Ignoring "'+e.type+'" event with '+o+" init data for selected key-system "+l);T=y[p]=r.getKeySystemSelectionPromise([o]).then((function(e){var s,n=e.keySystem,o=e.mediaKeys;r.throwIfDestroyed();var l=new ur("ISO-23001-7",p,null!=(s=ir(n))?s:"");return l.pssh=new Uint8Array(i),l.keyId=a,r.attemptSetMediaKeys(n,o).then((function(){r.throwIfDestroyed();var e=r.createMediaKeySessionContext({decryptdata:l,keySystem:n,mediaKeys:o});return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-no-match")}))})),T.catch((function(e){return r.handleError(e)}))}}}))}},r.onWaitingForKey=function(e){r.log('"'+e.type+'" event')},r.hls=i,r.config=i.config,r.registerListeners(),r}d(t,e);var i=t.prototype;return i.destroy=function(){var e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null},i.registerListeners=function(){this.hls.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(M.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(M.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(M.MANIFEST_LOADED,this.onManifestLoaded,this)},i.unregisterListeners=function(){this.hls.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(M.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(M.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(M.MANIFEST_LOADED,this.onManifestLoaded,this)},i.getLicenseServerUrl=function(e){var t=this.config,i=t.drmSystems,r=t.widevineLicenseUrl,s=i[e];return s?s.licenseUrl:e===zi.WIDEVINE&&r?r:void 0},i.getLicenseServerUrlOrThrow=function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'+e+'"');return t},i.getServerCertificateUrl=function(e){var t=this.config.drmSystems[e];if(t)return t.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+e+'"]')},i.attemptKeySystemAccess=function(e){var t=this,i=this.hls.levels,r=function(e,t,i){return!!e&&i.indexOf(e)===t},s=i.map((function(e){return e.audioCodec})).filter(r),n=i.map((function(e){return e.videoCodec})).filter(r);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((function(i,r){var a=function(e){var o=e.shift();t.getMediaKeysPromise(o,s,n).then((function(e){return i({keySystem:o,mediaKeys:e})})).catch((function(t){e.length?a(e):r(t instanceof Mo?t:new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};a(e)}))},i.requestMediaKeySystemAccess=function(e,t){var i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function "+i;return null===nr&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(r))}return i(e,t)},i.getMediaKeysPromise=function(e,t,i){var r=this,s=ar(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e],a=null==n?void 0:n.keySystemAccess;if(!a){this.log('Requesting encrypted media "'+e+'" key-system access with config: '+bt(s)),a=this.requestMediaKeySystemAccess(e,s);var o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch((function(t){r.log('Failed to obtain access to key-system "'+e+'": '+t)})),a.then((function(t){r.log('Access for key-system "'+t.keySystem+'" obtained');var i=r.fetchServerCertificate(e);return r.log('Create media-keys for "'+e+'"'),o.mediaKeys=t.createMediaKeys().then((function(t){return r.log('Media-keys created for "'+e+'"'),i.then((function(i){return i?r.setMediaKeysServerCertificate(t,e,i):t}))})),o.mediaKeys.catch((function(t){r.error('Failed to create media-keys for "'+e+'"}: '+t)})),o.mediaKeys}))}return a.then((function(){return n.mediaKeys}))},i.createMediaKeySessionContext=function(e){var t=e.decryptdata,i=e.keySystem,r=e.mediaKeys;this.log('Creating key-system session "'+i+'" keyId: '+Z.hexDump(t.keyId||[]));var s=r.createSession(),n={decryptdata:t,keySystem:i,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n},i.renewKeySession=function(e){var t=e.decryptdata;if(t.pssh){var i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)},i.getKeyIdString=function(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Z.hexDump(e.keyId)},i.updateKeySession=function(e,t){var i,r=e.mediaKeysSession;return this.log('Updating key-session "'+r.sessionId+'" for keyID '+Z.hexDump((null==(i=e.decryptdata)?void 0:i.keyId)||[])+"\n } (data length: "+(t?t.byteLength:t)+")"),r.update(t)},i.selectKeySystemFormat=function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+e.sn+" "+e.type+": "+e.level+") key formats "+t.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise},i.getKeyFormatPromise=function(e){var t=this;return new Promise((function(i,r){var s=rr(t.config),n=e.map(Zi).filter((function(e){return!!e&&-1!==s.indexOf(e)}));return t.getKeySystemSelectionPromise(n).then((function(e){var t=e.keySystem,s=ir(t);s?i(s):r(new Error('Unable to find format for key-system "'+t+'"'))})).catch(r)}))},i.loadKey=function(e){var t=this,i=e.keyInfo.decryptdata,r=this.getKeyIdString(i),s="(keyId: "+r+' format: "'+i.keyFormat+'" method: '+i.method+" uri: "+i.uri+")";this.log("Starting session for key "+s);var n=this.keyIdToKeySessionPromise[r];return n||(n=this.getKeySystemForKeyPromise(i).then((function(r){var n=r.keySystem,a=r.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: "+e.frag.sn+" "+e.frag.type+": "+e.frag.level+" using key "+s),t.attemptSetMediaKeys(n,a).then((function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:n,mediaKeys:a,decryptdata:i})}))})),(this.keyIdToKeySessionPromise[r]=n.then((function(e){var r="cenc",s=i.pssh?i.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,r,s,"playlist-key")}))).catch((function(e){return t.handleError(e)}))),n},i.throwIfDestroyed=function(e){if(!this.hls)throw new Error("invalid state")},i.handleError=function(e){this.hls&&(this.error(e.message),e instanceof Mo?this.hls.trigger(M.ERROR,e.data):this.hls.trigger(M.ERROR,{type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))},i.getKeySystemForKeyPromise=function(e){var t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){var r=Zi(e.keyFormat),s=r?[r]:rr(this.config);return this.attemptKeySystemAccess(s)}return i},i.getKeySystemSelectionPromise=function(e){if(e.length||(e=rr(this.config)),0===e.length)throw new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+bt({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(e)},i.attemptSetMediaKeys=function(e,t){var i=this,r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+e+'"');var s=Promise.all(r).then((function(){if(!i.media)throw new Error("Attempted to set mediaKeys without media element attached");return i.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(s),s.then((function(){i.log('Media-keys set for "'+e+'"'),r.push(s),i.setMediaKeysQueue=i.setMediaKeysQueue.filter((function(e){return-1===r.indexOf(e)}))}))},i.generateRequestWithPreferredKeySession=function(e,t,i,r){var s,n,a=this,o=null==(s=this.config.drmSystems)||null==(n=s[e.keySystem])?void 0:n.generateRequest;if(o)try{var l=o.call(this.hls,t,i,e);if(!l)throw new Error("Invalid response from configured generateRequest filter");t=l.initDataType,i=l.initData?l.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){var h;if(this.warn(e.message),null!=(h=this.hls)&&h.config.debug)throw e}if(null===i)return this.log('Skipping key-session request for "'+r+'" (no initData)'),Promise.resolve(e);var d=this.getKeyIdString(e.decryptdata);this.log('Generating key-session request for "'+r+'": '+d+" (init data type: "+t+" length: "+(i?i.byteLength:null)+")");var u=new b,c=e._onmessage=function(t){var i=e.mediaKeysSession;if(i){var r=t.messageType,s=t.message;a.log('"'+r+'" message event for session "'+i.sessionId+'" message size: '+s.byteLength),"license-request"===r||"license-renewal"===r?a.renewLicense(e,s).catch((function(e){u.eventNames().length?u.emit("error",e):a.handleError(e)})):"license-release"===r?e.keySystem===zi.FAIRPLAY&&(a.updateKeySession(e,Wi("acknowledged")),a.removeSession(e)):a.warn('unhandled media key message type "'+r+'"')}else u.emit("error",new Error("invalid state"))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){a.onKeyStatusChange(e);var i=e.keyStatus;u.emit("keyStatus",i),"expired"===i&&(a.warn(e.keySystem+" expired for key "+d),a.renewKeySession(e))}else u.emit("error",new Error("invalid state"))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",f);var g=new Promise((function(e,t){u.on("error",t),u.on("keyStatus",(function(i){i.startsWith("usable")?e():"output-restricted"===i?t(new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},'key status changed to "'+i+'"')):"expired"===i?t(new Error("key expired while generating request")):a.warn('unhandled key status change "'+i+'"')}))}));return e.mediaKeysSession.generateRequest(t,i).then((function(){var t;a.log('Request generated for key-session "'+(null==(t=e.mediaKeysSession)?void 0:t.sessionId)+'" keyId: '+d)})).catch((function(e){throw new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},"Error generating key-session request: "+e)})).then((function(){return g})).catch((function(t){throw u.removeAllListeners(),a.removeSession(e),t})).then((function(){return u.removeAllListeners(),e}))},i.onKeyStatusChange=function(e){var t=this;e.mediaKeysSession.keyStatuses.forEach((function(i,r){if("string"==typeof r&&"object"==typeof i){var s=r;r=i,i=s}t.log('key status change "'+i+'" for keyStatuses keyId: '+Z.hexDump("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))+" session keyId: "+Z.hexDump(new Uint8Array(e.decryptdata.keyId||[]))+" uri: "+e.decryptdata.uri),e.keyStatus=i}))},i.fetchServerCertificate=function(e){var t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'+e+'"'),new Promise((function(s,n){var a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(e,t,i,r){s(e.data)},onError:function(t,i,s,o){n(new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:g({url:a.url,data:void 0},t)},'"'+e+'" certificate request failed ('+r+"). Status: "+t.code+" ("+t.text+")"))},onTimeout:function(t,i,s){n(new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},'"'+e+'" certificate request timed out ('+r+")"))},onAbort:function(e,t,i){n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()},i.setMediaKeysServerCertificate=function(e,t,i){var r=this;return new Promise((function(s,n){e.setServerCertificate(i).then((function(n){r.log("setServerCertificate "+(n?"success":"not supported by CDM")+" ("+(null==i?void 0:i.byteLength)+') on "'+t+'"'),s(e)})).catch((function(e){n(new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))},i.renewLicense=function(e,t){var i=this;return this.requestLicense(e,new Uint8Array(t)).then((function(t){return i.updateKeySession(e,new Uint8Array(t)).catch((function(e){throw new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))}))},i.unpackPlayReadyKeyMessage=function(e,t){var i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0)for(var n,a=0,o=s.length;a<o;a++){var l,h,d=null==(l=(n=s[a]).querySelector("name"))?void 0:l.textContent,u=null==(h=n.querySelector("value"))?void 0:h.textContent;d&&u&&e.setRequestHeader(d,u)}var c=r.querySelector("Challenge"),f=null==c?void 0:c.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return Wi(atob(f))},i.setupLicenseXHR=function(e,t,i,r){var s=this,n=this.config.licenseXhrSetup;return n?Promise.resolve().then((function(){if(!i.decryptdata)throw new Error("Key removed");return n.call(s.hls,e,t,i,r)})).catch((function(a){if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(s.hls,e,t,i,r)})).then((function(i){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))},i.requestLicense=function(e,t){var i=this,r=this.config.keyLoadPolicy.default;return new Promise((function(s,n){var a=i.getLicenseServerUrlOrThrow(e.keySystem);i.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=i.config.licenseResponseCallback;if(h)try{l=h.call(i.hls,o,a,e)}catch(e){i.error(e)}s(l)}else{var d=r.errorRetry,u=d?d.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>u||o.status>=400&&o.status<500)n(new Mo({type:x.KEY_SYSTEM_ERROR,details:O.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+a+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=u-i._requestLicenseFailureCount+1;i.warn("Retrying license request, "+c+" attempts left"),i.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,i.setupLicenseXHR(o,a,e,t).then((function(t){var r=t.xhr,s=t.licenseChallenge;e.keySystem==zi.PLAYREADY&&(s=i.unpackPlayReadyKeyMessage(r,s)),r.send(s)}))}))},i.onMediaAttached=function(e,t){if(this.config.emeEnabled){var i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}},i.onMediaDetached=function(){var e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)},i._clear=function(e){var i,r=this,s=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ur.clearKeyUriToKeyIdMap();var n=s.length;t.CDMCleanupPromise=Promise.all(s.map((function(e){return r.removeSession(e)})).concat(null==e||null==(i=e.setMediaKeys(null))?void 0:i.catch((function(e){var t;r.log("Could not clear media keys: "+e),null==(t=r.hls)||t.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))).then((function(){n&&(r.log("finished closing key sessions and clearing media keys"),s.length=0)})).catch((function(e){var t;r.log("Could not close sessions and clear media keys: "+e),null==(t=r.hls)||t.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})}))},i.onManifestLoading=function(){this.keyFormatPromise=null},i.onManifestLoaded=function(e,t){var i=t.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+r.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(r)}},i.removeSession=function(e){var t=this,i=e.mediaKeysSession,r=e.licenseXhr;if(i){this.log("Remove licenses and keys and close session "+i.sessionId),e._onmessage&&(i.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var s=this.mediaKeySessions.indexOf(e);return s>-1&&this.mediaKeySessions.splice(s,1),(lr(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),i.remove().then(e)})):Promise.resolve()).catch((function(e){var i;t.log("Could not remove session: "+e),null==(i=t.hls)||i.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return i.close()})).catch((function(e){var i;t.log("Could not close session: "+e),null==(i=t.hls)||i.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}},t}(G);Oo.CDMCleanupPromise=void 0;var Mo=function(e){function t(t,i){var r;return(r=e.call(this,i)||this).data=void 0,t.error||(t.error=new Error(i)),r.data=t,t.err=t.error,r}return d(t,e),t}(E(Error)),Fo=function(){function e(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(M.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(M.MEDIA_DETACHING,this.onMediaDetaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var i=this.hls.config;if(i.capLevelOnFPSDrop){var r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,i){var r=performance.now();if(t){if(this.lastTime){var s=r-this.lastTime,n=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/s,l=this.hls;if(l.trigger(M.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){var h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=h)&&(h-=1,l.trigger(M.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}();function No(e){for(var t=5381,i=e.length;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}var Uo=.025,Bo=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Go(e,t,i){return e.identifier+"-"+(i+1)+"-"+No(t)}var $o=function(){function e(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}var t=e.prototype;return t.setDateRange=function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){if(e>=this.assetList.length)return!0;var t=this.playoutLimit;return!(e<=0||isNaN(t))&&this.assetList[e].startOffset>t},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return Ho(this)},n(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Ko(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-Ko(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=P(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Ko(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Uo))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Bo.Range:Bo.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}}])}();function Ko(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Uo)?t.start:t.start+t.duration}function Vo(e,t,i){var r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function Ho(e){return'["'+e.identifier+'" '+(e.cue.pre?"<pre>":e.cue.post?"<post>":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]"}function Yo(e){var t=e.timelineStart,i=e.duration||0;return'["'+e.identifier+'" '+t.toFixed(2)+"-"+(t+i).toFixed(2)+"]"}var Wo=function(){function e(e,t,i,r){var s=this;this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){var e=s.interstitial.playoutLimit,t=s.currentTime;s.startOffset+t>=e&&s.hls.trigger(M.PLAYOUT_LIMIT_REACHED,{})};var n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;var a=r.uri;try{a=Vo(a,n.sessionId).href}catch(e){}n.loadSource(a);var o=function(){s.hasDetails=!0};n.once(M.LEVEL_LOADED,o),n.once(M.AUDIO_TRACK_LOADED,o),n.once(M.SUBTITLE_TRACK_LOADED,o),n.on(M.MEDIA_ATTACHING,(function(e,t){var i=t.media;s.removeMediaListeners(),s.mediaAttached=i,s.interstitial.playoutLimit&&i.addEventListener("timeupdate",s.checkPlayout)}))}var t=e.prototype;return t.bufferedInPlaceToEnd=function(e){var t;if(!this.interstitial.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;var i=this.timelineOffset,r=ki.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=this._bufferedEosTime-.02},t.getAssetTime=function(e){var t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){this.hls.attachMedia(e)},t.detachMedia=function(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()},t.resumeBuffering=function(){this.hls.resumeBuffering()},t.pauseBuffering=function(){this.hls.pauseBuffering()},t.transferMedia=function(){return this.bufferSnapShot(),this.hls.transferMedia()},t.on=function(e,t,i){this.hls.on(e,t)},t.once=function(e,t,i){this.hls.once(e,t)},t.off=function(e,t,i){this.hls.off(e,t)},t.toString=function(){var e,t;return"HlsAssetPlayer: "+Yo(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(null!=(t=this.interstitial)&&t.appendInPlace?"append-in-place":"")},n(e,[{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=ki.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;return e||0}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var i=e-t;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),jo=.033,qo=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials-sched",i)||this).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=t,r}d(t,e);var i=t.prototype;return i.destroy=function(){this.reset(),this.onScheduleUpdate=null},i.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},i.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(i,r){return e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i}),0):0},i.getEvent=function(e){return e&&this.eventMap[e]||null},i.hasEvent=function(e){return e in this.eventMap},i.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i},i.findItemIndexAtTime=function(e,t){var i=this.items;if(i)for(var r=0;r<i.length;r++){var s=i[r];if(t&&"primary"!==t&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return r}return-1},i.findJumpRestrictedIndex=function(e,t){var i=this.items;if(i)for(var r=e;r<=t&&i[r];r++){var s=i[r].event;if(null!=s&&s.restrictions.jump&&!s.appendInPlace)return r}return-1},i.findEventIndex=function(e){var t=this.items;if(t)for(var i=t.length;i--;){var r;if((null==(r=t[i].event)?void 0:r.identifier)===e)return i}return-1},i.findAssetIndex=function(e,t){var i=e.assetList,r=i.length;if(r>1)for(var s=0;s<r;s++){var n=i[s];if(!n.error){var a=n.timelineStart;if(t===a||t>a&&t<a+(n.duration||0))return s}}return 0},i.parseInterstitialDateRanges=function(e,t){var i=this,r=e.main.details,s=r.dateRanges,n=this.events,a=this.parseDateRanges(s,{url:r.url},t),o=Object.keys(s),l=n?n.filter((function(e){return!o.includes(e.identifier)})):[];a.length&&a.sort((function(e,t){var i=e.cue.pre,r=e.cue.post,s=t.cue.pre,n=t.cue.post;if(i&&!s)return-1;if(s&&!i)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(i||s||r||n)){var a=e.startTime,o=t.startTime;if(a!==o)return a-o}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=a,l.forEach((function(e){i.removeEvent(e)})),this.updateSchedule(e,l)},i.updateSchedule=function(e,t){void 0===t&&(t=[]);var i=this.events||[];if(i.length||t.length||this.length<2){var r=this.items,s=this.parseSchedule(i,e);(t.length||(null==r?void 0:r.length)!==s.length||s.some((function(e,t){return Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005})))&&(this.items=s,this.onScheduleUpdate(t,r))}},i.parseDateRanges=function(e,t,i){for(var r=[],s=Object.keys(e),n=0;n<s.length;n++){var a=s[n],o=e[a];if(o.isInterstitial){var l=this.eventMap[a];l?l.setDateRange(o):(l=new $o(o,t),this.eventMap[a]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r},i.parseSchedule=function(e,t){var i=[],r=t.main.details,s=r.live?1/0:r.edge,n=0;if((e=e.filter((function(e){return!(e.error||e.cue.once&&e.hasPlayed)}))).length){this.resolveOffsets(e,t);var a=0,o=0;if(e.forEach((function(t,r){var l=t.cue.pre,h=t.cue.post,d=e[r-1]||null,u=t.appendInPlace,c=h?s:t.startOffset,f=t.duration,g=t.timelineOccupancy===Bo.Range?f:0,m=t.resumptionOffset,p=(null==d?void 0:d.startTime)===c,v=c+t.cumulativeDuration,y=u?v+f:c+m;if(l||!h&&c<=0){var E=o;o+=g,t.timelineStart=v;var T=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:T,end:n},integrated:{start:E,end:o}})}else{if(!(c<=s))return;if(!p){var S=c-a;if(S>jo){var A=a,L=o;o+=S;var R=n;n+=S;var I={previousEvent:e[r-1]||null,nextEvent:t,start:A,end:A+S,playout:{start:R,end:n},integrated:{start:L,end:o}};i.push(I)}else S>0&&d&&(d.cumulativeDuration+=S,i[i.length-1].end=c)}h&&(y=v),t.timelineStart=v;var b=o;o+=g;var D=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:D,end:n},integrated:{start:b,end:o}})}var k=t.resumeTime;a=h||k>s?s:k})),a<s){var l,h=a,d=o,u=s-a;o+=u;var c=n;n+=u,i.push({previousEvent:(null==(l=i[i.length-1])?void 0:l.event)||null,nextEvent:null,start:a,end:h+u,playout:{start:c,end:n},integrated:{start:d,end:o}})}this.setDurations(s,n,o)}else{var f=0;i.push({previousEvent:null,nextEvent:null,start:f,end:s,playout:{start:f,end:s},integrated:{start:f,end:s}}),this.setDurations(s,s,s)}return i},i.setDurations=function(e,t,i){this.durations={primary:e,playout:t,integrated:i}},i.resolveOffsets=function(e,t){var i=this,r=t.main.details,s=r.live?1/0:r.edge,n=0,a=-1;e.forEach((function(o,l){var h=o.cue.pre,d=o.cue.post,u=h?0:d?s:o.startTime;i.updateAssetDurations(o),a===u?o.cumulativeDuration=n:(n=0,a=u),!d&&o.snapOptions.in&&(o.resumeAnchor=Vt(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(i.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<jo&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&i.warn("Could not change append strategy for abutting event "+o));var c=P(o.resumeOffset)?o.resumeOffset:o.duration;n+=c}))},i.primaryCanResumeInPlaceAt=function(e,t){var i=this,r=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(r-s)>Uo?(this.log('"'+e.identifier+'" resumption '+r+" not aligned with estimated timeline end "+s),!1):t?!Object.keys(t).some((function(s){var n=t[s].details,a=n.edge;if(r>=a)return i.log('"'+e.identifier+'" resumption '+r+" past "+s+" playlist end "+a),!1;var o=Vt(null,n.fragments,r);if(!o)return i.log('"'+e.identifier+'" resumption '+r+" does not align with any fragments in "+s+" playlist ("+n.fragStart+"-"+n.fragmentEnd+")"),!0;var l="audio"===s?.175:0;return!(Math.abs(o.start-r)<Uo+l||Math.abs(o.end-r)<Uo+l||(i.log('"'+e.identifier+'" resumption '+r+" not aligned with "+s+" fragment bounds ("+o.start+"-"+o.end+" sn: "+o.sn+" cc: "+o.cc+")"),0))})):(this.log('"'+e.identifier+'" resumption '+r+" can not be aligned with media (none selected)"),!1)},i.updateAssetDurations=function(e){if(e.assetListLoaded){var t=e.timelineStart,i=0,r=!1,s=!1;e.assetList.forEach((function(e,n){var a=t+i;e.startOffset=i,e.timelineStart=a,r||(r=null===e.duration),s||(s=!!e.error);var o=e.error?0:e.duration||0;i+=o})),e.duration=r&&!s?Math.max(i,e.duration):i}},i.removeEvent=function(e){e.reset(),delete this.eventMap[e.identifier]},n(t,[{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var e,t,i=null==(e=this.items)||null==(t=e[this.length-1])?void 0:t.event;if(i){var r=i.assetList,s=r[r.length-1];if(s)return s.identifier}return null}}])}(G);function Xo(e){return"["+(e.event?'"'+e.event.identifier+'"':"primary")+": "+e.start.toFixed(2)+"-"+e.end.toFixed(2)+"]"}var Qo=function(){function e(e){this.hls=void 0,this.hls=e}var t=e.prototype;return t.destroy=function(){this.hls=null},t.loadAssetList=function(e,t){var i,r=this,s=e.assetListUrl;try{i=Vo(s,this.hls.sessionId,e.baseUrl)}catch(t){var n=this.assignAssetListError(e,O.ASSET_LIST_LOAD_ERROR,t,s);return void this.hls.trigger(M.ERROR,n)}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);var a=this.hls.config,o=new(0,a.loader)(a),l={responseType:"json",url:i.href},h=a.interstitialAssetListLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(t,i,s,n){var a=t.data,o=null==a?void 0:a.ASSETS;if(Array.isArray(o))e.assetListResponse=a,r.hls.trigger(M.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:n});else{var l=r.assignAssetListError(e,O.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,n);r.hls.trigger(M.ERROR,l)}},onError:function(t,i,s,n){var a=r.assignAssetListError(e,O.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+t.code+" "+t.text+" ("+i.url+")"),i.url,n,s);r.hls.trigger(M.ERROR,a)},onTimeout:function(t,i,s){var n=r.assignAssetListError(e,O.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+i.url+")"),i.url,t,s);r.hls.trigger(M.ERROR,n)}};return o.load(l,d,u),this.hls.trigger(M.ASSET_LIST_LOADING,{event:e}),o},t.assignAssetListError=function(e,t,i,r,s,n){return e.error=i,{type:x.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:n,stats:s}},e}();function zo(e,t,i){Jo(e,t,i),e.addEventListener(t,i)}function Jo(e,t,i){e.removeEventListener(t,i)}function Zo(e){null==e||e.play().catch((function(){}))}var el=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials",t.logger)||this).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled){var t=e-r.timelinePos;if(!(Math.abs(t)<1/7056e5)){var i=t<=-.01;r.timelinePos=e,r.bufferedPos=e;var s=r.playingItem;if(s)if(i&&r.schedule.resetErrorsInRange(e,e-t)&&r.updateSchedule(),r.checkBuffer(),i&&e<s.start||e>=s.end){var n,a=r.schedule.findItemIndexAtTime(r.timelinePos);if(!r.isInterstitial(s)&&null!=(n=r.media)&&n.paused&&(r.shouldPlay=!1),!i){var o=r.findItemIndex(s);if(a>o){var l=r.schedule.findJumpRestrictedIndex(o+1,a);if(l>o)return void r.setSchedulePosition(l)}}r.setSchedulePosition(a)}else{var h=r.playingAsset;if(h){var d=h.timelineStart,u=h.duration||0;(i&&e<d||e>=d+u)&&r.setScheduleToAssetAtTime(e,h)}else if(r.playingLastItem&&r.isInterstitial(s)){var c=s.event.assetList[0];c&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(e,c))}}else r.checkBuffer()}}},r.onTimeupdate=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&e>r.timelinePos){r.timelinePos=e,e>r.bufferedPos&&r.checkBuffer();var t=r.playingItem;if(t&&!r.playingLastItem){if(e>=t.end){r.timelinePos=t.end;var i=r.findItemIndex(t);r.setSchedulePosition(i+1)}var s=r.playingAsset;s&&e>=s.timelineStart+(s.duration||0)&&r.setScheduleToAssetAtTime(e,s)}}},r.onScheduleUpdate=function(e,t){var i=r.schedule,s=r.playingItem,n=i.events||[],a=i.items||[],o=i.durations,l=e.map((function(e){return e.identifier})),h=!(!n.length&&!l.length);if(h&&r.log("INTERSTITIALS_UPDATED ("+n.length+"): "+n+"\nSchedule: "+a.map((function(e){return Xo(e)}))),l.length&&r.log("Removed events "+l),r.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>Uo&&r.warn(s+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),s){var d=r.updateItem(s,r.timelinePos);r.itemsMatch(s,d)&&(r.playingItem=d,r.waitingItem=r.endedItem=null)}else r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var u=r.bufferingItem;if(u){var c=r.updateItem(u,r.bufferedPos);r.itemsMatch(u,c)?r.bufferingItem=c:u.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(u.event,null))}if(e.forEach((function(e){e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,null)}))})),h||t){if(r.hls.trigger(M.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:a.slice(0),durations:o,removedIds:l}),r.isInterstitial(s)&&l.includes(s.event.identifier))return r.warn('Interstitial "'+s.event.identifier+'" removed while playing'),void r.primaryFallback(s.event);r.checkBuffer()}},r.hls=t,r.HlsPlayerClass=i,r.assetListLoader=new Qo(t),r.schedule=new qo(r.onScheduleUpdate,t.logger),r.registerListeners(),r}d(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(M.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(M.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(M.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(M.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(M.BUFFER_APPENDED,this.onBufferAppended,this),e.on(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(M.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(M.MEDIA_ENDED,this.onMediaEnded,this),e.on(M.ERROR,this.onError,this),e.on(M.DESTROYING,this.onDestroying,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(M.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(M.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(M.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(M.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(M.BUFFER_CODECS,this.onBufferCodecs,this),e.off(M.BUFFER_APPENDED,this.onBufferAppended,this),e.off(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(M.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(M.MEDIA_ENDED,this.onMediaEnded,this),e.off(M.ERROR,this.onError,this),e.off(M.DESTROYING,this.onDestroying,this))},i.startLoad=function(){this.resumeBuffering()},i.stopLoad=function(){this.pauseBuffering()},i.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},i.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},i.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},i.removeMediaListeners=function(e){Jo(e,"play",this.onPlay),Jo(e,"pause",this.onPause),Jo(e,"seeking",this.onSeeking),Jo(e,"timeupdate",this.onTimeupdate)},i.onMediaAttaching=function(e,t){var i=this.media=t.media;zo(i,"seeking",this.onSeeking),zo(i,"timeupdate",this.onTimeupdate),zo(i,"play",this.onPlay),zo(i,"pause",this.onPause)},i.onMediaAttached=function(e,t){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var s=this.findItemIndex(i);this.setSchedulePosition(s)}},i.clearScheduleState=function(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){var s=this.getBufferingPlayer();s&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}},i.isInterstitial=function(e){return!(null==e||!e.event)},i.retreiveMediaSource=function(e,t){var i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)},i.transferMediaFromPlayer=function(e,t){var i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});var s=e.transferMedia();this.log("transfer MediaSource from "+e+" "+bt(s)),this.detachedData=s}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))},i.transferMediaTo=function(e,t){var i,r,s=this;if(e.media!==t){var n,a=null,o=this.hls,l=e!==o,h=l&&e.interstitial.appendInPlace,d=null==(i=this.detachedData)?void 0:i.mediaSource;if(o.media)h&&(a=o.transferMedia(),this.detachedData=a),n="Primary";else if(d){var u=this.getBufferingPlayer();u?(a=u.transferMedia(),n=""+u):n="detached MediaSource"}else n="detached media";if(!a)if(d)a=this.detachedData,this.log("using detachedData: MediaSource "+bt(a));else if(!this.detachedData||o.media===t){var c=this.playerQueue;c.length>1&&c.forEach((function(e){if(l&&e.interstitial.appendInPlace!==h){var t=e.interstitial;s.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&s.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var f=a&&"mediaSource"in a&&"closed"!==(null==(r=a.mediaSource)?void 0:r.readyState),g=f&&a?a:t;if(this.log((f?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+n),g===a){var m=l&&e.assetId===this.schedule.assetIdAtEnd;g.overrides={duration:this.schedule.duration,endOfStream:!l||m,cueRemoval:!l}}e.attachMedia(g)}},i.onInterstitialCueEnter=function(){this.onTimeupdate()},i.checkStart=function(){var e=this.schedule,t=e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){var s=this.hls.startPosition;if(this.timelinePos=s,t.length&&t[0].cue.pre){var n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(s>=0||!this.primaryLive){var a=this.timelinePos=s>0?s:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){var l=e.findItemIndex(r);this.setSchedulePosition(l)}}},i.advanceAfterAssetEnded=function(e,t,i){var r=i+1;if(e.isAssetPastPlayoutLimit(r)||e.assetList[r].error){var s=this.schedule.items;if(s){var n=t+1;if(n>=s.length)return void this.setSchedulePosition(-1);var a=e.resumeTime;this.timelinePos<a&&(this.timelinePos=a,this.checkBuffer()),this.setSchedulePosition(n)}}else this.setSchedulePosition(t,r)},i.setScheduleToAssetAtTime=function(e,t){var i=this.schedule,r=t.parentIdentifier,s=i.getEvent(r);if(s){var n=i.findEventIndex(r),a=i.findAssetIndex(s,e);this.setSchedulePosition(n,a)}},i.setSchedulePosition=function(e,t){var i=this.schedule.items;if(i&&!this.playbackDisabled){this.log("setSchedulePosition "+e+", "+t);var r=e>=0?i[e]:null,s=this.playingItem,n=this.playingLastItem;if(this.isInterstitial(s)){var a,o=s.event,l=this.playingAsset,h=null==l?void 0:l.identifier,d=h?this.getAssetPlayer(h):null;if(d&&h&&(!this.eventItemsMatch(s,r)||void 0!==t&&h!==(null==(a=o.assetList)?void 0:a[t].identifier))){var u,c=o.findAssetIndex(l);this.log("INTERSTITIAL_ASSET_ENDED "+(c+1)+"/"+o.assetList.length+" "+Yo(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(M.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:c,event:o,schedule:i.slice(0),scheduleIndex:e,player:d}),this.retreiveMediaSource(h,r),!d.media||null!=(u=this.detachedData)&&u.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(s,r)&&(this.endedItem=s,this.playingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+Xo(s)),o.hasPlayed=!0,this.hls.trigger(M.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once)){this.updateSchedule();var f=this.schedule.items;if(r&&f){var g=this.schedule.findItemIndex(r);this.advanceSchedule(g,f,t,s,n)}return}}this.advanceSchedule(e,i,t,s,n)}},i.advanceSchedule=function(e,t,i,r,s){var n=this,a=e>=0?t[e]:null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach((function(t){var i=t.interstitial,r=n.schedule.findEventIndex(i.identifier);(r<e||r>e+1)&&n.clearInterstitial(i,a)})),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);var h=a.event;void 0===i&&(i=this.schedule.findAssetIndex(h,this.timelinePos));var d=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);var u=this.preloadAssets(h,i);if(this.eventItemsMatch(a,d||r)||(this.waitingItem=a,this.log("INTERSTITIAL_STARTED "+Xo(a)+" "+(h.appendInPlace?"append in place":"")),this.hls.trigger(M.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+h);if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!o)return void this.log("Waiting for attachMedia to start Interstitial "+h);this.waitingItem=this.endedItem=null,this.playingItem=a;var c=h.assetList[i];if(!c){var f=t[e+1],g=this.media;return f&&g&&!this.isInterstitial(f)&&g.currentTime<f.start&&(g.currentTime=this.timelinePos=f.start),void this.advanceAfterAssetEnded(h,e,i||0)}if(u||(u=this.getAssetPlayer(c.identifier)),null===u||u.destroyed){var m=h.assetList.length;this.warn("asset "+(i+1)+"/"+m+" player destroyed "+h),u=this.createAssetPlayer(h,c,i)}if(!this.eventItemsMatch(a,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(u,i,t,e,o),this.shouldPlay&&Zo(u.media)}else null!==a?(this.resumePrimary(a,e,r),this.shouldPlay&&Zo(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))},i.resumePrimary=function(e,t,i){var r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming "+Xo(e)),null==(r=this.detachedData)||!r.mediaSource){var s=this.timelinePos;(s<e.start||s>=e.end)&&(s=this.getPrimaryResumption(e,t),this.timelinePos=s),this.attachPrimary(s,e)}if(i){var n=this.schedule.items;n&&(this.log("resumed "+Xo(e)),this.hls.trigger(M.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}},i.getPrimaryResumption=function(e,t){var i=e.start;if(this.primaryLive){var r=this.primaryDetails;if(0===t)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i},i.isAssetBuffered=function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:ki.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)},i.attachPrimary=function(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}},i.startLoadingPrimaryAt=function(e,t){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()},i.onManifestLoading=function(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(M.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(M.BUFFER_CODECS,this.onBufferCodecs,this)},i.onLevelUpdated=function(e,t){if(-1!==t.level){var i=this.hls.levels[t.level],r=g(g({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}},i.onAudioTrackUpdated=function(e,t){var i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(r){var s=g(g({},r),{},{audio:i});this.mediaSelection=s}else this.altSelection=g(g({},this.altSelection),{},{audio:i})},i.onSubtitleTrackUpdated=function(e,t){var i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(r){var s=g(g({},r),{},{subtitles:i});this.mediaSelection=s}else this.altSelection=g(g({},this.altSelection),{},{subtitles:i})},i.onAudioTrackSwitching=function(e,t){var i=Ct(t);this.playerQueue.forEach((function(e){return e.hls.setAudioOption(t)||e.hls.setAudioOption(i)}))},i.onSubtitleTrackSwitch=function(e,t){var i=Ct(t);this.playerQueue.forEach((function(e){return e.hls.setSubtitleOption(t)||-1!==t.id&&e.hls.setSubtitleOption(i)}))},i.onBufferCodecs=function(e,t){var i=t.tracks;i&&(this.requiredTracks=i)},i.onBufferAppended=function(e,t){this.checkBuffer()},i.onBufferFlushed=function(e,t){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}},i.onBufferedToEnd=function(e){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var i=0;i<t.length;i++){var r=t[i];if(r.cue.post){var s,n=this.schedule.findEventIndex(r.identifier),a=null==(s=this.schedule.items)?void 0:s[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}},i.onMediaEnded=function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1},i.updateItem=function(e,t){var i=this.schedule.items;return e&&i&&i[this.findItemIndex(e,t)]||null},i.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},i.eventItemsMatch=function(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))},i.findItemIndex=function(e,t){return e?this.schedule.findItemIndex(e,t):-1},i.updateSchedule=function(){var e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])},i.checkBuffer=function(e){var t=this.schedule.items;if(t){var i=ki.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,t,e)}},i.updateBufferedPos=function(e,t,i){var r=this.schedule,s=this.bufferingItem;if(!(this.bufferedPos>e))if(1===t.length&&this.itemsMatch(t[0],s))this.bufferedPos=e;else{var n=this.playingItem,a=this.findItemIndex(n),o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h,d=this.findItemIndex(s),u=Math.min(d+1,t.length-1),c=t[u];if((-1===o&&s&&e>=s.end||null!=(l=c.event)&&l.appendInPlace&&e+.01>=c.start)&&(o=u),u-a>1&&!1===(null==s||null==(h=s.event)?void 0:h.appendInPlace))return;if(this.bufferedPos=e,o>d&&o>a)this.bufferedToItem(c);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&c.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(c)&&this.preloadAssets(c.event,0)}}else i&&n&&!this.itemsMatch(n,s)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}},i.assetsBuffered=function(e,t){var i=this;return 0!==e.event.assetList.length&&!e.event.assetList.some((function(e){var r=i.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))}))},i.setBufferingItem=function(e){var t=this,i=this.bufferingItem,r=this.schedule;if(this.itemsMatch(e,i))this.bufferingItem!==e&&(this.bufferingItem=e);else{var s=r.items,n=r.events;if(!s||!n)return i;var a=this.isInterstitial(e),o=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){var l=o?o.remaining:i?i.end-this.timelinePos:0;this.log("buffered to boundary "+Xo(e)+(i?" ("+l.toFixed(2)+" remaining)":"")),a?e.event.assetList.forEach((function(e){var i=t.getAssetPlayer(e.identifier);i&&i.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((function(e){return e.pauseBuffering()})))}this.hls.trigger(M.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return i},i.bufferedToItem=function(e,t){void 0===t&&(t=0);var i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;if(r)if(r.mediaSource){var s=!0;this.attachPrimary(e.start,e,s)}else this.preloadPrimary(e);else this.preloadPrimary(e)}},i.preloadPrimary=function(e){var t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)},i.bufferedToEvent=function(e,t){var i=e.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){var n=this.preloadAssets(i,t);if(null!=n&&n.interstitial.appendInPlace){var a=i.assetList[t],o=this.primaryMedia;a&&o&&this.bufferAssetPlayer(n,o)}}},i.preloadAssets=function(e,t){var i=e.assetUrl,r=e.assetList.length,s=0===r&&!e.assetListLoader,n=e.cue.once;if(s){var a,o=e.timelineStart;if(e.appendInPlace){var l,h=this.playingItem;this.isInterstitial(h)||(null==h||null==(l=h.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var d=0;if(!this.playingItem&&this.primaryLive&&-1===(d=this.hls.startPosition)&&(d=this.hls.liveSyncPosition||0),d&&!e.cue.pre&&!e.cue.post){var u=d-o;u>0&&(a=Math.round(1e3*u)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(i?1:r)+" "+e+(a?" live-start: "+d+" start-offset: "+a:"")),i)return this.createAsset(e,0,0,o,e.duration,i);var c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!n&&r){for(var f=t;f<r;f++){var g=e.assetList[f],m=this.getAssetPlayerQueueIndex(g.identifier);-1!==m&&!this.playerQueue[m].destroyed||g.error||this.createAssetPlayer(e,g,f)}return this.getAssetPlayer(e.assetList[t].identifier)}return null},i.flushFrontBuffer=function(e){var t=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at "+e),Object.keys(i).forEach((function(i){t.hls.trigger(M.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})))},i.getAssetPlayerQueueIndex=function(e){for(var t=this.playerQueue,i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1},i.getAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null},i.getBufferingPlayer=function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null},i.createAsset=function(e,t,i,r,s,n){var a={parentIdentifier:e.identifier,identifier:Go(e,n,t),duration:s,startOffset:i,timelineStart:r,uri:n};return this.createAssetPlayer(e,a,t)},i.createAssetPlayer=function(e,t,i){var r=this;this.log("create HLSAssetPlayer for "+Yo(t));var s=this.hls,n=s.userConfig,a=n.videoPreference,o=s.loadLevelObj||s.levels[s.currentLevel];(a||o)&&(a=l({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));var h=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){var c=this.timelinePos-t.timelineStart;if(c>1){var f=t.duration;f&&c<f&&(u=c)}}var m=t.identifier,p=g(g({},n),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:m,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:h||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(p.timelineOffset=t.timelineStart));var v=p.cmcd;null!=v&&v.sessionId&&v.contentId&&(p.cmcd=l({},v,{contentId:No(t.uri)})),this.getAssetPlayer(m)&&this.warn("Duplicate date range identifier "+e+" and asset "+m);var y=new Wo(this.HlsPlayerClass,p,e,t);this.playerQueue.push(y),e.assetList[i]=t;var E=function(s){if(s.live){var n=new Error("Interstitials MUST be VOD assets "+e),a={fatal:!0,type:x.OTHER_ERROR,details:O.INTERSTITIAL_ASSET_ITEM_ERROR,error:n};r.handleAssetItemError(a,e,r.schedule.findEventIndex(e.identifier),i,n.message)}else{var o=s.edge-s.fragmentStart,l=t.duration;(null===l||o>l)&&(r.log('Interstitial asset "'+m+'" duration change '+l+" > "+o),t.duration=o,r.updateSchedule())}};y.on(M.LEVEL_UPDATED,(function(e,t){var i=t.details;return E(i)})),y.on(M.LEVEL_PTS_UPDATED,(function(e,t){var i=t.details;return E(i)}));var T=function(e,t){var i=r.getAssetPlayer(m);if(i&&t.tracks){i.off(M.BUFFER_CODECS,T),i.tracks=t.tracks;var s=r.primaryMedia;r.bufferingAsset===i.assetItem&&s&&!i.media&&r.bufferAssetPlayer(i,s)}};y.on(M.BUFFER_CODECS,T);var S=function(){var i,s=r.getAssetPlayer(m);if(r.log("buffered to end of asset "+s),s){var n=r.schedule.findEventIndex(e.identifier),a=e.findAssetIndex(t),o=a+1,l=null==(i=r.schedule.items)?void 0:i[n];if(r.isInterstitial(l))if(-1===a||e.isAssetPastPlayoutLimit(o)||e.assetList[o].error){var h,d=null==(h=r.schedule.items)?void 0:h[n+1];d&&r.bufferedToItem(d)}else r.bufferedToItem(l,o)}};y.on(M.BUFFERED_TO_END,S);var A=function(t){return function(){if(r.getAssetPlayer(m)){r.shouldPlay=!0;var i=r.schedule.findEventIndex(e.identifier);r.advanceAfterAssetEnded(e,i,t)}}};return y.once(M.MEDIA_ENDED,A(i)),y.once(M.PLAYOUT_LIMIT_REACHED,A(1/0)),y.on(M.ERROR,(function(t,s){var n=r.getAssetPlayer(m);if(s.details!==O.BUFFER_STALLED_ERROR)r.handleAssetItemError(s,e,r.schedule.findEventIndex(e.identifier),i,"Asset player error "+s.error+" "+e);else if(null!=n&&n.media){var a=n.currentTime,o=n.duration-a;a&&e.appendInPlace&&o/n.media.playbackRate<.5?(r.log("Advancing buffer past end of asset "+m+" "+e+" at "+n.media.currentTime),S()):(r.warn("Stalled at "+a+" of "+(a+o)+" in asset "+m+" "+e),r.onTimeupdate(),r.checkBuffer(!0))}})),y.on(M.DESTROYING,(function(){if(r.getAssetPlayer(m)){var t=new Error("Asset player destroyed unexpectedly "+m),s={fatal:!0,type:x.OTHER_ERROR,details:O.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};r.handleAssetItemError(s,e,r.schedule.findEventIndex(e.identifier),i,t.message)}})),this.hls.trigger(M.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:y}),y},i.clearInterstitial=function(e,t){var i=this;e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,t)})),e.reset()},i.clearAssetPlayer=function(e,t){var i=this.getAssetPlayerQueueIndex(e);if(-1!==i){this.log('clearAssetPlayer "'+e+'" toSegment: '+(t?Xo(t):t));var r=this.playerQueue[i];this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}},i.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},i.startAssetPlayer=function(e,t,i,r,s){var n=e.interstitial,a=e.assetItem,o=e.assetId,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+e),this.hls.trigger(M.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)},i.bufferAssetPlayer=function(e,t){var i,r,s=e.interstitial,n=e.assetItem,a=e.assetId,o=this.schedule.findEventIndex(s.identifier),l=null==(i=this.schedule.items)?void 0:i[o];if(l){this.setBufferingItem(l),this.bufferingAsset=n;var h=this.getBufferingPlayer();if(h!==e){var d=s.appendInPlace;if(!d||!1!==(null==h?void 0:h.interstitial.appendInPlace)){var u=(null==h?void 0:h.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks)return;if(u&&!z(u,e.tracks)){var c=new Error('Asset "'+a+"\" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(u)+"')"),f={fatal:!0,type:x.OTHER_ERROR,details:O.INTERSTITIAL_ASSET_ITEM_ERROR,error:c},g=s.findAssetIndex(n);return void this.handleAssetItemError(f,s,o,g,c.message)}}this.transferMediaTo(e,t)}}}},i.handleAssetItemError=function(e,t,i,r,s){if(e.details!==O.BUFFER_STALLED_ERROR){var n=t.assetList[r]||null,a=null;if(n){var o=this.getAssetPlayerQueueIndex(n.identifier);a=this.playerQueue[o]||null}var h=this.schedule.items,d=l({},e,{fatal:!1,errorAction:si(!0),asset:n,assetListIndex:r,event:t,schedule:h,scheduleIndex:i,player:a});if(this.warn("Asset item error: "+e.error),this.hls.trigger(M.INTERSTITIAL_ASSET_ERROR,d),e.fatal){var u=new Error(s);n&&(this.playingAsset!==n&&this.clearAssetPlayer(n.identifier,null),n.error=u),t.assetList.some((function(e){return!e.error}))?t.appendInPlace&&(t.error=u):t.error=u,this.primaryFallback(t)}}},i.primaryFallback=function(e){var t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log('Fallback to primary from event "'+e.identifier+'" start: '+t+" pos: "+this.timelinePos+" playing: "+(i?Xo(i):"<none>")+" error: "+e.error),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));var r=this.timelinePos;-1===r&&(r=this.hls.startPosition);var s=this.updateItem(i,r);if(this.itemsMatch(i,s))this.clearInterstitial(e,null);else{var n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}}else this.checkStart()},i.onAssetListLoaded=function(e,t){var i,r=this,s=t.event,n=s.identifier,a=t.assetListResponse.ASSETS;if(this.schedule.hasEvent(n)){var o=s.timelineStart,l=s.duration,h=0;a.forEach((function(e,t){var i=parseFloat(e.DURATION);r.createAsset(s,t,h,o+h,i,e.URI),h+=i})),s.duration=h,this.log("Loaded asset-list with duration: "+h+" (was: "+l+") "+s);var d=this.waitingItem,u=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();var c=null==(i=this.bufferingItem)?void 0:i.event;if(u){var f,g=this.schedule.findEventIndex(n),m=null==(f=this.schedule.items)?void 0:f[g];if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return s.error=new Error("Interstitial no longer within playback range "+this.timelinePos+" "+s),void this.primaryFallback(s);this.setBufferingItem(m)}this.setSchedulePosition(g)}else if((null==c?void 0:c.identifier)===n&&c.appendInPlace){var p=s.assetList[0],v=this.getAssetPlayer(p.identifier),y=this.primaryMedia;p&&v&&y&&this.bufferAssetPlayer(v,y)}}},i.onError=function(e,t){switch(t.details){case O.ASSET_LIST_PARSING_ERROR:case O.ASSET_LIST_LOAD_ERROR:case O.ASSET_LIST_LOAD_TIMEOUT:var i=t.interstitial;i&&this.primaryFallback(i);break;case O.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}},n(t,[{key:"interstitialsManager",get:function(){if(!this.manager){if(!this.hls)return null;var e=this,t=function(){return e.bufferingItem||e.waitingItem},i=function(t){return t?e.getAssetPlayer(t.identifier):t},r=function(t,r,s,a,o){if(t){var l=t[r].start,h=t.event;if(h){if("playout"===r||h.timelineOccupancy!==Bo.Point){var d=i(s);(null==d?void 0:d.interstitial)===h&&(l+=d.assetItem.startOffset+d[o])}}else l+=("bufferedPos"===a?n():e[a])-t.start;return l}return 0},s=function(t,i){if(0!==t&&"primary"!==i&&e.schedule.length){var r,s=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[s];if(n)return t+(n[i].start-n.start)}return t},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var i;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:e.schedule.durations[t]},o=function(t,s){var n,a,o=e.effectivePlayingItem;if(null==o||null==(n=o.event)||!n.restrictions.skip){e.log("seek to "+t+' "'+s+'"');var l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,s),d=null==(a=e.schedule.items)?void 0:a[h],u=e.getBufferingPlayer(),c=null==u?void 0:u.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(f||g)){var m=i(e.playingAsset),p=(null==m?void 0:m.media)||e.primaryMedia;if(p){var v="primary"===s?p.currentTime:r(l,s,e.playingAsset,"timelinePos","currentTime"),y=t-v,E=(f?v:p.currentTime)+y;if(E>=0&&(!m||f||E<=m.duration))return void(p.currentTime=E)}}if(d){var T=t;if("primary"!==s){var S=t-d[s].start;T=d.start+S}var A=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!A&&!d.event.appendInPlace){if(l){var L=e.findItemIndex(l);if(h>L){var R=e.schedule.findJumpRestrictedIndex(L+1,h);if(R>L)return void e.setSchedulePosition(R)}var I=0;if(A)e.timelinePos=T,e.checkBuffer();else{var b,D=null==d||null==(b=d.event)?void 0:b.assetList;if(D)for(var k=t-(d[s]||d).start,_=D.length;_--;){var P=D[_];if(P.duration&&k>=P.startOffset&&k<P.startOffset+P.duration){I=_;break}}}e.setSchedulePosition(h,I)}}else{var C=e.media||(f?null==u?void 0:u.media:null);C&&(C.currentTime=T)}}}},l=function(){var i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;var r=t();return e.isInterstitial(r)?r:null},h={get currentTime(){var t=l(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){var i=l(),r=e.effectivePlayingItem;r&&r===i&&o(t+r.playout.start,"playout")},get duration(){var e=l();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,i=null==(t=l())?void 0:t.event.assetList;return i?i.map((function(t){return e.getAssetPlayer(t.identifier)})):[]},get playingIndex(){var t,i=null==(t=l())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var t,i;return(null==(t=e.schedule)||null==(i=t.events)?void 0:i.slice(0))||[]},get schedule(){var t,i;return(null==(t=e.schedule)||null==(i=t.items)?void 0:i.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){o(e,"primary")},get duration(){return a("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){o(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){var t;return s((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){var r=e.findItemIndex(t);if(i.appendInPlace){var s=t.playout.start+t.event.duration;o(s+.001,"playout")}else e.advanceAfterAssetEnded(i,r,1/0)}}}}return this.manager}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t,i;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var s=this.media;!s&&null!=(e=this.bufferingItem)&&null!=(t=e.event)&&t.appendInPlace&&(s=this.primaryMedia);var n=null==(i=s)?void 0:i.currentTime;if(void 0!==n&&P(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e,t;return null==(e=this.mediaSelection)||null==(t=e.main)?void 0:t.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}}])}(G),tl=500,il=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"subtitle-stream-controller",N.SUBTITLE)||this).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s.registerListeners(),s}d(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(M.LEVEL_LOADED,this.onLevelLoaded,this),t.on(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(M.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(M.LEVEL_LOADED,this.onLevelLoaded,this),t.off(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(M.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.startLoad=function(e,t){this.stopLoad(),this.state=Zr.IDLE,this.setInterval(tl),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},i.onMediaDetaching=function(t,i){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,i)},i.onLevelLoaded=function(e,t){this.mainDetails=t.details},i.onSubtitleFragProcessed=function(e,t){var i=t.frag,r=t.success;if(re(i)&&(this.fragPrevious=i),this.state=Zr.IDLE,r){var s=this.tracksBuffered[this.currentTrackId];if(s){for(var n,a=i.start,o=0;o<s.length;o++)if(a>=s[o].start&&a<=s[o].end){n=s[o];break}var l=i.start+i.duration;n?n.end=l:(n={start:a,end:l},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}},i.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var s=r-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(e){for(var t=0;t<e.length;)if(e[t].end<=s)e.shift();else{if(!(e[t].start<s))break;e[t].start=s,t++}})),this.fragmentTracker.removeFragmentsInRange(i,s,N.SUBTITLE)}},i.onError=function(e,t){var i=t.frag;(null==i?void 0:i.type)===N.SUBTITLE&&(t.details===O.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Zr.STOPPED&&(this.state=Zr.IDLE))},i.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks;this.levels&&Ta(this.levels,r)?this.levels=r.map((function(e){return new St(e)})):(this.tracksBuffered=[],this.levels=r.map((function(e){var t=new St(e);return i.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,N.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)},i.onSubtitleTrackSwitch=function(e,t){var i;if(this.currentTrackId=t.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==Zr.STOPPED&&this.setInterval(tl)}else this.clearInterval()},i.onSubtitleTrackLoaded=function(e,t){var i,r=this.currentTrackId,s=this.levels,n=t.details,a=t.id;if(s){var o=s[a];if(!(a>=s.length)&&o){if(this.log("Subtitle track "+a+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges,n.live||null!=(i=o.details)&&i.live){var l=this.mainDetails;if(n.deltaUpdateFailed||!l)return;var h,d=l.fragments[0];o.details?0===this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details)&&d&&Br(n,d.start):n.hasProgramDateTime&&l.hasProgramDateTime?(zr(n,l),n.fragmentStart):d&&Br(n,d.start)}o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(M.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Zr.IDLE&&(Vt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},i._handleFragmentLoadComplete=function(e){var t=this,i=e.frag,r=e.payload,s=i.decryptdata,n=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&Vi(s.method)){var a=performance.now();this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,Hi(s.method)).catch((function(e){throw n.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(e){var t=performance.now();n.trigger(M.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:a,tdecrypt:t}})})).catch((function(e){t.warn(e.name+": "+e.message),t.state=Zr.IDLE}))}},i.doTick=function(){if(this.media){if(this.state===Zr.IDLE){var e=this.currentTrackId,t=this.levels,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,s=this.getLoadPosition(),n=ki.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),a=n.end,o=n.len,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var h=l.fragments,d=h.length,u=l.edge,c=null,f=this.fragPrevious;if(a<u){var g=r.maxFragLookUpTolerance,m=a>u-g?0:g;!(c=Vt(f,h,Math.max(h[0].start,a),m))&&f&&f.start<h[0].start&&(c=h[0])}else c=h[d-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;var p=h[c.sn-l.startSN-1];if(p&&p.cc===c.cc&&this.fragmentTracker.getState(p)===ni.NOT_LOADED&&(c=p),this.fragmentTracker.getState(c)===ni.NOT_LOADED){var v=this.mapToInitFragWhenRequired(c);v&&this.loadFragment(v,i,a)}}}else this.state=Zr.IDLE},i.loadFragment=function(t,i,r){re(t)?e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i)},n(t,[{key:"mediaBufferTimeRanges",get:function(){return new rl(this.tracksBuffered[this.currentTrackId]||[])}}])}(es),rl=function(e){this.buffered=void 0;var t=function(t,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+i+") is greater than the maximum bound ("+r+")");return e[i][t]};this.buffered={get length(){return e.length},end:function(i){return t("end",i,e.length)},start:function(i){return t("start",i,e.length)}}};function sl(e,t){var i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function nl(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(i){q.debug("[texttrack-utils]: "+i);try{var r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){q.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===i&&(e.mode=i)}function al(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===i&&(e.mode=i)}function ol(e,t,i,r){var s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var n=hl(e.cues,t,i),a=0;a<n.length;a++)r&&!r(n[a])||e.removeCue(n[a]);"disabled"===s&&(e.mode=s)}function ll(e,t){if(t<=e[0].startTime)return 0;var i=e.length-1;if(t>e[i].endTime)return-1;for(var r,s=0,n=i;s<=n;)if(t<e[r=Math.floor((n+s)/2)].startTime)n=r-1;else{if(!(t>e[r].startTime&&s<i))return r;s=r+1}return e[s].startTime-t<t-e[n].startTime?s:n}function hl(e,t,i){var r=[],s=ll(e,t);if(s>-1)for(var n=s,a=e.length;n<a;n++){var o=e[n];if(o.startTime>=t&&o.endTime<=i)r.push(o);else if(o.startTime>i)return r}return r}function dl(e){for(var t=[],i=0;i<e.length;i++){var r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}var ul=function(e){function t(t){var i;return(i=e.call(this,t,"subtitle-track-controller")||this).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var e=null,t=dl(i.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}var s=i.findTrackForTextTrack(e);i.subtitleTrack!==s&&i.setSubtitleTrack(s)}},i.registerListeners(),i}d(t,e);var i=t.prototype;return i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},i.registerListeners=function(){var e=this.hls;e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.LEVEL_LOADING,this.onLevelLoading,this),e.on(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(M.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.LEVEL_LOADING,this.onLevelLoading,this),e.off(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(M.ERROR,this.onError,this)},i.onMediaAttached=function(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},i.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},i.onMediaDetaching=function(e,t){var i=this.media;if(i){var r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||dl(i.textTracks).forEach((function(e){al(e)}))}},i.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},i.onSubtitleTrackLoaded=function(e,t){var i=t.id,r=t.groupId,s=t.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=t.details,this.log("Subtitle track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Subtitle track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(e,t){e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;var o=wt(a,n);if(o>-1)s=n[o];else{var l=wt(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var d={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(M.SUBTITLE_TRACKS_UPDATED,d),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=this.selectDefaultTrack,r=0;r<t.length;r++){var s=t[r];if((!i||s.default)&&(i||e)&&(!e||xt(s,e)))return r}if(e){for(var n=0;n<t.length;n++){var a=t[n];if(Sa(e.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(var o=0;o<t.length;o++){var l=t[o];if(Sa(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},i.findTrackForTextTrack=function(e){if(e)for(var t=this.tracksInGroup,i=0;i<t.length;i++)if(Aa(t[i],e))return i;return-1},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==F.SUBTITLE_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setSubtitleOption=function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var i=this.currentTrack;if(i&&xt(e,i))return i;var r=wt(e,this.tracksInGroup);if(r>-1){var s=this.tracksInGroup[r];return this.setSubtitleTrack(r),s}if(i)return null;var n=wt(e,t);if(n>-1)return t[n]}}return null},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading subtitle "+r+' "'+t.name+'" lang:'+t.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type?" "+a.type||0:""):"")+" "+n),this.hls.trigger(M.SUBTITLE_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:t})},i.toggleTrackModes=function(){var e=this.media;if(e){var t,i=dl(e.textTracks),r=this.currentTrack;if(r&&((t=i.filter((function(e){return Aa(r,e)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+r.name+'" and language "'+r.lang+'"')),[].slice.call(i).forEach((function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){var s=this.subtitleDisplay?"showing":"hidden";t.mode!==s&&(t.mode=s)}}},i.setSubtitleTrack=function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!P(e))this.warn("Invalid subtitle track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),r){var s=!!r.details&&!r.details.live;if(e!==this.trackId||r!==i||!s){this.log("Switching to subtitle-track "+e+(r?' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId:""));var n=r.id,a=r.groupId,o=void 0===a?"":a,l=r.name,h=r.type,d=r.url;this.hls.trigger(M.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:l,type:h,url:d});var u=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(u)}}else this.hls.trigger(M.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e},n(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}}])}(Ea),cl={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},fl=function(e){return String.fromCharCode(cl[e]||e)},gl=15,ml=100,pl={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},vl={17:2,18:4,21:6,22:8,23:10,19:13,20:15},yl={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},El={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Tl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Sl=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var i="function"==typeof t?t():t;q.log(this.time+" ["+e+"] "+i)}},e}(),Al=function(e){for(var t=[],i=0;i<e.length;i++)t.push(e[i].toString(16));return t},Ll=function(){function e(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}var t=e.prototype;return t.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},t.setStyles=function(e){for(var t=["foreground","underline","italics","background","flash"],i=0;i<t.length;i++){var r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}},t.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},t.equals=function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},t.copy=function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},t.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},e}(),Rl=function(){function e(){this.uchar=" ",this.penState=new Ll}var t=e.prototype;return t.reset=function(){this.uchar=" ",this.penState.reset()},t.setChar=function(e,t){this.uchar=e,this.penState.copy(t)},t.setPenState=function(e){this.penState.copy(e)},t.equals=function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},t.copy=function(e){this.uchar=e.uchar,this.penState.copy(e.penState)},t.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},e}(),Il=function(){function e(e){this.chars=[],this.pos=0,this.currPenState=new Ll,this.cueStartTime=null,this.logger=void 0;for(var t=0;t<ml;t++)this.chars.push(new Rl);this.logger=e}var t=e.prototype;return t.equals=function(e){for(var t=0;t<ml;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0},t.copy=function(e){for(var t=0;t<ml;t++)this.chars[t].copy(e.chars[t])},t.isEmpty=function(){for(var e=!0,t=0;t<ml;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},t.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>ml&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ml)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)},t.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},t.insertChar=function(e){var t=this;e>=144&&this.backSpace();var i=fl(e);this.pos>=ml?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+i+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t<ml;t++)this.chars[t].reset()},t.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.getTextString=function(){for(var e=[],t=!0,i=0;i<ml;i++){var r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")},t.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),bl=function(){function e(e){this.rows=[],this.currRow=gl-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var t=0;t<gl;t++)this.rows.push(new Il(e));this.logger=e}var t=e.prototype;return t.reset=function(){for(var e=0;e<gl;e++)this.rows[e].clear();this.currRow=gl-1},t.equals=function(e){for(var t=!0,i=0;i<gl;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t},t.copy=function(e){for(var t=0;t<gl;t++)this.rows[t].copy(e.rows[t])},t.isEmpty=function(){for(var e=!0,t=0;t<gl;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},t.backSpace=function(){this.rows[this.currRow].backSpace()},t.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.insertChar=function(e){this.rows[this.currRow].insertChar(e)},t.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},t.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},t.setCursor=function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},t.setPAC=function(e){this.logger.log(2,(function(){return"pacData = "+bt(e)}));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var i=0;i<gl;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){var n=s.rows[r].cueStartTime,a=this.logger.time;if(null!==n&&null!==a&&n<a)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(s.rows[r+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var h=e.indent,d=Math.max(h-1,0);l.setCursor(e.indent),e.color=l.chars[d].penState.foreground}var u={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(u)},t.setBkgData=function(e){this.logger.log(2,(function(){return"bkgData = "+bt(e)})),this.backSpace(),this.setPen(e),this.insertChar(32)},t.setRollUpRows=function(e){this.nrRollUpRows=e},t.rollUp=function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return e.getDisplayText()}));var t=this.currRow+1-this.nrRollUpRows,i=this.rows.splice(t,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},t.getDisplayText=function(e){e=e||!1;for(var t=[],i="",r=-1,s=0;s<gl;s++){var n=this.rows[s].getTextString();n&&(r=s+1,e?t.push("Row "+r+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i},t.getTextAndFormat=function(){return this.rows},e}(),Dl=function(){function e(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new bl(i),this.nonDisplayedMemory=new bl(i),this.lastOutputScreen=new bl(i),this.currRollUpRow=this.displayedMemory.rows[gl-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[gl-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"MODE="+e})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=this,i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return r+": "+t.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},t.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},t.ccAOF=function(){},t.ccAON=function(){},t.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.ccRU=function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},t.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},t.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},t.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.ccEOC=function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+e.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},t.ccTO=function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},t.ccMIDROW=function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+bt(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),kl=function(){function e(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Cl(),this.logger=void 0;var r=this.logger=new Sl;this.channels=[null,new Dl(e,t,r),new Dl(e+1,i,r)]}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var i=this;this.logger.time=e;for(var r=function(e){var r=127&t[e],s=127&t[e+1],n=!1,a=null;if(0===r&&0===s)return 0;i.logger.log(3,(function(){return"["+Al([t[e],t[e+1]])+"] -> ("+Al([r,s])+")"}));var o=i.cmdHistory;if(r>=16&&r<=31){if(Pl(r,s,o))return _l(null,null,o),i.logger.log(3,(function(){return"Repeated command ("+Al([r,s])+") is dropped"})),0;_l(r,s,i.cmdHistory),(n=i.parseCmd(r,s))||(n=i.parseMidrow(r,s)),n||(n=i.parsePAC(r,s)),n||(n=i.parseBackgroundAttributes(r,s))}else _l(null,null,o);if(!n&&(a=i.parseChars(r,s))){var l=i.currentChannel;l&&l>0?i.channels[l].insertChars(a):i.logger.log(2,"No channel found yet. TEXT-MODE?")}n||a||i.logger.log(2,(function(){return"Couldn't parse cleaned data "+Al([r,s])+" orig: "+Al([t[e],t[e+1]])}))},s=0;s<t.length;s+=2)r(s)},t.parseCmd=function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0},t.parseMidrow=function(e,t){var i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+Al([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var r=e<=23?1:2;i=t>=64&&t<=95?1===r?pl[e]:yl[e]:1===r?vl[e]:El[e];var s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)},t.interpretPAC=function(e,t){var i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r},t.parseChars=function(e,t){var i,r,s=null,n=null;return e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19?(r=17===n?t+80:18===n?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+fl(r)+"' in channel "+i})),s=[r]):e>=32&&e<=127&&(s=0===t?[e]:[e,t]),s&&this.logger.log(3,(function(){return"Char codes = "+Al(s).join(",")})),s},t.parseBackgroundAttributes=function(e,t){var i;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=Tl[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));var s=e<=23?1:2;return this.channels[s].setBkgData(r),!0},t.reset=function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}_l(null,null,this.cmdHistory)},t.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++){var i=this.channels[t];i&&i.cueSplitAtTime(e)}},e}();function _l(e,t,i){i.a=e,i.b=t}function Pl(e,t,i){return i.a===e&&i.b===t}function Cl(){return{a:null,b:null}}var wl=function(){if(null!=Qi&&Qi.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(t){return i(e,t)}function s(e){return i(t,e)}function n(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)e[a]=n[a]}return e}function a(e,t,i){var a=this,o={enumerable:!0};a.hasBeenReset=!1;var l="",h=!1,d=e,u=t,c=i,f=null,g="",m=!0,p="auto",v="start",y=50,E="middle",T=50,S="middle";Object.defineProperty(a,"id",n({},o,{get:function(){return l},set:function(e){l=""+e}})),Object.defineProperty(a,"pauseOnExit",n({},o,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(a,"startTime",n({},o,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"endTime",n({},o,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"text",n({},o,{get:function(){return c},set:function(e){c=""+e,this.hasBeenReset=!0}})),Object.defineProperty(a,"region",n({},o,{get:function(){return f},set:function(e){f=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"vertical",n({},o,{get:function(){return g},set:function(e){var t=r(e);if(!1===t)throw new SyntaxError("An invalid or illegal string was specified.");g=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"snapToLines",n({},o,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(a,"line",n({},o,{get:function(){return p},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"lineAlign",n({},o,{get:function(){return v},set:function(e){var t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"position",n({},o,{get:function(){return y},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"positionAlign",n({},o,{get:function(){return E},set:function(e){var t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"size",n({},o,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"align",n({},o,{get:function(){return S},set:function(e){var t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),a.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),xl=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function Ol(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}var i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}var Ml=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,i){for(var r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}},t.integer=function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},t.percent=function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1},e}();function Fl(e,t,i,r){var s=r?e.split(r):[e];for(var n in s)if("string"==typeof s[n]){var a=s[n].split(i);2===a.length&&t(a[0],a[1])}}var Nl=new wl(0,0,""),Ul="middle"===Nl.align?"middle":"center";function Bl(e,t,i){var r=e;function s(){var t=Ol(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(e,t){var r=new Ml;Fl(e,(function(e,t){var s;switch(e){case"region":for(var n=i.length-1;n>=0;n--)if(i[n].id===t){r.set(e,i[n].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",Ul,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",Ul,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",Ul,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");var s=r.get("line","auto");"auto"===s&&-1===Nl.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",Ul);var n=r.get("position","auto");"auto"===n&&50===Nl.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=s(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),a(),t.endTime=s(),a(),n(e,t)}function Gl(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var $l=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new xl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function i(){var e=t.buffer,i=0;for(e=Gl(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;var r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}function r(e){Fl(e,(function(e,t){}),/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var s="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var n=(s=i()).match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var a=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:s=i(),t.state){case"HEADER":/:/.test(s)?r(s):s||(t.state="ID");continue;case"NOTE":s||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){t.state="NOTE";break}if(!s)continue;if(t.cue=new wl(0,0,""),t.state="CUE",-1===s.indexOf("--\x3e")){t.cue.id=s;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Bl(s,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var o=-1!==s.indexOf("--\x3e");if(!s||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=s;continue;case"BADCUE":s||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},t.flush=function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this},e}(),Kl=/\r\n|\n\r|\n|\r/g,Vl=function(e,t,i){return void 0===i&&(i=0),e.slice(i,i+t.length)===t},Hl=function(e){var t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(P(t)&&P(i)&&P(r)&&P(s)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*i,t+=6e4*r,t+=36e5*s};function Yl(e,t,i){return No(e.toString())+No(t.toString())+No(i)}var Wl=function(e,t,i){var r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,s=e[(r=s).prevCC]}e.presentationOffset=i};function jl(e,t,i,r,s,n,a){var o,l=new $l,h=J(new Uint8Array(e)).trim().replace(Kl,"\n").split("\n"),d=[],u=t?Cn(t.baseTime,t.timescale):0,c="00:00.000",f=0,g=0,m=!0;l.oncue=function(e){var n=i[r],a=i.ccOffset,l=(f-u)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:Wl(i,r,l)),l){if(!t)return void(o=new Error("Missing initPTS for VTT MPEGTS"));a=l-i.presentationOffset}var h=e.endTime-e.startTime,c=Gn(9e4*(e.startTime+a-g),9e4*s)/9e4;e.startTime=Math.max(c,0),e.endTime=Math.max(c+h,0);var m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=Yl(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},l.onparsingerror=function(e){o=e},l.onflush=function(){o?a(o):n(d)},h.forEach((function(e){if(m){if(Vl(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((function(e){Vl(e,"LOCAL:")?c=e.slice(6):Vl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=Hl(c)/1e3}catch(e){o=e}return}""===e&&(m=!1)}l.parse(e+"\n")})),l.flush()}var ql="stpp.ttml.im1t",Xl=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ql=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,zl={left:"start",center:"center",right:"end",start:"start",end:"end"};function Jl(e,t,i,r){var s=ye(new Uint8Array(e),["mdat"]);if(0!==s.length){var n=s.map((function(e){return J(e)})),a=_n(t.baseTime,1,t.timescale);try{n.forEach((function(e){return i(Zl(e,a))}))}catch(e){r(e)}}else r(new Error("Could not parse IMSC1 mdat"))}function Zl(e,t){var i=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||r[t],e}),{}),n="preserve"!==i.getAttribute("xml:space"),a=th(eh(i,"styling","style")),o=th(eh(i,"layout","region")),h=eh(i,"body","[begin]");return[].map.call(h,(function(e){var i=ih(e,n);if(!i||!e.hasAttribute("begin"))return null;var r=ah(e.getAttribute("begin"),s),h=ah(e.getAttribute("dur"),s),d=ah(e.getAttribute("end"),s);if(null===r)throw nh(e);if(null===d){if(null===h)throw nh(e);d=r+h}var u=new wl(r-t,d-t,i);u.id=Yl(u.startTime,u.endTime,u.text);var c=rh(o[e.getAttribute("region")],a[e.getAttribute("style")],a),f=c.textAlign;if(f){var g=zl[f];g&&(u.lineAlign=g),u.align=f}return l(u,c),u})).filter((function(e){return null!==e}))}function eh(e,t,i){var r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function th(e){return e.reduce((function(e,t){var i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function ih(e,t){return[].slice.call(e.childNodes).reduce((function(e,i,r){var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?ih(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function rh(e,t,i){var r="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),n.reduce((function(i,n){var a=sh(t,r,n)||sh(e,r,n)||sh(s,r,n);return a&&(i[n]=a),i}),{})}function sh(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function nh(e){return new Error("Could not parse ttml timestamp "+e)}function ah(e,t){if(!e)return null;var i=Ol(e);return null===i&&(Xl.test(e)?i=oh(e,t):Ql.test(e)&&(i=lh(e,t))),i}function oh(e,t){var i=Xl.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}function lh(e,t){var i=Ql.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}var hh=function(){function e(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}var t=e.prototype;return t.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},t.newCue=function(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),dh=function(){function e(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=gh(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(M.FRAG_LOADING,this.onFragLoading,this),e.on(M.FRAG_LOADED,this.onFragLoaded,this),e.on(M.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(M.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(M.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(M.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=function(){var e=this.hls;e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(M.FRAG_LOADING,this.onFragLoading,this),e.off(M.FRAG_LOADED,this.onFragLoaded,this),e.off(M.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(M.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(M.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(M.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new hh(this,"textTrack1"),t=new hh(this,"textTrack2"),i=new hh(this,"textTrack3"),r=new hh(this,"textTrack4");this.cea608Parser1=new kl(1,e,t),this.cea608Parser2=new kl(3,i,r)},t.addCues=function(e,t,i,r,s){for(var n=!1,a=s.length;a--;){var o=s[a],l=fh(o[0],o[1],t,i);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],i),n=!0,l/(i-t)>.5))return}if(n||s.push([t,i]),this.config.renderTextTracksNatively){var h=this.captionsTracks[e];this.Cues.newCue(h,t,i,r)}else{var d=this.Cues.newCue(null,t,i,r);this.hls.trigger(M.CUES_PARSED,{type:"captions",cues:d,track:e})}},t.onInitPtsFound=function(e,t){var i=this,r=t.frag,s=t.id,n=t.initPTS,a=t.timescale,o=this.unparsedVttFrags;s===N.MAIN&&(this.initPTS[r.cc]={baseTime:n,timescale:a}),o.length&&(this.unparsedVttFrags=[],o.forEach((function(e){i.onFragLoaded(M.FRAG_LOADED,e)})))},t.getExistingTrack=function(e,t){var i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var s=i.textTracks[r];if(ch(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null},t.createCaptionsTrack=function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},t.createNativeTrack=function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,i=this.captionsTracks,r=this.media,s=t[e],n=s.label,a=s.languageCode,o=this.getExistingTrack(n,a);if(o)i[e]=o,al(i[e]),sl(i[e],r);else{var l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}},t.createNonNativeTrack=function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(M.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}},t.createTextTrack=function(e,t,i){var r=this.media;if(r)return r.addTextTrack(e,t,i)},t.onMediaAttaching=function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()},t.onMediaDetaching=function(e,t){var i=!!t.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach((function(e){al(r[e]),delete r[e]})),this.nonNativeCaptionsTracks={}}},t.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=gh(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},t._cleanTracks=function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var i=0;i<t.length;i++)al(t[i])}},t.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks||[],s=r.some((function(e){return e.textCodec===ql}));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Ta(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var n=this.media,a=n?dl(n.textTracks):null;if(this.tracks.forEach((function(e,t){var r;if(a){for(var s=null,n=0;n<a.length;n++)if(a[n]&&ch(a[n],e)){s=a[n],a[n]=null;break}s&&(r=s)}if(r)al(r);else{var o=uh(e);(r=i.createTextTrack(o,e.name,e.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)})),null!=a&&a.length){var o=a.filter((function(e){return null!==e})).map((function(e){return e.label}));o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: "+o.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")}}else if(this.tracks.length){var l=this.tracks.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(M.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}},t.onManifestLoaded=function(e,t){var i=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var r="textTrack"+t[1],s=i.captionsProperties[r];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)}}))},t.closedCaptionsForLevel=function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]},t.onFragLoading=function(e,t){if(this.enabled&&t.frag.type===N.MAIN){var i,r,s=this.cea608Parser1,n=this.cea608Parser2,a=this.lastSn,o=t.frag,l=o.cc,h=o.sn,d=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;s&&n&&(h!==a+1||h===a&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),n.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=d}},t.onFragLoaded=function(e,t){var i=t.frag,r=t.payload;if(i.type===N.SUBTITLE)if(r.byteLength){var s=i.decryptdata,n="stats"in t;if(null==s||!s.encrypted||n){var a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===ql?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})},t._parseIMSC1=function(e,t){var i=this,r=this.hls;Jl(t,this.initPTS[e.cc],(function(t){i._appendCues(t,e.level),r.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(function(t){r.logger.log("Failed to parse IMSC1: "+t),r.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))},t._parseVTTs=function(e){var t,i=this,r=e.frag,s=e.payload,n=this.initPTS,a=this.unparsedVttFrags,o=n.length-1;if(n[r.cc]||-1!==o){var l=this.hls;jl(null!=(t=r.initSegment)&&t.data?xe(r.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(function(e){i._appendCues(e,r.level),l.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(function(t){var n="Missing initPTS for VTT MPEGTS"===t.message;n?a.push(e):i._fallbackToIMSC1(r,s),l.logger.log("Failed to parse VTT cue: "+t),n&&o>r.cc||l.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}else a.push(e)},t._fallbackToIMSC1=function(e,t){var i=this,r=this.tracks[e.level];r.textCodec||Jl(t,this.initPTS[e.cc],(function(){r.textCodec=ql,i._parseIMSC1(e,t)}),(function(){r.textCodec="wvtt"}))},t._appendCues=function(e,t){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((function(e){return nl(r,e)}))}else{var s=this.tracks[t];if(!s)return;var n=s.default?"default":"subtitles"+t;i.trigger(M.CUES_PARSED,{type:"subtitles",cues:e,track:n})}},t.onFragDecrypted=function(e,t){t.frag.type===N.SUBTITLE&&this.onFragLoaded(M.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var i=t.frag,r=t.samples;if(i.type!==N.MAIN||"NONE"!==this.closedCaptionsForLevel(i))for(var s=0;s<r.length;s++){var n=r[s].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();var a=this.extractCea608Data(n);this.cea608Parser1.addData(r[s].pts,a[0]),this.cea608Parser2.addData(r[s].pts,a[1])}}}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,s=t.endOffsetSubtitles,n=t.type,a=this.media;if(a&&!(a.currentTime<r)){if(!n||"video"===n){var o=this.captionsTracks;Object.keys(o).forEach((function(e){return ol(o[e],i,r)}))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==s){var l=this.textTracks;Object.keys(l).forEach((function(e){return ol(l[e],i,s)}))}}},t.extractCea608Data=function(e){for(var t=[[],[]],i=31&e[0],r=2,s=0;s<i;s++){var n=e[r++],a=127&e[r++],o=127&e[r++];if((0!==a||0!==o)&&4&n){var l=3&n;0!==l&&1!==l||(t[l].push(a),t[l].push(o))}}return t},e}();function uh(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function ch(e,t){return!!e&&e.kind===uh(t)&&Aa(t,e)}function fh(e,t,i,r){return Math.min(t,r)-Math.max(e,i)}function gh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var mh=/\s/,ph={newCue:function(e,t,i,r){for(var s,n,a,o,l,h=[],d=self.VTTCue||self.TextTrackCue,u=0;u<r.rows.length;u++)if(a=!0,o=0,l="",!(s=r.rows[u]).isEmpty()){for(var c,f=0;f<s.chars.length;f++)mh.test(s.chars[f].uchar)&&a?o++:(l+=s.chars[f].uchar,a=!1);s.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;var g=Gl(l.trim()),m=Yl(t,i,g);null!=e&&null!=(c=e.cues)&&c.getCueById(m)||((n=new d(t,i,g)).id=m,n.line=u+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(n))}return e&&h.length&&(h.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),h.forEach((function(t){return nl(e,t)}))),h}};function vh(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}var yh=/(\d+)-(\d+)\/(\d+)/,Eh=function(){function e(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Lh,this.controller=new self.AbortController,this.stats=new ee}var t=e.prototype;return t.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},t.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},t.load=function(e,t,i){var r=this,s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();var n=Th(e,this.controller.signal),a="arraybuffer"===e.responseType,o=a?"byteLength":"length",l=t.loadPolicy,h=l.maxTimeToFirstByteMs,d=l.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=h&&P(h)?h:d,this.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,e,r.response))}),t.timeout),(Jn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(i){var n;r.response=r.loader=i;var o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(r.requestTimeout),t.timeout=d,r.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,e,r.response))}),d-(o-s.loading.start)),!i.ok){var l=i.status,h=i.statusText;throw new Rh(h||"fetch, bad network response",l,i)}s.loading.first=o,s.total=Ah(i.headers)||s.total;var u=null==(n=r.callbacks)?void 0:n.onProgress;return u&&P(t.highWaterMark)?r.loadProgressively(i,s,e,t.highWaterMark,u):a?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((function(i){var n,a,l=r.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);var h=i[o];h&&(s.loaded=s.total=h);var d={url:l.url,data:i,code:l.status},u=null==(n=r.callbacks)?void 0:n.onProgress;u&&!P(t.highWaterMark)&&u(s,e,i,l),null==(a=r.callbacks)||a.onSuccess(d,s,e,l)})).catch((function(t){var i;if(self.clearTimeout(r.requestTimeout),!s.aborted){var n=t&&t.code||0,a=t?t.message:null;null==(i=r.callbacks)||i.onError({code:n,text:a},e,t?t.details:null,s)}}))},t.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},t.loadProgressively=function(e,t,i,r,s){void 0===r&&(r=0);var n=new is,a=e.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return n.dataLength&&s(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(t,i,n.flush().buffer,e)):s(t,i,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function Th(e,t){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(l({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}function Sh(e){var t=yh.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Ah(e){var t=e.get("Content-Range");if(t){var i=Sh(t);if(P(i))return i}var r=e.get("Content-Length");if(r)return parseInt(r)}function Lh(e,t){return new self.Request(e.url,t)}var Rh=function(e){function t(t,i,r){var s;return(s=e.call(this,t)||this).code=void 0,s.details=void 0,s.code=i,s.details=r,s}return d(t,e),t}(E(Error)),Ih=/^age:\s*[\d.]+\s*$/im,bh=function(){function e(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ee,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},t.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()},t.loadInternal=function(){var e=this,t=this.config,i=this.context;if(t&&i){var r=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;var n=this.xhrSetup;n?Promise.resolve().then((function(){if(e.loader===r&&!e.stats.aborted)return n(r,i.url)})).catch((function(t){if(e.loader===r&&!e.stats.aborted)return r.open("GET",i.url,!0),n(r,i.url)})).then((function(){e.loader!==r||e.stats.aborted||e.openAndSendXhr(r,i,t)})).catch((function(t){var n;null==(n=e.callbacks)||n.onError({code:r.status,text:t.message},i,r,s)})):this.openAndSendXhr(r,i,t)}},t.openAndSendXhr=function(e,t,i){e.readyState||e.open("GET",t.url,!0);var r=t.headers,s=i.loadPolicy,n=s.maxTimeToFirstByteMs,a=s.maxLoadTimeMs;if(r)for(var o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&P(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,i=this.stats;if(e&&t){var r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var n=t.status,a="text"===t.responseType?t.responseText:null;if(n>=200&&n<300){var o=null!=a?a:t.response;if(null!=o){var l,h;i.loading.end=Math.max(self.performance.now(),i.loading.first);var d="arraybuffer"===t.responseType?o.byteLength:o.length;i.loaded=i.total=d,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var u=null==(l=this.callbacks)?void 0:l.onProgress;u&&u(i,e,o,t);var c={url:t.responseURL,data:o,code:n};return void(null==(h=this.callbacks)||h.onSuccess(c,i,e,t))}}var f,g=s.loadPolicy.errorRetry;Zt(g,i.retry,!1,{url:e.url,data:void 0,code:n})?this.retry(g):(q.error(n+" while loading "+e.url),null==(f=this.callbacks)||f.onError({code:n,text:t.statusText},e,t,i))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Zt(e,this.stats.retry,!0))this.retry(e);else{var t;q.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,i=this.stats;this.retryDelay=zt(e,i.retry),i.retry++,q.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+i.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&Ih.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},e}(),Dh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},kh=g(g({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,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:bh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Gt,bufferController:ka,capLevelController:xa,errorController:ri,fpsController:Fo,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:nr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:Dh},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},_h()),{},{subtitleStreamController:il,subtitleTrackController:ul,timelineController:dh,audioStreamController:ya,audioTrackController:La,emeController:Oo,cmcdController:_o,contentSteeringController:Co,interstitialsController:el});function _h(){return{cueHandler:ph,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Ph(e,t,i){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(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=Ch(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var n=("level"===e?"playlist":e)+"LoadPolicy",a=void 0===t[n],o=[];s.forEach((function(i){var s=e+"Loading"+i,l=t[s];if(void 0!==l&&a){o.push(s);var h=r[n].default;switch(t[n]={default:h},i){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+n+'": '+bt(t[n]))})),g(g({},r),t)}function Ch(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Ch):Object.keys(e).reduce((function(t,i){return t[i]=Ch(e[i]),t}),{}):e}function wh(e,t){var i=e.loader;i!==Eh&&i!==bh?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):vh()&&(e.loader=Eh,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var xh=2,Oh=.1,Mh=.05,Fh=100,Nh=function(e){function t(t,i){var r;return(r=e.call(this,"gap-controller",t.logger)||this).hls=null,r.fragmentTracker=null,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var e;null!=(e=r.media)&&e.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var e;r.hls&&(r.ended=(null==(e=r.media)?void 0:e.currentTime)||1,r.hls.trigger(M.MEDIA_ENDED,{stalled:!1}))},r.hls=t,r.fragmentTracker=i,r.registerListeners(),r}d(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e&&(e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.BUFFER_APPENDED,this.onBufferAppended,this))},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.BUFFER_APPENDED,this.onBufferAppended,this))},i.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},i.onMediaAttached=function(e,t){this.setInterval(Fh),this.mediaSource=t.mediaSource;var i=this.media=t.media;zo(i,"playing",this.onMediaPlaying),zo(i,"waiting",this.onMediaWaiting),zo(i,"ended",this.onMediaEnded)},i.onMediaDetaching=function(e,t){this.clearInterval();var i=this.media;i&&(Jo(i,"playing",this.onMediaPlaying),Jo(i,"waiting",this.onMediaWaiting),Jo(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},i.onBufferAppended=function(e,t){this.buffered=t.timeRanges},i.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}},i.poll=function(e,t){var i,r,s=null==(i=this.hls)?void 0:i.config;if(s){var n=this.media,a=this.stalled;if(n){var o=n.seeking,l=this.seeking&&!o,h=!this.seeking&&o,d=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,e!==t)return t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(h||l)l&&this.stallResolved(e);else{if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(M.MEDIA_ENDED,{stalled:!1})));if(ki.getBuffered(n).length){var u=ki.bufferInfo(n,e,0),c=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){var g=Uh(this.hls.inFlightFragments,e),m=u.len>xh,p=!c||g||c-e>xh&&!f.getPartialFragment(e);if(m||p)return;this.moved=!1}var v=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(u.len>0||c))return;var y=Math.max(c,u.start||0)-e,E=null!=v&&v.live?2*v.targetduration:xh,T=f.getPartialFragment(e);if(y>0&&(y<=E||T))return void(n.paused||this._trySkipBufferHole(T))}var S=s.detectStallWithCurrentTimeMs,A=self.performance.now(),L=this.waiting;if(null!==a){var R=A-a;if(!o&&(R>=S||L)&&this.hls){var I;if("ended"===(null==(I=this.mediaSource)?void 0:I.readyState)&&(null==v||!v.live)&&Math.abs(e-((null==v?void 0:v.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(M.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}var b=ki.bufferInfo(n,e,s.maxBufferHole);this._tryFixBufferStall(b,R)}else this.stalled=L>0&&A-L<S?L:A}else this.nudgeRetry=0}}}},i.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(i)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(M.STALL_RESOLVED,{})}},i.nudgeOnVideoHole=function(e,t){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){var s=ki.bufferedInfo(ki.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){var n=ki.timeRangesToArray(r),a=ki.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){var o=ki.bufferedInfo(n,e,0).bufferedIndex,l=n[a].end,h=n[a+1].start;if((-1===o||o>a)&&h-l<1&&e-l<2){var d=new Error("nudging playhead to flush pipeline after video hole. currentTime: "+e+" hole: "+l+" -> "+h+" buffered index: "+o);this.warn(d.message),this.media.currentTime+=1e-6;var u=this.fragmentTracker.getPartialFragment(e)||void 0,c=ki.bufferInfo(this.media,e,0);this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:u,buffer:c.len,bufferInfo:c})}}}}},i._tryFixBufferStall=function(e,t){var i,r,s=this.fragmentTracker,n=this.media,a=null==(i=this.hls)?void 0:i.config;if(n&&s&&a){var o=n.currentTime,l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=s.getPartialFragment(o);if((h||null!=l&&l.live&&o<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;var d=e.buffered;(d&&d.length>1&&e.len>a.maxBufferHole||e.nextStart&&e.nextStart-o<a.maxBufferHole)&&(t>1e3*a.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},i._reportStall=function(e){var t=this.hls,i=this.media,r=this.stallReported,s=this.stalled;if(!r&&null!==s&&i&&t){this.stallReported=!0;var n=new Error("Playback stalling at @"+i.currentTime+" due to low buffer ("+bt(e)+")");this.warn(n.message),t.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:s}})}},i._trySkipBufferHole=function(e){var t,i=this.fragmentTracker,r=this.media,s=null==(t=this.hls)?void 0:t.config;if(!r||!i||!s)return 0;var n=r.currentTime,a=ki.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){var l=a.len<=s.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,d=o-n;if(d>0&&(l||h)){if(d>s.maxBufferHole){var u=!1;if(0===n){var c=i.getAppendedFrag(0,N.MAIN);c&&o<c.end&&(u=!0)}if(!u){var f=e||i.getAppendedFrag(n,N.MAIN);if(f){var g;if(null==(g=this.hls.loadLevelObj)||!g.details)return 0;if(Uh(this.hls.inFlightFragments,o))return 0;for(var m=!1,p=f.end;p<o;){var v=i.getPartialFragment(p);if(!v){m=!0;break}p+=v.duration}if(m)return 0}}}var y=Math.max(o+Mh,n+Oh);if(this.warn("skipping hole, adjusting currentTime from "+n+" to "+y),this.moved=!0,r.currentTime=y,null==e||!e.gap){var E=new Error("fragment loaded with buffer holes, seeking from "+n+" to "+y);this.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:E,reason:E.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return y}}return 0},i._tryNudgeBuffer=function(e){var t=this.hls,i=this.media,r=this.nudgeRetry,s=null==t?void 0:t.config;if(!i||!s)return 0;var n=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){var a=n+(r+1)*s.nudgeOffset,o=new Error("Nudging 'currentTime' from "+n+" to "+a);this.warn(o.message),i.currentTime=a,t.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @"+n+" after "+s.nudgeMaxRetry+" nudges");this.error(l.message),t.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},n(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}(Ri);function Uh(e,t){var i=Bh(e.main);if(i&&i.start<=t)return i;var r=Bh(e.audio);return r&&r.start<=t?r:null}function Bh(e){if(!e)return null;switch(e.state){case Zr.IDLE:case Zr.STOPPED:case Zr.ENDED:case Zr.ERROR:return null}return e.frag}var Gh=.25;function $h(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Kh(e,t,i,r,s){var n=new e(t,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new e(t,i,bt(s?g({type:s},r):r))}return n}var Vh=function(){var e=$h();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}();function Hh(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var Yh=function(){function e(e){var t=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=function(){t.hls&&t.hls.trigger(M.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}var t=e.prototype;return t.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null},t._registerListeners=function(){var e=this.hls;e.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},t._unregisterListeners=function(){var e=this.hls;e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},t.onMediaAttaching=function(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)},t.onMediaAttached=function(){var e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)},t.onMediaDetaching=function(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&al(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},t.getID3Track=function(e){if(this.media){for(var t=0;t<e.length;t++){var i=e[t];if("metadata"===i.kind&&"id3"===i.label)return sl(i,this.media),i}return this.media.addTextTrack("metadata","id3")}},t.onFragParsingMetadata=function(e,t){if(this.media){var i=this.hls.config,r=i.enableEmsgMetadataCues,s=i.enableID3MetadataCues;if(r||s){var n=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=$h();if(a)for(var o=0;o<n.length;o++){var l=n[o].type;if((l!==$s.emsg||r)&&s){var h=Ns(n[o].data);if(h){var d=n[o].pts,u=d+n[o].duration;u>Vh&&(u=Vh),u-d<=0&&(u=d+Gh);for(var c=0;c<h.length;c++){var f=h[c];if(!Us(f)){this.updateId3CueEnds(d,l);var g=Kh(a,d,u,f,l);g&&this.id3Track.addCue(g)}}}}}}}},t.updateId3CueEnds=function(e,t){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var s=r.length;s--;){var n=r[s];n.type===t&&n.startTime<e&&n.endTime===Vh&&(n.endTime=e)}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,s=t.type,n=this.id3Track,a=this.hls;if(a){var o=a.config,l=o.enableEmsgMetadataCues,h=o.enableID3MetadataCues;n&&(l||h)&&ol(n,i,r,"audio"===s?function(e){return e.type===$s.audioId3&&h}:"video"===s?function(e){return e.type===$s.emsg&&l}:function(e){return e.type===$s.audioId3&&h||e.type===$s.emsg&&l})}},t.onLevelUpdated=function(e,t){var i=t.details;this.updateDateRangeCues(i,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var i=this;if(this.media&&e.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var r,s=this.id3Track,n=e.dateRanges,a=Object.keys(n),o=this.dateRangeCuesAppended;if(s&&t)if(null!=(r=s.cues)&&r.length)for(var l=Object.keys(o).filter((function(e){return!a.includes(e)})),h=function(){var e=l[d],t=o[e].cues;delete o[e],Object.keys(t).forEach((function(e){try{var r=t[e];r.removeEventListener("enter",i.onEventCueEnter),s.removeCue(r)}catch(e){}}))},d=l.length;d--;)h();else o=this.dateRangeCuesAppended={};var u=e.fragments[e.fragments.length-1];if(0!==a.length&&P(null==u?void 0:u.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var c=$h(),f=function(){var e=a[g],t=n[e],r=t.startTime,s=o[e],l=(null==s?void 0:s.cues)||{},h=(null==s?void 0:s.durationKnown)||!1,d=Vh,u=t.duration;if(t.endDate&&null!==u)d=r+u,h=!0;else if(t.endOnNext&&!h){var f=a.reduce((function(e,i){if(i!==t.id){var r=n[i];if(r.class===t.class&&r.startDate>t.startDate&&(!e||t.startDate<e.startDate))return r}return e}),null);f&&(d=f.startTime,h=!0)}for(var m=Object.keys(t.attr),p=0;p<m.length;p++){var v=m[p];if(Ui(v)){var y=l[v];if(y)h&&!s.durationKnown?y.endTime=d:Math.abs(y.startTime-r)>.01&&(y.startTime=r,y.endTime=d);else if(c){var E=t.attr[v];Bi(v)&&(E=Hh(E));var T=Kh(c,r,d,{key:v,data:E},$s.dateRange);T&&(T.id=e,i.id3Track.addCue(T),l[v]=T,i.hls.config.interstitialsController&&("X-ASSET-LIST"!==v&&"X-ASSET-URL"!==v||T.addEventListener("enter",i.onEventCueEnter)))}}}o[e]={cues:l,dateRange:t,durationKnown:h}},g=0;g<a.length;g++)f()}}},e}(),Wh=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e=t.media,i=t.levelDetails;if(e&&i){t.currentTime=e.currentTime;var r=t.computeLatency();if(null!==r){t._latency=r;var s=t.config,n=s.lowLatencyMode,a=s.maxLiveSyncPlaybackRate;if(n&&1!==a&&i.live){var o=t.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(t.maxLatency,o+i.targetduration)&&l>.05&&t.forwardBufferLength>1){var h=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*l-t.edgeStalled))*20)/20,u=Math.min(h,Math.max(1,d));t.changeMediaPlaybackRate(e,u)}else 1!==e.playbackRate&&0!==e.playbackRate&&t.changeMediaPlaybackRate(e,1)}}}}},this.hls=e,this.config=e.config,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.ERROR,this.onError,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.ERROR,this.onError,this))},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)},t.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},t.onManifestLoading=function(){this._latency=null,this.stallCount=0},t.onLevelUpdated=function(e,t){var i=t.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var i;t.details===O.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(r=this.targetLatency)?void 0:r.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},n(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,i=e.partHoldBack,r=e.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*r);var d=r;return h+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var i=this.levelDetails;if(null===i)return null;var r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}}])}(),jh=function(e){function t(t,i){var r;return(r=e.call(this,t,"level-controller")||this)._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,r._registerListeners(),r}d(t,e);var i=t.prototype;return i._registerListeners=function(){var e=this.hls;e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.LEVEL_LOADED,this.onLevelLoaded,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(M.FRAG_BUFFERED,this.onFragBuffered,this),e.on(M.ERROR,this.onError,this)},i._unregisterListeners=function(){var e=this.hls;e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.LEVEL_LOADED,this.onLevelLoaded,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(M.FRAG_BUFFERED,this.onFragBuffered,this),e.off(M.ERROR,this.onError,this)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},i.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(e,t){this.resetLevels()},i.onManifestLoaded=function(e,t){var i=this,r=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,h=!1;t.levels.forEach((function(e){var t,d=e.attrs,u=e.audioCodec,c=e.videoCodec;u&&(e.audioCodec=u=tt(u,r)||void 0),0===(null==(t=c)?void 0:t.indexOf("avc1"))&&(c=e.videoCodec=st(c));var f=e.width,g=e.height,m=e.unknownCodecs,p=m?m.length:0;if(m)for(var v=p;v--;){var y=m[v];i.isAudioSupported(y)?(e.audioCodec=u=u?u+","+y:y,p--,Ye.audio[u.substring(0,4)]=2):i.isVideoSupported(y)&&(e.videoCodec=c=c?c+","+y:y,p--,Ye.video[c.substring(0,4)]=2)}if(o||(o=!(!f||!g)),l||(l=!!c),h||(h=!!u),p||u&&!i.isAudioSupported(u)||c&&!i.isVideoSupported(c))i.log('Some or all CODECS not supported "'+d.CODECS+'"');else{var E=d.CODECS,T=d["FRAME-RATE"],S=d["HDCP-LEVEL"],A=d["PATHWAY-ID"],L=d.RESOLUTION,R=d["VIDEO-RANGE"],I=(A||".")+"-"+e.bitrate+"-"+L+"-"+T+"-"+E+"-"+R+"-"+S;if(n[I])if(n[I].uri===e.url||e.attrs["PATHWAY-ID"])n[I].addGroupId("audio",d.AUDIO),n[I].addGroupId("text",d.SUBTITLES);else{var b=a[I]+=1;e.attrs["PATHWAY-ID"]=new Array(b+1).join(".");var D=i.createLevel(e);n[I]=D,s.push(D)}else{var k=i.createLevel(e);n[I]=k,a[I]=1,s.push(k)}}})),this.filterAndSortMediaOptions(s,t,o,l,h)},i.createLevel=function(e){var t=new St(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'+i.videoCodec+'"');this.log(r.message),t.supportedResult=ht(r,[])}return t},i.isAudioSupported=function(e){return je(e,"audio",this.hls.config.preferManagedMediaSource)},i.isVideoSupported=function(e){return je(e,"video",this.hls.config.preferManagedMediaSource)},i.filterAndSortMediaOptions=function(e,t,i,r,s){var n=this,a=[],o=[],l=e;if((i||r)&&s&&(l=l.filter((function(e){var t=e.videoCodec,i=e.videoRange,r=e.width,s=e.height;return(!!t||!(!r||!s))&&vt(i)}))),0!==l.length){t.audioTracks&&qh(a=t.audioTracks.filter((function(e){return!e.audioCodec||n.isAudioSupported(e.audioCodec)}))),t.subtitles&&qh(o=t.subtitles);var h=l.slice(0);l.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return pt.indexOf(e.videoRange)-pt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var r=Qe(e.videoCodec),s=Qe(t.videoCodec);if(r!==s)return s-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var n=ze(e.codecSet),a=ze(t.codecSet);if(n!==a)return a-n}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var d=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==h.length)for(var u=0;u<h.length;u++)if(h[u].pathwayId===l[0].pathwayId){d=h[u];break}this._levels=l;for(var c=0;c<l.length;c++)if(l[c]===d){var f;this._firstLevel=c;var g=d.bitrate,m=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+l.length+" level(s) found, first bitrate: "+g),void 0===(null==(f=this.hls.userConfig)?void 0:f.abrEwmaDefaultEstimate)){var p=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);p>m&&m===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=p)}break}var v=s&&!r,y=this.hls.config,E=!(!y.audioStreamController||!y.audioTrackController),T={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:E&&!v&&a.some((function(e){return!!e.url}))};this.hls.trigger(M.MANIFEST_PARSED,T)}else Promise.resolve().then((function(){if(n.hls){var e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i="one or more CODECS in variant not supported: "+bt(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,i){return i.indexOf(e)===t}))),n.warn(i),e+=" ("+i+")");var r=new Error(e);n.hls.trigger(M.ERROR,{type:x.MEDIA_ERROR,details:O.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}))},i.onError=function(e,t){!t.fatal&&t.context&&t.context.type===F.LEVEL&&t.context.level===this.level&&this.checkRetry(t)},i.onFragBuffered=function(e,t){var i=t.frag;if(void 0!==i&&i.type===N.MAIN){var r=i.elementaryStreams;if(!Object.keys(r).some((function(e){return!!r[e]})))return;var s=this._levels[i.level];null!=s&&s.loadError&&(this.log("Resetting level error count of "+s.loadError+" on frag buffered"),s.loadError=0)}},i.onLevelLoaded=function(e,t){var i,r,s=t.level,n=t.details,a=t.levelInfo;if(!a)return this.warn("Invalid level index "+s),void(null!=(r=t.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0));if(a===this.currentLevel||t.withoutMultiVariant){0===a.fragmentError&&(a.loadError=0);var o=a.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(s,t,o)}else null!=(i=t.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0)},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=this.getUrlWithDirectives(t.uri,i),s=this.currentLevelIndex,n=t.attrs["PATHWAY-ID"],a=t.details,o=null==a?void 0:a.age;this.log("Loading level index "+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(n?" Pathway "+n:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type?" "+a.type||0:""):"")+" "+r),this.hls.trigger(M.LEVEL_LOADING,{url:r,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||null})},i.removeLevel=function(e){var t,i=this;if(1!==this._levels.length){var r=this._levels.filter((function(t,r){return r!==e||(i.steering&&i.steering.removeLevel(t),t===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));Hr(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var s=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(M.LEVELS_UPDATED,{levels:r})}},i.onLevelsUpdated=function(e,t){var i=t.levels;this._levels=i},i.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,i=e.maxAutoLevel,r=e.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(M.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))},n(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}var s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,s!==e||!n||a!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+s+(a?" with Pathway "+a:""));var h={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(M.LEVEL_SWITCHING,h);var d=o.details;if(!d||d.live){var u=this.switchParams(o.uri,null==n?void 0:n.details,d);this.loadPlaylist(u)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),i=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=i}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(Ea);function qh(e){var t={};e.forEach((function(e){var i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function Xh(){return self.SourceBuffer||self.WebKitSourceBuffer}function Qh(){if(!X())return!1;var e=Xh();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function zh(){if(!Qh())return!1;var e=X();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Xe(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Xe(t,"audio"))})))}function Jh(){var e,t=Xh();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}var Zh=100,ed=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"stream-controller",N.MAIN)||this).audioCodecSwap=!1,s.level=-1,s._forceStartLoad=!1,s._hasEnoughToStart=!1,s.altAudio=0,s.audioOnly=!1,s.fragPlaying=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s.onMediaPlaying=function(){s.tick()},s.onMediaSeeked=function(){var e=s.media,t=e?e.currentTime:null;if(null!==t&&P(t)&&(s.log("Media seeked to "+t.toFixed(3)),s.getBufferedFrag(t))){var i=s.getFwdBufferInfoAtPos(e,t,N.MAIN,0);null!==i&&0!==i.len?s.tick():s.warn("Main forward buffer length at "+t+' on "seeked" event '+(i?i.len:"empty")+")")}},s.registerListeners(),s}d(t,e);var i=t.prototype;return i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(M.MANIFEST_PARSED,this.onManifestParsed,this),t.on(M.LEVEL_LOADING,this.onLevelLoading,this),t.on(M.LEVEL_LOADED,this.onLevelLoaded,this),t.on(M.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(M.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(M.BUFFER_CREATED,this.onBufferCreated,this),t.on(M.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(M.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(M.MANIFEST_PARSED,this.onManifestParsed,this),t.off(M.LEVEL_LOADED,this.onLevelLoaded,this),t.off(M.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(M.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(M.BUFFER_CREATED,this.onBufferCreated,this),t.off(M.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(M.FRAG_BUFFERED,this.onFragBuffered,this)},i.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},i.startLoad=function(e,t){if(this.levels){var i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(Zh),this.level=-1,!this.startFragRequested){var s=r.startLevel;-1===s&&(r.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=r.firstAutoLevel),r.nextLoadLevel=s,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i),this.state=Zr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Zr.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case Zr.WAITING_LEVEL:var e=this.levels,t=this.level,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=Zr.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Zr.IDLE;break}break;case Zr.FRAG_LOADING_WAITING_RETRY:var s,n=self.performance.now(),a=this.retryDate;if(!a||n>=a||null!=(s=this.media)&&s.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=Zr.IDLE}}this.state===Zr.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},i.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,i=this.levels,r=this.media;if(null!==t&&(r||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var s=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=i&&i[s]){var n=i[s],a=this.getMainFwdBufferInfo();if(null!==a){var o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(M.BUFFER_EOS,l),void(this.state=Zr.ENDED)}if(this.buffering){e.loadLevel!==s&&-1===e.manualLevel&&this.log("Adapting to level "+s+" from level "+this.level),this.level=e.nextLoadLevel=s;var h=n.details;if(!h||this.state===Zr.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=Zr.WAITING_LEVEL,void(this.startFragRequested=!1);var d=a.len,u=this.getMaxBufferLength(n.maxBitrate);if(!(d>=u)){this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:a.end,f=this.getNextFragment(c,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&re(f)&&this.fragmentTracker.getState(f)!==ni.OK){var g,m=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,p=h.fragments[m-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var v=this.audioOnly&&!this.altAudio?te.AUDIO:te.VIDEO,y=(v===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,v,N.MAIN)}f=this.getNextFragmentLoopLoading(f,h,a,N.MAIN,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}}}}}},i.loadFragment=function(t,i,r){var s=this.fragmentTracker.getState(t);s===ni.NOT_LOADED||s===ni.PARTIAL?re(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,i)):e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i):this.clearTrackerIfNeeded(t)},i.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,N.MAIN)},i.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);var s=this.getLevelDetails();if(null!=s&&s.live){var n=this.getMainFwdBufferInfo();if(!n||n.len<2*s.targetduration)return}if(!t.paused&&e){var a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;i=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(t.currentTime+i);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var d=h.maxStartPTS?h.maxStartPTS:h.start,u=h.duration,c=Math.max(l.end,d+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Zr.KEY_LOADING:case Zr.FRAG_LOADING:case Zr.FRAG_LOADING_WAITING_RETRY:case Zr.PARSING:case Zr.PARSED:this.state=Zr.IDLE}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(t,i){e.prototype.flushMainBuffer.call(this,t,i,2===this.altAudio?"video":null)},i.onMediaAttached=function(t,i){e.prototype.onMediaAttached.call(this,t,i);var r=i.media;zo(r,"playing",this.onMediaPlaying),zo(r,"seeked",this.onMediaSeeked)},i.onMediaDetaching=function(t,i){var r=this.media;r&&(Jo(r,"playing",this.onMediaPlaying),Jo(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,i),i.transferMedia||(this._hasEnoughToStart=!1)},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(M.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},i.onManifestParsed=function(e,t){var i=!1,r=!1;t.levels.forEach((function(e){var t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),r=r||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!Jh(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1},i.onLevelLoading=function(e,t){if(this.levels&&this.state===Zr.IDLE){var i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Zr.WAITING_LEVEL)}},i.onLevelLoaded=function(e,t){var i,r=this.levels,s=this.startFragRequested,n=t.level,a=t.details,o=a.totalduration;if(r){this.log("Level "+n+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+", cc ["+a.startCC+", "+a.endCC+"] duration:"+o);var l=t.levelInfo,h=this.fragCurrent;!h||this.state!==Zr.FRAG_LOADING&&this.state!==Zr.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();var d=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,d),this.hls.trigger(M.LEVEL_UPDATED,{details:a,level:n}),this.state===Zr.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=Zr.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+n)},i.synchronizeToLiveEdge=function(e){var t=this.config,i=this.media;if(i){var r=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&i.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState&&(this.warn("Playback: "+s.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+r.toFixed(3)),i.currentTime=r))}}},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,s=e.payload,n=this.levels;if(n){var a=n[i.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+i.sn+" of level "+i.level+" after level details were reset"),void this.fragmentTracker.removeFragment(i);var l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=i.initSegment)?void 0:t.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new pa(this.hls,N.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Ii(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];c.push(s,d,u,l,i,r,o.totalduration,h,m,p)}else this.warn("Level "+i.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i.onAudioTrackSwitching=function(e,t){var i=this,r=this.hls,s=2===this.altAudio;if(Bt(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),r.once(M.BUFFER_FLUSHED,(function(){var e;null==(e=i.hls)||e.trigger(M.AUDIO_TRACK_SWITCHED,t)})),void r.trigger(M.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(M.AUDIO_TRACK_SWITCHED,t)}},i.onAudioTrackSwitched=function(e,t){var i=Bt(t.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()},i.onBufferCreated=function(e,t){var i,r,s=t.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(r=a,i=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log("Alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,s=i.type===N.MAIN;if(s){if(this.fragContextChanged(i))return this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Zr.PARSED&&(this.state=Zr.IDLE));var n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),re(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var a=this.media;a&&(!this._hasEnoughToStart&&ki.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())},i.onError=function(e,t){var i;if(t.fatal)this.state=Zr.ERROR;else switch(t.details){case O.FRAG_GAP:case O.FRAG_PARSING_ERROR:case O.FRAG_DECRYPT_ERROR:case O.FRAG_LOAD_ERROR:case O.FRAG_LOAD_TIMEOUT:case O.KEY_LOAD_ERROR:case O.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.MAIN,t);break;case O.LEVEL_LOAD_ERROR:case O.LEVEL_LOAD_TIMEOUT:case O.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Zr.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==F.LEVEL||(this.state=Zr.IDLE);break;case O.BUFFER_ADD_CODEC_ERROR:case O.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case O.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case O.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},i.onFragLoadEmergencyAborted=function(){this.state=Zr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==te.AUDIO||!this.altAudio){var r=(i===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,N.MAIN),this.tick())}},i.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log("could not seek to "+i+", already seeking at "+t);var r=this.timelineOffset;r&&i&&(i+=r);var s=this.getLevelDetails(),n=ki.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0))&&(this.log("adjusting start position by "+o+" to match buffer start"),i+=o,this.startPosition=i),t<i&&(this.log("seek to target start position "+i+" from current time "+t+" buffer start "+a),e.currentTime=i)}}},i._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t},i._loadBitrateTestFrag=function(e,t){var i=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var r=i.hls,s=null==e?void 0:e.frag;if(s&&!i.fragContextChanged(s)){t.fragmentError=0,i.state=Zr.IDLE,i.startFragRequested=!1,i.bitrateTest=!1;var n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(M.FRAG_LOADED,e),s.bitrateTest=!1}}))},i._handleTransmuxComplete=function(e){var t,i=this.playlistType,r=this.hls,s=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var o=a.frag,l=a.part,h=a.level,d=s.video,u=s.text,c=s.id3,f=s.initSegment,g=h.details,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Zr.PARSING,f){if(null!=f&&f.tracks){var p=o.initSegment||o;this._bufferInitSegment(h,f.tracks,p,n),r.trigger(M.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:f.tracks})}var v=f.initPTS,y=f.timescale;P(v)&&(this.initPTS[o.cc]={baseTime:v,timescale:y},r.trigger(M.INIT_PTS_FOUND,{frag:o,id:i,initPTS:v,timescale:y}))}if(d&&g){m&&"audiovideo"===d.type&&this.logMuxedErr(o);var E=g.fragments[o.sn-1-g.startSN],T=o.sn===g.startSN,S=!E||o.cc>E.cc;if(!1!==s.independent){var A=d.startPTS,L=d.endPTS,R=d.startDTS,I=d.endDTS;if(l)l.elementaryStreams[d.type]={startPTS:A,endPTS:L,startDTS:R,endDTS:I};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!S&&(this.couldBacktrack=!0),d.dropped&&d.independent){var b=this.getMainFwdBufferInfo(),D=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,k=d.firstKeyFramePTS?d.firstKeyFramePTS:A;if(!T&&D<k-this.config.maxBufferHole&&!S)return void this.backtrack(o);S&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,L,o.start,I,!0)}else T&&A-(g.appliedTimelineOffset||0)>xh&&(o.gap=!0);o.setElementaryStreamInfo(d.type,A,L,R,I),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,T||S)}else{if(!T&&!S)return void this.backtrack(o);o.gap=!0}}if(m){var _=m.startPTS,C=m.endPTS,w=m.startDTS,x=m.endDTS;l&&(l.elementaryStreams[te.AUDIO]={startPTS:_,endPTS:C,startDTS:w,endDTS:x}),o.setElementaryStreamInfo(te.AUDIO,_,C,w,x),this.bufferFragmentData(m,o,l,n)}if(g&&null!=c&&null!=(t=c.samples)&&t.length){var O={id:i,frag:o,details:g,samples:c.samples};r.trigger(M.FRAG_PARSING_METADATA,O)}if(g&&u){var F={id:i,frag:o,details:g,samples:u.samples};r.trigger(M.FRAG_PARSING_USERDATA,F)}}}else this.resetWhenMissingContext(n)},i.logMuxedErr=function(e){this.warn((re(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},i._bufferInitSegment=function(e,t,i,r){var s=this;if(this.state===Zr.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));var n=t.audio,a=t.video,o=t.audiovideo;if(n){var l=rt(n.codec,e.audioCodec);"mp4a"===l&&(l="mp4a.40.5");var h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=n.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&-1===h.indexOf("firefox")&&(l="mp4a.40.5")}l&&-1!==l.indexOf("mp4a.40.5")&&-1!==h.indexOf("android")&&"audio/mpeg"!==n.container&&(l="mp4a.40.2",this.log("Android: force audio codec to "+l)),e.audioCodec&&e.audioCodec!==l&&this.log('Swapping manifest audio codec "'+e.audioCodec+'" for "'+l+'"'),n.levelCodec=l,n.id=N.MAIN,this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(e.audioCodec||"")+"/"+n.codec+"]"),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=N.MAIN;var u=a.codec;if(4===(null==u?void 0:u.length))switch(u){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e"}this.log("Init video buffer, container:"+a.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+u+"]"+(a.codec!==u?" parsed-corrected="+a.codec:"")+(a.supplemental?" supplemental="+a.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),delete t.video,delete t.audio);var c=Object.keys(t);if(c.length){if(this.hls.trigger(M.BUFFER_CODECS,t),!this.hls)return;c.forEach((function(e){var n=t[e].initSegment;null!=n&&n.byteLength&&s.hls.trigger(M.BUFFER_APPENDING,{type:e,data:n,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}},i.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,N.MAIN)},i.backtrack=function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Zr.IDLE},i.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var i=e.currentTime;if(ki.isBuffered(e,i)?t=this.getAppendedFrag(i):ki.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;var r=this.fragPlaying,s=t.level;r&&t.sn===r.sn&&r.level===s||(this.fragPlaying=t,this.hls.trigger(M.FRAG_CHANGED,{frag:t}),r&&r.level===s||this.hls.trigger(M.LEVEL_SWITCHED,{level:s}))}}},n(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return P(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(P(t)){var i=this.getLevelDetails(),r=this.currentFrag||(i?Vt(null,i.fragments,t):null);if(r){var s=r.programDateTime;if(null!==s){var n=s+1e3*(t-r.start);return new Date(n)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(es),td=function(){function e(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}var t=e.prototype;return t.abort=function(e){for(var t in this.keyUriToKeyInfo){var i=this.keyUriToKeyInfo[t].loader;if(i){var r;if(e&&e!==(null==(r=i.context)?void 0:r.frag.type))return;i.abort()}}},t.detach=function(){for(var e in this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}},t.destroy=function(){for(var e in this.detach(),this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}},t.createKeyLoadError=function(e,t,i,r,s){return void 0===t&&(t=O.KEY_LOAD_ERROR),new Li({type:x.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})},t.loadClear=function(e,t){var i=this;if(this.emeController&&this.config.emeEnabled)for(var r=e.sn,s=e.cc,n=function(){var e=t[a];if(s<=e.cc&&("initSegment"===r||"initSegment"===e.sn||r<e.sn))return i.emeController.selectKeySystemFormat(e).then((function(t){e.setKeyFormat(t)})),1},a=0;a<t.length&&!n();a++);},t.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(i){return t.loadInternal(e,i)})):this.loadInternal(e)},t.loadInternal=function(e,t){var i,r;t&&e.setKeyFormat(t);var s=e.decryptdata;if(!s){var n=new Error(t?"Expected frag.decryptdata to be defined after setting format "+t:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,O.KEY_LOAD_ERROR,n))}var a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,O.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+a+'"')));var o,l=this.keyUriToKeyInfo[a];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(null!=(r=l)&&r.keyLoadPromise)switch(null==(o=l.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return l.keyLoadPromise.then((function(t){return s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:l}}))}switch(l=this.keyUriToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,O.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+s.method+'"')))}},t.loadKeyEME=function(e,t){var i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then((function(t){return e.mediaKeySessionContext=t,i}))).catch((function(t){throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)},t.loadKeyHTTP=function(e,t){var i=this,r=this.config,s=new(0,r.loader)(r);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((function(n,a){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,t,r,s){var o=r.frag,l=r.keyInfo,h=r.url;if(!o.decryptdata||l!==i.keyUriToKeyInfo[h])return a(i.createKeyLoadError(o,O.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,n({frag:o,keyInfo:l})},onError:function(e,r,s,n){i.resetLoader(r),a(i.createKeyLoadError(t,O.KEY_LOAD_ERROR,new Error("HTTP Error "+e.code+" loading key "+e.text),s,g({url:o.url,data:void 0},e)))},onTimeout:function(e,r,s){i.resetLoader(r),a(i.createKeyLoadError(t,O.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:function(e,r,s){i.resetLoader(r),a(i.createKeyLoadError(t,O.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,h,d)}))},t.resetLoader=function(e){var t=e.frag,i=e.keyInfo,r=e.url,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()},e}();function id(e){switch(e.type){case F.AUDIO_TRACK:return N.AUDIO;case F.SUBTITLE_TRACK:return N.SUBTITLE;default:return N.MAIN}}function rd(e,t){var i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}var sd=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_LOADING,this.onLevelLoading,this),e.on(M.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(M.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_LOADING,this.onLevelLoading,this),e.off(M.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(M.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.createInternalLoader=function(e){var t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var i=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:F.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var i=t.id,r=t.level,s=t.pathwayId,n=t.url,a=t.deliveryDirectives,o=t.levelInfo;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:F.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var i=t.id,r=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:F.AUDIO_TRACK,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onSubtitleTrackLoading=function(e,t){var i=t.id,r=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:F.SUBTITLE_TRACK,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onLevelsUpdated=function(e,t){var i=this.loaders[F.LEVEL];if(i){var r=i.context;r&&!t.levels.some((function(e){return e===r.levelOrTrack}))&&(i.abort(),delete this.loaders[F.LEVEL])}},t.load=function(e){var t,i,r,s=this,n=this.hls.config,a=this.getInternalLoader(e);if(a){var o=this.hls.logger,h=a.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives))return void(h.url===e.url?o.log("[playlist-loader]: ignore "+e.url+" ongoing request"):o.log("[playlist-loader]: ignore "+e.url+" in favor of "+h.url));o.log("[playlist-loader]: aborting previous loader for type: "+e.type),a.abort()}if(i=e.type===F.MANIFEST?n.manifestLoadPolicy.default:l({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(e),P(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===F.LEVEL&&null!==e.level?r=this.hls.levels[e.level].details:e.type===F.AUDIO_TRACK&&null!==e.id?r=this.hls.audioTracks[e.id].details:e.type===F.SUBTITLE_TRACK&&null!==e.id&&(r=this.hls.subtitleTracks[e.id].details),r)){var d=r.partTarget,u=r.targetduration;if(d&&u){var c=1e3*Math.max(3*d,.8*u);i=l({},i,{maxTimeToFirstByteMs:Math.min(c,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,i.maxTimeToFirstByteMs)})}}var f=i.errorRetry||i.timeoutRetry||{},g={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},m={onSuccess:function(e,t,i,r){var n=s.getInternalLoader(i);s.resetInternalLoader(i.type);var a=e.data;0===a.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),yr.isMediaPlaylist(a)||i.type!==F.MANIFEST?s.handleTrackOrLevelPlaylist(e,t,i,r||null,n):s.handleMasterPlaylist(e,t,i,r)):s.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:function(e,t,i,r){s.handleNetworkError(t,i,!1,e,r)},onTimeout:function(e,t,i){s.handleNetworkError(t,i,!0,void 0,e)}};a.load(e,g,m)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,i=t.autoStartLoad,r=t.startPosition,s=e.forceStartLoad;(i||s)&&(this.hls.logger.log((i?"auto":"force")+" startLoad with configured startPosition "+r),this.hls.startLoad(r))}},t.handleMasterPlaylist=function(e,t,i,r){var s=this.hls,n=e.data,a=rd(e,i),o=yr.parseMasterPlaylist(n,a);if(o.playlistParsingError)this.handleManifestParsingError(e,i,o.playlistParsingError,r,t);else{var l=o.contentSteering,h=o.levels,d=o.sessionData,u=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=yr.parseMasterPlaylistMedia(n,a,o),m=g.AUDIO,p=void 0===m?[]:m,v=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];p.length&&(p.some((function(e){return!e.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Fi({}),bitrate:0,url:""}))),s.trigger(M.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:v,captions:y,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f})}},t.handleTrackOrLevelPlaylist=function(e,t,i,r,s){var n=this.hls,a=i.id,o=i.level,l=i.type,h=rd(e,i),d=P(o)?o:P(a)?a:0,u=id(i),c=yr.parseLevelPlaylist(e.data,h,d,u,0,this.variableList);if(l===F.MANIFEST){var f={attrs:new Fi({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+Gr(c,0),n.trigger(M.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,r,s)},t.handleManifestParsingError=function(e,t,i,r,s){this.hls.trigger(M.ERROR,{type:x.NETWORK_ERROR,details:O.MANIFEST_PARSING_ERROR,fatal:t.type===F.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})},t.handleNetworkError=function(e,t,i,r,s){void 0===i&&(i=!1);var n="A network "+(i?"timeout":"error"+(r?" (status "+r.code+")":""))+" occurred while loading "+e.type;e.type===F.LEVEL?n+=": "+e.level+" id: "+e.id:e.type!==F.AUDIO_TRACK&&e.type!==F.SUBTITLE_TRACK||(n+=" id: "+e.id+' group-id: "'+e.groupId+'"');var a=new Error(n);this.hls.logger.warn("[playlist-loader]: "+n);var o=O.UNKNOWN,l=!1,h=this.getInternalLoader(e);switch(e.type){case F.MANIFEST:o=i?O.MANIFEST_LOAD_TIMEOUT:O.MANIFEST_LOAD_ERROR,l=!0;break;case F.LEVEL:o=i?O.LEVEL_LOAD_TIMEOUT:O.LEVEL_LOAD_ERROR,l=!1;break;case F.AUDIO_TRACK:o=i?O.AUDIO_TRACK_LOAD_TIMEOUT:O.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case F.SUBTITLE_TRACK:o=i?O.SUBTITLE_TRACK_LOAD_TIMEOUT:O.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);var d={type:x.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){var u=(null==t?void 0:t.url)||e.url;d.response=g({url:u,data:void 0},r)}this.hls.trigger(M.ERROR,d)},t.handlePlaylistLoaded=function(e,t,i,r,s,n){var a=this.hls,o=r.type,l=r.level,h=r.id,d=r.groupId,u=r.deliveryDirectives,c=rd(t,r),f=id(r),g="number"==typeof r.level&&f===N.MAIN?l:void 0;if(e.fragments.length){e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));var m=e.playlistParsingError;if(m){if(this.hls.logger.warn(m),!a.config.ignorePlaylistParsingErrors)return void a.trigger(M.ERROR,{type:x.NETWORK_ERROR,details:O.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i});e.playlistParsingError=null}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case F.MANIFEST:case F.LEVEL:a.trigger(M.LEVEL_LOADED,{details:e,levelInfo:r.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:u,withoutMultiVariant:o===F.MANIFEST});break;case F.AUDIO_TRACK:a.trigger(M.AUDIO_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u});break;case F.SUBTITLE_TRACK:a.trigger(M.SUBTITLE_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u})}}else{var p=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(M.ERROR,{type:x.NETWORK_ERROR,details:O.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i})}},e}(),nd=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new b,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var i=this.logger=j(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=Ph(e.DefaultConfig,t,i);this.userConfig=t,r.progressive&&wh(r,i);var s=r.abrController,n=r.bufferController,a=r.capLevelController,o=r.errorController,l=r.fpsController,h=new o(this),d=this.abrController=new s(this),u=new ai(this),c=r.interstitialsController,f=c?this.interstitialsController=new c(this,e):null,g=this.bufferController=new n(this,u),m=this.capLevelController=new a(this),p=new l(this),v=new sd(this),y=r.contentSteeringController,E=y?new y(this):null,T=this.levelController=new jh(this,E),S=new Yh(this),A=new td(this.config),L=this.streamController=new ed(this,u,A),R=this.gapController=new Nh(this,u);m.setStreamController(L),p.setStreamController(L);var I=[v,T,L];f&&I.splice(1,0,f),E&&I.splice(1,0,E),this.networkControllers=I;var D=[d,g,R,m,p,S,u];this.audioTrackController=this.createController(r.audioTrackController,I);var k=r.audioStreamController;k&&I.push(this.audioStreamController=new k(this,u,A)),this.subtitleTrackController=this.createController(r.subtitleTrackController,I);var _=r.subtitleStreamController;_&&I.push(this.subtititleStreamController=new _(this,u,A)),this.createController(r.timelineController,D),A.emeController=this.emeController=this.createController(r.emeController,D),this.cmcdController=this.createController(r.cmcdController,D),this.latencyController=this.createController(Wh,D),this.coreComponents=D,I.push(h);var P=h.onErrorOut;"function"==typeof P&&this.on(M.ERROR,P,h),this.on(M.MANIFEST_LOADED,v.onManifestLoaded,v)}e.isMSESupported=function(){return Qh()},e.isSupported=function(){return zh()},e.getMediaSource=function(){return X()};var t=e.prototype;return t.createController=function(e,t){if(e){var i=new e(this);return t&&t.push(i),i}return null},t.on=function(e,t,i){void 0===i&&(i=this),this._emitter.on(e,t,i)},t.once=function(e,t,i){void 0===i&&(i=this),this._emitter.once(e,t,i)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,i,r){void 0===i&&(i=this),this._emitter.off(e,t,i,r)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,i){return this._emitter.emit(e,t,i)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var i=e===M.ERROR;this.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(M.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument ("+e+")");this.trigger(M.ERROR,{type:x.OTHER_ERROR,details:O.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var i="media"in e,r=i?e.media:e,s=i?e:{media:r};this._media=r,this.trigger(M.MEDIA_ATTACHING,s)}},t.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(M.MEDIA_DETACHING,{}),this._media=null},t.transferMedia=function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(M.MEDIA_DETACHING,{transferMedia:e}),e},t.loadSource=function(e){this.stopLoad();var t=this.media,i=this._url,r=this._url=_.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+r),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(M.MANIFEST_LOADING,{url:e})},t.startLoad=function(e,t){void 0===e&&(e=-1),this.logger.log("startLoad("+e+(t?", <skip seek to start>":"")+")"),this.started=!0,this.resumeBuffering();for(var i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);},t.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);},t.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((function(e){e.resumeBuffering&&e.resumeBuffering()})))},t.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((function(e){e.pauseBuffering&&e.pauseBuffering()})))},t.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null},t.setSubtitleOption=function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null},t.getMediaDecodingInfo=function(e,t){return void 0===t&&(t=this.allAudioTracks),ct(e,_t(t),navigator.mediaCapabilities)},n(e,[{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"inFlightFragments",get:function(){var e,t=((e={})[N.MAIN]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[N.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[N.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=T()),e}},{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){mt(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var i=e.length,r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(var s=e;s--;){var n=t[s].attrs["HDCP-LEVEL"];if(n&&n<=r)return s}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(e){this.latencyController.targetLatency=e}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}}],[{key:"version",get:function(){return ha}},{key:"Events",get:function(){return M}},{key:"MetadataSchema",get:function(){return $s}},{key:"ErrorTypes",get:function(){return x}},{key:"ErrorDetails",get:function(){return O}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:kh},set:function(t){e.defaultConfig=t}}])}();return nd.defaultConfig=void 0,nd}()}(!1)}}]);